From norman at khine.net Mon Feb 1 00:43:59 2010 From: norman at khine.net (Norman Khine) Date: Mon, 1 Feb 2010 00:43:59 +0100 Subject: [Tutor] parse text file In-Reply-To: <20100123005017.7532df62@o> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> Message-ID: <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> Hello, I am still unable to get this to work correctly! In [1]: file=open('producers_google_map_code.txt', 'r') In [2]: data = repr( file.read().decode('utf-8') ) In [3]: from BeautifulSoup import BeautifulStoneSoup In [4]: soup = BeautifulStoneSoup(data) In [6]: soup http://paste.lisp.org/display/94195 In [7]: import re In [8]: p = re.compile(r"""GLatLng\((\d+\.\d*)\, \n (\d+\.\d*)\)""") In [9]: r = p.findall(data) In [10]: r Out[10]: [] see http://paste.lisp.org/+20BO/1 i can't seem to get the regex correct (r"""GLatLng\((\d+\.\d*)\, \n (\d+\.\d*)\)""") the problem is that, each for example is: GLatLng(27.729912,\\n 85.31559) GLatLng(-18.889851,\\n -66.770897) i have a big whitespace, plus the group can have a negative value, so if i do this: In [31]: p = re.compile(r"""GLatLng\((\d+\.\d*)\,\\n (\d+\.\d*)\)""") In [32]: r = p.findall(data) In [33]: r Out[33]: [('27.729912', '85.31559'), ('9.696333', '122.985992'), ('17.964625', '102.60040'), ('21.046439', '105.853043'), but this does not take into account of data which has negative values, also i am unsure how to pull it all together. i.e. to return a CSV file such as: "ACP", "acp.html", "9.696333", "122.985992" "ALTER TRADE CORPORATION", "alter-trade-corporation.html", "-18.889851", "-66.770897" Thanks On Sat, Jan 23, 2010 at 12:50 AM, spir wrote: > On Sat, 23 Jan 2010 00:22:41 +0100 > Norman Khine wrote: > >> Hi >> >> On Fri, Jan 22, 2010 at 7:44 PM, spir wrote: >> > On Fri, 22 Jan 2010 14:11:42 +0100 >> > Norman Khine wrote: >> > >> >> but my problem comes when i try to list the GLatLng: >> >> >> >> GLatLng(9.696333, 122.985992); >> >> >> >> >>> StartingWithGLatLng = soup.findAll(re.compile('GLatLng')) >> >> >>> StartingWithGLatLng >> >> [] >> > >> > Don't about soup's findall. But the regex pattern string should rather be something like (untested): >> > ? r"""GLatLng\(\(d+\.\d*)\, (d+\.\d*)\) """ >> > capturing both integers. >> > >> > Denis >> > >> > PS: finally tested: >> > >> > import re >> > s = "GLatLng(9.696333, 122.985992)" >> > p = re.compile(r"""GLatLng\((\d+\.\d*)\, (\d+\.\d*)\)""") >> > r = p.match(s) >> > print r.group() ? ? ? ? # --> GLatLng(9.696333, 122.985992) >> > print r.groups() ? ? ? ?# --> ('9.696333', '122.985992') >> > >> > s = "xGLatLng(1.1, 11.22)xxxGLatLng(111.111, 1111.2222)x" >> > r = p.findall(s) >> > print r ? ? ? ? ? ? ? ? ? ? ? ? # --> [('1.1', '11.22'), ('111.111', '1111.2222')] >> >> Thanks for the help, but I can't seem to get the RegEx to work correctly. >> >> Here is my input and output: >> >> http://paste.lisp.org/+20BO/1 > > See my previous examples... > If you use match: > > In [6]: r = p.match(data) > > Then the result is a regex match object (unlike when using findall). To get the string(s) matched; you need to use the group() and/or groups() methods. > >>>> import re >>>> p = re.compile('x') >>>> print p.match("xabcx") > <_sre.SRE_Match object at 0xb74de6e8> >>>> print p.findall("xabcx") > ['x', 'x'] > > Denis > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ > From amonroe at columbus.rr.com Mon Feb 1 01:04:10 2010 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 31 Jan 2010 19:04:10 -0500 Subject: [Tutor] query In-Reply-To: References: <903803.75117.qm@web45304.mail.sp1.yahoo.com>,, <1264969877.8709.15.camel@opteron.dwabbott.com>,, , , <1264974598.17460.9.camel@dedal-laptop> Message-ID: <118709992455.20100131190410@columbus.rr.com> > i just don wana index all the characters rather i wana double it too like > ['d','a','v','i','d'] > would b > ['d','dd','a','aa','v','vv','i','ii','d','dd'] > and then i wana replace all non 'd' characters with '.' a dot > i know how replace a specific character, but i don know how to > replace all characters other than a specific character Hint 1: a FOR loop will help you count your way through lists one at a time. Let the computer do the counting for you. Hint 2: learn about IF statements to replace characters IF they're not a d, for example. Alan From transmogribenno at gmail.com Mon Feb 1 03:56:34 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Mon, 1 Feb 2010 11:56:34 +0900 Subject: [Tutor] can any one help In-Reply-To: References: <1264893675.6587.29.camel@dedal-laptop> <1264894841.6587.39.camel@dedal-laptop> <4681047264.20100131110119@columbus.rr.com> Message-ID: <9b00d1a91001311856i6f57658el2c9bc2f98f70de90@mail.gmail.com> On Mon, Feb 1, 2010 at 6:27 AM, invincible patriot wrote: > thanks for the reply > i did one question > i will tel u my progress in another question n then u tel me that what next > must be done > thatz the question > i think that first i woulf take a string 'foobar' > convert it into a list > take itz length > n then do indexing > and then multiply using for loop > > herez my code > thatz where i am > now i wana do the indexing of each character so that i use for loop n > multply each character with 2 > > > waiting for ur reply Hi there, I think everyone on the list would appreciate it if you wrote in English, not gibberish. Regards, benno. From cabbagetreecustard at gmail.com Mon Feb 1 05:08:34 2010 From: cabbagetreecustard at gmail.com (Victoria Wood) Date: Mon, 1 Feb 2010 17:08:34 +1300 Subject: [Tutor] python and sqlite Message-ID: Hi, I am very new to Python myself and decided to use sqlite so I could learn about gui programming. Although it has a lot of adverts on and is short I found this tutorial very useful http://www.devshed.com/c/a/Python/Using-SQLite-in-Python/ I hope I have replied to this correctly. Victoria On Sun, Jan 31, 2010 at 11:03 AM, Samuel de Champlain < samueldechamplain at gmail.com> wrote: > My project is relatively light and postgresql or mysql might be overkill. > Does python work well with sqlite? > If so, can you point me towards the proper libraries and manuals/tutorials? > Thanks. > > ______________________________ _________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From johann.spies at gmail.com Mon Feb 1 06:55:12 2010 From: johann.spies at gmail.com (Johann Spies) Date: Mon, 1 Feb 2010 07:55:12 +0200 Subject: [Tutor] Deterimining the maximum length of a field in csv file Message-ID: <80421a1b1001312155s188b850apdffd09365ff99ce5@mail.gmail.com> I would appreciate some help on this: I want a script that can 1. determine the fieldnames from a csv file from the first line 2. determine the maximum length of data for each field in that file. So far I could not figure out how to do 1 and my effort for the second one is not working as expected. Here is my present code: reader = csv.DictReader(open("/media/usb0/kbase/web2py/db_scopus_rou.csv"),delimiter = ',') csv.field_size_limit(1000000) reader.fieldnames = ["scopus_rou.id","scopus_rou.Authors","scopus_rou.Title", "scopus_rou.Year","scopus_rou.Source_title","scopus_rou.Volume", "scopus_rou.Issue","scopus_rou.Art_No","scopus_rou.Page_start", "scopus_rou.Page_end","scopus_rou.Page_count","scopus_rou.Cited_by", "scopus_rou.Link","scopus_rou.Affiliations", "scopus_rou.Authors_with_affiliations","scopus_rou.Abstract", "scopus_rou.Author_Keywords","scopus_rou.Index_Keywords", "scopus_rou.Molecular_Sequence_Numbers","scopus_rou.Chemicals_CAS", "scopus_rou.Tradenames","scopus_rou.Manufacturers", "scopus_rou.Funding_Details","scopus_rou.Refs", "scopus_rou.Correspondence_Address","scopus_rou.Editors", "scopus_rou.Sponsors","scopus_rou.Publisher", "scopus_rou.Conference_name","scopus_rou.Conference_date", "scopus_rou.Conference_location","scopus_rou.Conference_code", "scopus_rou.ISSN","scopus_rou.ISBN","scopus_rou.CODEN", "scopus_rou.DOI","scopus_rou.Pubmed_ID","scopus_rou.Language", "scopus_rou.Abbreviated_Source_Title","scopus_rou.Document_Type", "scopus_rou.Source"] maksimum = { "scopus_rou.id":0,"scopus_rou.Authors":0,"scopus_rou.Title":0, "scopus_rou.Year":0,"scopus_rou.Source_title":0,"scopus_rou.Volume":0, "scopus_rou.Issue":0,"scopus_rou.Art_No":0,"scopus_rou.Page_start":0, "scopus_rou.Page_end":0,"scopus_rou.Page_count":0,"scopus_rou.Cited_by":0, "scopus_rou.Link":0,"scopus_rou.Affiliations":0, "scopus_rou.Authors_with_affiliations":0,"scopus_rou.Abstract":0, "scopus_rou.Author_Keywords":0,"scopus_rou.Index_Keywords":0, "scopus_rou.Molecular_Sequence_Numbers":0,"scopus_rou.Chemicals_CAS":0, "scopus_rou.Tradenames":0,"scopus_rou.Manufacturers":0, "scopus_rou.Funding_Details":0,"scopus_rou.Refs":0, "scopus_rou.Correspondence_Address":0,"scopus_rou.Editors":0, "scopus_rou.Sponsors":0,"scopus_rou.Publisher":0, "scopus_rou.Conference_name":0,"scopus_rou.Conference_date":0, "scopus_rou.Conference_location":0,"scopus_rou.Conference_code":0, "scopus_rou.ISSN":0,"scopus_rou.ISBN":0,"scopus_rou.CODEN":0, "scopus_rou.DOI":0,"scopus_rou.Pubmed_ID":0,"scopus_rou.Language":0, "scopus_rou.Abbreviated_Source_Title":0,"scopus_rou.Document_Type":0, "scopus_rou.Source":0} ry = 0 try: for row in reader: ry = ry + 1 for k in reader.fieldnames: try: lengte = len(row[k].strip()) except: lengte = 0 if k in maksimum: if lengte > maksimum[k]: maksimum[k]= lengte else: maksimum[k] = lengte print maksimum except: pass for l in maksimum.keys: print ("%s: %d\n" % (l, maksimum(l))) Regards Johann From samueldechamplain at gmail.com Mon Feb 1 08:48:14 2010 From: samueldechamplain at gmail.com (Samuel de Champlain) Date: Mon, 1 Feb 2010 02:48:14 -0500 Subject: [Tutor] python and sqlite In-Reply-To: References: Message-ID: <10cd5a2c1001312348r4074465cl71e7c18acd719ab5@mail.gmail.com> Thank you. I will read it next. Here is another short one that I found: http://www.wdvl.com/Authoring/python/SQLite/Watts07162009.html If anyone knows of other tutorials on python and sqlite, please tell me of them. On Sun, Jan 31, 2010 at 11:08 PM, Victoria Wood < cabbagetreecustard at gmail.com> wrote: > Hi, I am very new to Python myself and decided to use sqlite so I could > learn about gui programming. Although it has a lot of adverts on and is > short I found this tutorial very useful > > http://www.devshed.com/c/a/Python/Using-SQLite-in-Python/ > > I hope I have replied to this correctly. > > Victoria > > On Sun, Jan 31, 2010 at 11:03 AM, Samuel de Champlain < > samueldechamplain at gmail.com> wrote: > > > My project is relatively light and postgresql or mysql might be overkill. > > Does python work well with sqlite? > > If so, can you point me towards the proper libraries and > manuals/tutorials? > > Thanks. > > > > ______________________________ > _________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 1 09:34:09 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Feb 2010 08:34:09 -0000 Subject: [Tutor] python and sqlite References: <10cd5a2c1001312348r4074465cl71e7c18acd719ab5@mail.gmail.com> Message-ID: "Samuel de Champlain" wrote > Here is another short one that I found: > http://www.wdvl.com/Authoring/python/SQLite/Watts07162009.html > If anyone knows of other tutorials on python and sqlite, please tell me > of > them. The databases topic in my tutorial uses SQLite as its database engine. (Only in the v2 tutor so far) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From denis.spir at free.fr Mon Feb 1 10:57:24 2010 From: denis.spir at free.fr (spir) Date: Mon, 1 Feb 2010 10:57:24 +0100 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> Message-ID: <20100201105724.6c3e3af6@o> On Mon, 1 Feb 2010 00:43:59 +0100 Norman Khine wrote: > but this does not take into account of data which has negative values just add \-? in front of \d+ Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From norman at khine.net Mon Feb 1 12:29:44 2010 From: norman at khine.net (Norman Khine) Date: Mon, 1 Feb 2010 12:29:44 +0100 Subject: [Tutor] parse text file In-Reply-To: <20100201105724.6c3e3af6@o> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> Message-ID: <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> On Mon, Feb 1, 2010 at 10:57 AM, spir wrote: > On Mon, 1 Feb 2010 00:43:59 +0100 > Norman Khine wrote: > >> but this does not take into account of data which has negative values > > just add \-? in front of \d+ thanks, what about the whitespace problem? > > Denis > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From DE0001UN at ntu.edu.sg Mon Feb 1 09:46:36 2010 From: DE0001UN at ntu.edu.sg (#DENG JUN#) Date: Mon, 1 Feb 2010 16:46:36 +0800 Subject: [Tutor] One question related to installation of Spyder Message-ID: <253C84E92C975749A448F4BC90DBAE2107DFC462@MAIL21.student.main.ntu.edu.sg> To those it may concern: Hi, I got a problem with installing Spyder. By the way, my desktop is of windows system. I know that before installing Spyder, I first have to equip my computer with PyQt4.x(x>=4), QScintilla (x>=1) and Python2.5 (and upper). Do you have any release of QScintilla in .exe form? I failed to find the detailed instruction about how to install with the source file. Best, DENG JUN -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Feb 1 13:19:15 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 1 Feb 2010 07:19:15 -0500 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> Message-ID: <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> On Mon, Feb 1, 2010 at 6:29 AM, Norman Khine wrote: > thanks, what about the whitespace problem? \s* will match any amount of whitespace includin newlines. Kent From norman at khine.net Mon Feb 1 16:30:02 2010 From: norman at khine.net (Norman Khine) Date: Mon, 1 Feb 2010 16:30:02 +0100 Subject: [Tutor] parse text file In-Reply-To: <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> Message-ID: <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> On Mon, Feb 1, 2010 at 1:19 PM, Kent Johnson wrote: > On Mon, Feb 1, 2010 at 6:29 AM, Norman Khine wrote: > >> thanks, what about the whitespace problem? > > \s* will match any amount of whitespace includin newlines. thank you, this worked well. here is the code: ### import re file=open('producers_google_map_code.txt', 'r') data = repr( file.read().decode('utf-8') ) block = re.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""") b = block.findall(data) block_list = [] for html in b: namespace = {} t = re.compile(r"""(.*)<\/strong>""") title = t.findall(html) for item in title: namespace['title'] = item u = re.compile(r"""a href=\"\/(.*)\">En savoir plus""") url = u.findall(html) for item in url: namespace['url'] = item g = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""") lat = g.findall(html) for item in lat: namespace['LatLng'] = item block_list.append(namespace) ### can this be made better? > > Kent > From grigor.kolev at gmail.com Mon Feb 1 18:51:54 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Mon, 01 Feb 2010 19:51:54 +0200 Subject: [Tutor] query In-Reply-To: References: <903803.75117.qm@web45304.mail.sp1.yahoo.com> ,, <1264969877.8709.15.camel@opteron.dwabbott.com> ,, , ,<1264974598.17460.9.camel@dedal-laptop> Message-ID: <1265046714.3227.2.camel@dedal-laptop> ? 22:09 +0000 ?? 31.01.2010 (??), invincible patriot ??????: > i just don wana index all the characters rather i wana double it too > like > ['d','a','v','i','d'] > would b > ['d','dd','a','aa','v','vv','i','ii','d','dd'] > and then i wana replace all non 'd' characters with '.' a dot > > i know how replace a specific character, but i don know how to replace > all characters other than a specific character > > > thanks > > > > > Subject: Re: [Tutor] query > > From: grigor.kolev at gmail.com > > To: invincible_patriot at hotmail.com > > CC: anand.shashwat at gmail.com; david at pythontoo.com; tutor at python.org > > Date: Sun, 31 Jan 2010 23:49:58 +0200 > > > > ? 21:21 +0000 ?? 31.01.2010 (??), invincible patriot ??????: > > > Hi > > > can any one tel me how can i do indexing of individual characters > in > > > python > > > like if i hav a word eg david > > > a='david' > > > b=list(a) > > > # this will give ['d','a','v','i','d'] > > > not i want to print the index of each character > > > how can i do that > > > please tel me > > > > > > thanks > > > > > > > > > > > > > ______________________________________________________________________ > > > Hotmail: Free, trusted and rich email service. Get it now. > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > To unsubscribe or change subscription options: > > > http://mail.python.org/mailman/listinfo/tutor > > List indexed by position > > ['d','a','v','i','d'] > > 0,1,2,3,4,5 > > Can index like this > > a[1] > > You can index and string too not need to be a list > > a[1] > > if you want find position of 'a' use this > > a.find('a') > > -- > > Grigor Kolev > > > > > ______________________________________________________________________ > Hotmail: Free, trusted and rich email service. Get it now. Read this http://docs.python.org/tutorial/controlflow.html#for-statements -- Grigor Kolev From anand.shashwat at gmail.com Mon Feb 1 19:59:14 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Tue, 2 Feb 2010 00:29:14 +0530 Subject: [Tutor] Algorithm for combined area of circles Message-ID: Let there be 'n' circles (upper bound on n = 10**6) each of radius '1'. We enter their co-ordinates which are floating points and lies between (-1000, 1000). I need to find area of the resulting figure formed by intersection of circles. I came across these links : http://stackoverflow.com/questions/1667310/combined-area-of-overlapping-circles http://answers.google.com/answers/threadview?id=480288 http://mathworld.wolfram.com/Circle-CircleIntersection.html But of no avail. Can anyone point me towards right direction? :( ~Shashwat Anand From gow524 at gmail.com Mon Feb 1 20:45:25 2010 From: gow524 at gmail.com (Luis Ortega) Date: Mon, 1 Feb 2010 11:45:25 -0800 Subject: [Tutor] tracking program Message-ID: <8f69b2391002011145q5d963f2cvecd1e7b1d039a506@mail.gmail.com> Hello I am fairly new to programming (which means I have never, ever, ever written a program). I have a book or two in Python, and so far I like it. I have a stupid question to ask; Is it possible to write an employee's internet tracking program in Python? I know I have a long way before I even attempt to code, but could someone describe what the process would entail? How would my python program be able to track an employee as he surfs the net (along with capture IP & time wasted on the net). I know that there are programs that can be purchase to do what I 'm trying to accomplish. I just will like to write it my self. Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From jecarnell at saintfrancis.com Mon Feb 1 21:53:10 2010 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Mon, 1 Feb 2010 14:53:10 -0600 Subject: [Tutor] Tutor Digest, Vol 72, Issue 3 In-Reply-To: Message-ID: Let there be 'n' circles (upper bound on n = 10**6) each of radius '1'. We enter their co-ordinates which are floating points and lies between (-1000, 1000). I need to find area of the resulting figure formed by intersection of circles. I came across these links : http://stackoverflow.com/questions/1667310/combined-area-of-overlapping- circles http://answers.google.com/answers/threadview?id=480288 http://mathworld.wolfram.com/Circle-CircleIntersection.html But of no avail. Can anyone point me towards right direction? :( ~Shashwat Anand =========================== This is probably spam, but... 1) My bad answer is to render them in pygame et al and do edge detection, if overlap color pixels a different color then count pixels. Probably would have to do in parts since the area is so big. Last I knew edge detection for circles sucks... 2) My trying to be good answer but is untested and probably doesn't work (ugh) is to use an FFT on the x and y axis. Numpy has an FFT. Since they all have the same circumference then maybe you can just scan to the left and right on the X axis and on the Y axis compute the difference and the resulting intersection. Put the intersection in a lookup chart under a key value for the differences (I think you can sum the x and y difference maybe not to have less keys). At some point you could probably just interpolate your lookup chart to save time unless you need it exact as possible. Is this some kind of vision algorithm? Sincerely, Bad answer man From waynejwerner at gmail.com Mon Feb 1 22:32:22 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 1 Feb 2010 15:32:22 -0600 Subject: [Tutor] tracking program In-Reply-To: <8f69b2391002011145q5d963f2cvecd1e7b1d039a506@mail.gmail.com> References: <8f69b2391002011145q5d963f2cvecd1e7b1d039a506@mail.gmail.com> Message-ID: <333efb451002011332x27afd983x2476f65e523d57d@mail.gmail.com> On Mon, Feb 1, 2010 at 1:45 PM, Luis Ortega wrote: > Hello > > I am fairly new to programming (which means I have never, ever, ever > written a program). I have a book or two in Python, and so far I like it. > I have a stupid question to ask; Is it possible to write an employee's > internet tracking program in Python? > > I know I have a long way before I even attempt to code, but could someone > describe what the process would entail? How would my python program be able > to track an employee as he surfs the net (along with capture IP & time > wasted on the net). > > I know that there are programs that can be purchase to do what I 'm trying > to accomplish. I just will like to write it my self. You're right about having quite a while to go... but it's definitely possible. Basically, from about a 10,000' view, you would be writing a program to act as proxy between the web browser and the internet. I suppose at its most simple, you could write it with fairly few lines of code. The only thing I'm not sure on how to do is grab the outgoing connection. I presume it would require some type of loopback device, but I'm not terribly familiar with sockets/network programming. The IP part is pretty simple - a simple google search about "python resolve ip address" or something to that effect would probably get you good results. After learning a bit about program flow (i.e. writing a few programs), you could probably look up "python socket programming" and come up with some useful info. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Tue Feb 2 09:30:57 2010 From: denis.spir at free.fr (spir) Date: Tue, 2 Feb 2010 09:30:57 +0100 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> Message-ID: <20100202093057.6b48bb65@o> On Mon, 1 Feb 2010 16:30:02 +0100 Norman Khine wrote: > On Mon, Feb 1, 2010 at 1:19 PM, Kent Johnson wrote: > > On Mon, Feb 1, 2010 at 6:29 AM, Norman Khine wrote: > > > >> thanks, what about the whitespace problem? > > > > \s* will match any amount of whitespace includin newlines. > > thank you, this worked well. > > here is the code: > > ### > import re > file=open('producers_google_map_code.txt', 'r') > data = repr( file.read().decode('utf-8') ) > > block = re.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""") > b = block.findall(data) > block_list = [] > for html in b: > namespace = {} > t = re.compile(r"""(.*)<\/strong>""") > title = t.findall(html) > for item in title: > namespace['title'] = item > u = re.compile(r"""a href=\"\/(.*)\">En savoir plus""") > url = u.findall(html) > for item in url: > namespace['url'] = item > g = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""") > lat = g.findall(html) > for item in lat: > namespace['LatLng'] = item > block_list.append(namespace) > > ### > > can this be made better? The 3 regex patterns are constants: they can be put out of the loop. You may also rename b to blocks, and find a more a more accurate name for block_list; eg block_records, where record = set of (named) fields. A short desc and/or example of the overall and partial data formats can greatly help later review, since regex patterns alone are hard to decode. The def of "namespace" would be clearer imo in a single line: namespace = {title:t, url:url, lat:g} This also reveals a kind of name confusion, doesn't it? Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From sudheer.kay at gmail.com Tue Feb 2 09:38:07 2010 From: sudheer.kay at gmail.com (sudhir prasad) Date: Tue, 2 Feb 2010 14:08:07 +0530 Subject: [Tutor] callable objects Message-ID: hi, in my porgram i have two modules say module 1 and module 2,module 2 consists of two sub modules say sm1 and sm2, i run module1 ,first it calls sm1 in module 2 and a list gets updated,now i again pass the same list to sm2 in module2 but im getting an error " 'list' object is not callable" so i wrote a top module which calls module 1 and i defined the list in the top module instead of module 1,but again m getting the same error -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Tue Feb 2 10:16:15 2010 From: norman at khine.net (Norman Khine) Date: Tue, 2 Feb 2010 10:16:15 +0100 Subject: [Tutor] parse text file In-Reply-To: <20100202093057.6b48bb65@o> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> Message-ID: <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> thanks denis, On Tue, Feb 2, 2010 at 9:30 AM, spir wrote: > On Mon, 1 Feb 2010 16:30:02 +0100 > Norman Khine wrote: > >> On Mon, Feb 1, 2010 at 1:19 PM, Kent Johnson wrote: >> > On Mon, Feb 1, 2010 at 6:29 AM, Norman Khine wrote: >> > >> >> thanks, what about the whitespace problem? >> > >> > \s* will match any amount of whitespace includin newlines. >> >> thank you, this worked well. >> >> here is the code: >> >> ### >> import re >> file=open('producers_google_map_code.txt', 'r') >> data = ?repr( file.read().decode('utf-8') ) >> >> block = re.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""") >> b = block.findall(data) >> block_list = [] >> for html in b: >> ? ? ? namespace = {} >> ? ? ? t = re.compile(r"""(.*)<\/strong>""") >> ? ? ? title = t.findall(html) >> ? ? ? for item in title: >> ? ? ? ? ? ? ? namespace['title'] = item >> ? ? ? u = re.compile(r"""a href=\"\/(.*)\">En savoir plus""") >> ? ? ? url = u.findall(html) >> ? ? ? for item in url: >> ? ? ? ? ? ? ? namespace['url'] = item >> ? ? ? g = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""") >> ? ? ? lat = g.findall(html) >> ? ? ? for item in lat: >> ? ? ? ? ? ? ? namespace['LatLng'] = item >> ? ? ? block_list.append(namespace) >> >> ### >> >> can this be made better? > > The 3 regex patterns are constants: they can be put out of the loop. > > You may also rename b to blocks, and find a more a more accurate name for block_list; eg block_records, where record = set of (named) fields. > > A short desc and/or example of the overall and partial data formats can greatly help later review, since regex patterns alone are hard to decode. here are the changes: import re file=open('producers_google_map_code.txt', 'r') data = repr( file.read().decode('utf-8') ) get_record = re.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""") get_title = re.compile(r"""(.*)<\/strong>""") get_url = re.compile(r"""a href=\"\/(.*)\">En savoir plus""") get_latlng = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""") records = get_record.findall(data) block_record = [] for record in records: namespace = {} titles = get_title.findall(record) for title in titles: namespace['title'] = title urls = get_url.findall(record) for url in urls: namespace['url'] = url latlngs = get_latlng.findall(record) for latlng in latlngs: namespace['latlng'] = latlng block_record.append(namespace) print block_record > > The def of "namespace" would be clearer imo in a single line: > ? ?namespace = {title:t, url:url, lat:g} i am not sure how this will fit into the code! > This also reveals a kind of name confusion, doesn't it? > > > Denis > > > > > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Feb 2 10:18:51 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Feb 2010 09:18:51 -0000 Subject: [Tutor] callable objects References: Message-ID: "sudhir prasad" wrote > i run module1 ,first it calls sm1 in module 2 and a list gets updated,now > i > again pass the same list to sm2 in module2 but im getting an error " > 'list' > object is not callable" That suggests that somewhere in your code you are trying to call the list. ie putting parentheses after it: lst = [1,2,3] lst() # tryiong to call list but list is "not callable" So I think the error is to do with a mistake in your copde rather than the module/submodule structure! But that is guesswork without seeing the code. When discussing an error always send the full error message so that we can read the stack trace etc. And post the code if possible too - at the very least the function where the error occurs! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From stefan_ml at behnel.de Tue Feb 2 13:05:12 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 02 Feb 2010 13:05:12 +0100 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> Message-ID: Norman Khine, 02.02.2010 10:16: > get_record = re.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""") > get_title = re.compile(r"""(.*)<\/strong>""") > get_url = re.compile(r"""a href=\"\/(.*)\">En savoir plus""") > get_latlng = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""") > > records = get_record.findall(data) > block_record = [] > for record in records: > namespace = {} > titles = get_title.findall(record) > for title in titles: > namespace['title'] = title I usually go one step further: find_all_titles = re.compile(r"""(.*)<\/strong>""").findall for record in records: titles = find_all_titles(record) Both faster and more readable (as is so common in Python). Stefan From davea at ieee.org Tue Feb 2 13:25:35 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 02 Feb 2010 07:25:35 -0500 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> Message-ID: <4B6819BF.3000705@ieee.org> Norman Khine wrote: > thanks denis, > > On Tue, Feb 2, 2010 at 9:30 AM, spir wrote: > >> On Mon, 1 Feb 2010 16:30:02 +0100 >> Norman Khine wrote: >> >> >>> On Mon, Feb 1, 2010 at 1:19 PM, Kent Johnson wrote: >>> >>>> On Mon, Feb 1, 2010 at 6:29 AM, Norman Khine wrote: >>>> >>>> >>>>> thanks, what about the whitespace problem? >>>>> >>>> \s* will match any amount of whitespace includin newlines. >>>> >>> thank you, this worked well. >>> >>> here is the code: >>> >>> ### >>> import re >>> file=en('producers_google_map_code.txt', 'r') >>> data =repr( file.read().decode('utf-8') ) >>> >>> block =e.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""") >>> b =lock.findall(data) >>> block_list =] >>> for html in b: >>> namespace =} >>> t =e.compile(r"""(.*)<\/strong>""") >>> title =.findall(html) >>> for item in title: >>> namespace['title'] =tem >>> u =e.compile(r"""a href=\"\/(.*)\">En savoir plus""") >>> url =.findall(html) >>> for item in url: >>> namespace['url'] =tem >>> g =e.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""") >>> lat =.findall(html) >>> for item in lat: >>> namespace['LatLng'] =tem >>> block_list.append(namespace) >>> >>> ### >>> >>> can this be made better? >>> >> The 3 regex patterns are constants: they can be put out of the loop. >> >> You may also rename b to blocks, and find a more a more accurate name for block_list; eg block_records, where record =et of (named) fields. >> >> A short desc and/or example of the overall and partial data formats can greatly help later review, since regex patterns alone are hard to decode. >> > > here are the changes: > > import re > file=en('producers_google_map_code.txt', 'r') > data =repr( file.read().decode('utf-8') ) > > get_record =e.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""") > get_title =e.compile(r"""(.*)<\/strong>""") > get_url =e.compile(r"""a href=\"\/(.*)\">En savoir plus""") > get_latlng =e.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""") > > records =et_record.findall(data) > block_record =] > for record in records: > namespace =} > titles =et_title.findall(record) > for title in titles: > namespace['title'] =itle > urls =et_url.findall(record) > for url in urls: > namespace['url'] =rl > latlngs =et_latlng.findall(record) > for latlng in latlngs: > namespace['latlng'] =atlng > block_record.append(namespace) > > print block_record > >> The def of "namespace" would be clearer imo in a single line: >> namespace =title:t, url:url, lat:g} >> > > i am not sure how this will fit into the code! > > >> This also reveals a kind of name confusion, doesn't it? >> >> >> Denis >> >> > Your variable 'file' is hiding a built-in name for the file type. No harm in this example, but it's a bad habit to get into. What did you intend to happen if the number of titles, urls, and latIngs are not each exactly one? As you have it now, if there's more than one, you spend time adding them all to the dictionary, but only the last one survives. And if there aren't any, you don't make an entry in the dictionary. If that's the exact behavior you want, then you could replace the loop with an if statement: (untested) if titles: namespace['title'] = titles[-1] On the other hand, if you want a None in your dictionary for missing information, then something like: (untested) for record in records: titles = get_title.findall(record) title = titles[-1] if titles else None urls = get_url.findall(record) url = urls[-1] if urls else None latlngs = get_latlng.findall(record) lating = latings[-1] if latings else None block_record.append( {'title':title, 'url':url, 'lating':lating{ ) DaveA From kent37 at tds.net Tue Feb 2 13:27:53 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 2 Feb 2010 07:27:53 -0500 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> Message-ID: <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> On Tue, Feb 2, 2010 at 4:16 AM, Norman Khine wrote: > here are the changes: > > import re > file=open('producers_google_map_code.txt', 'r') > data = ?repr( file.read().decode('utf-8') ) Why do you use repr() here? > get_record = re.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""") > get_title = re.compile(r"""(.*)<\/strong>""") > get_url = re.compile(r"""a href=\"\/(.*)\">En savoir plus""") > get_latlng = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""") > > records = get_record.findall(data) > block_record = [] > for record in records: > ? ? ? ?namespace = {} > ? ? ? ?titles = get_title.findall(record) > ? ? ? ?for title in titles: > ? ? ? ? ? ? ? ?namespace['title'] = title This is odd, you don't need a loop to get the last title, just use namespace['title'] = get_title.findall(html)[-1] and similarly for url and latings. Kent > ? ? ? ?urls = get_url.findall(record) > ? ? ? ?for url in urls: > ? ? ? ? ? ? ? ?namespace['url'] = url > ? ? ? ?latlngs = get_latlng.findall(record) > ? ? ? ?for latlng in latlngs: > ? ? ? ? ? ? ? ?namespace['latlng'] = latlng > ? ? ? ?block_record.append(namespace) > > print block_record >> >> The def of "namespace" would be clearer imo in a single line: >> ? ?namespace = {title:t, url:url, lat:g} > > i am not sure how this will fit into the code! > >> This also reveals a kind of name confusion, doesn't it? >> >> >> Denis >> >> >> >> >> ________________________________ >> >> la vita e estrany >> >> http://spir.wikidot.com/ >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From zjkhere at gmail.com Tue Feb 2 14:04:22 2010 From: zjkhere at gmail.com (Zheng Jiekai) Date: Tue, 2 Feb 2010 21:04:22 +0800 Subject: [Tutor] how to pass data to aother function from a class? Message-ID: <266765dc1002020504u4415c991r7b3c7cc7fc70e7e5@mail.gmail.com> I'm beginning my python learning. My python version is 3.1 I?v never learnt OOP before. So I'm confused by the HTMLParser Here's the code: >>> from html.parser import HTMLParser >>> class parser(HTMLParser): def handle_data(self, data): print(data) >>> p = parser() >>> page = """

Title

I'm a paragraph!

""" >>> p.feed(page) Title I'm a paragraph! I'm wondering if I can pass the data generated by ' handle_data' to a function instead of just print the data. Sorry for my poor English and Thank you for tutoring! -------------- next part -------------- An HTML attachment was scrubbed... URL: From phil at xfr.co.uk Tue Feb 2 13:49:07 2010 From: phil at xfr.co.uk (Philip Kilner) Date: Tue, 02 Feb 2010 12:49:07 +0000 Subject: [Tutor] tracking program In-Reply-To: <8f69b2391002011145q5d963f2cvecd1e7b1d039a506@mail.gmail.com> References: <8f69b2391002011145q5d963f2cvecd1e7b1d039a506@mail.gmail.com> Message-ID: <4B681F43.2040405@xfr.co.uk> Hi Luis, Luis Ortega wrote: > I am fairly new to programming (which means I have never, ever, ever > written a program). I have a book or two in Python, and so far I like > it. I have a stupid question to ask; Is it possible to write an > employee's internet tracking program in Python? > Wayne is right that you could do it as a proxy, but one question you can ask is "which bits do I need to write in Python, and which bits can I use an off the shelf solution for?". One choice here is to use an existing proxy server that logs activity, and then write a Python application to analyse the logs. That might be a more approachable problem for you at this point. HTH -- Regards, PhilK 'work as if you lived in the early days of a better nation' - alasdair gray -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 5583 bytes Desc: S/MIME Cryptographic Signature URL: From norman at khine.net Tue Feb 2 15:33:17 2010 From: norman at khine.net (Norman Khine) Date: Tue, 2 Feb 2010 15:33:17 +0100 Subject: [Tutor] parse text file In-Reply-To: <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100123005017.7532df62@o> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> Message-ID: <9c2c8ffb1002020633k31dc5810yddc204df660e7c50@mail.gmail.com> hello, thank you all for the advise, here is the updated version with the changes. import re file = open('producers_google_map_code.txt', 'r') data = repr( file.read().decode('utf-8') ) get_records = re.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""").findall get_titles = re.compile(r"""(.*)<\/strong>""").findall get_urls = re.compile(r"""a href=\"\/(.*)\">En savoir plus""").findall get_latlngs = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""").findall records = get_records(data) block_record = [] for record in records: namespace = {} titles = get_titles(record) title = titles[-1] if titles else None urls = get_urls(record) url = urls[-1] if urls else None latlngs = get_latlngs(record) latlng = latlngs[-1] if latlngs else None block_record.append( {'title':title, 'url':url, 'lating':latlng} ) print block_record On Tue, Feb 2, 2010 at 1:27 PM, Kent Johnson wrote: > On Tue, Feb 2, 2010 at 4:16 AM, Norman Khine wrote: > >> here are the changes: >> >> import re >> file=open('producers_google_map_code.txt', 'r') >> data = ?repr( file.read().decode('utf-8') ) > > Why do you use repr() here? i have latin-1 chars in the producers_google_map_code.txt' file and this is the only way to get it to read the data. is this incorrect? > >> get_record = re.compile(r"""openInfoWindowHtml\(.*?\\ticon: myIcon\\n""") >> get_title = re.compile(r"""(.*)<\/strong>""") >> get_url = re.compile(r"""a href=\"\/(.*)\">En savoir plus""") >> get_latlng = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\\n\s*(\-?\d+\.\d*)\)""") >> >> records = get_record.findall(data) >> block_record = [] >> for record in records: >> ? ? ? ?namespace = {} >> ? ? ? ?titles = get_title.findall(record) >> ? ? ? ?for title in titles: >> ? ? ? ? ? ? ? ?namespace['title'] = title > > > This is odd, you don't need a loop to get the last title, just use > ?namespace['title'] = get_title.findall(html)[-1] > > and similarly for url and latings. > > Kent > > >> ? ? ? ?urls = get_url.findall(record) >> ? ? ? ?for url in urls: >> ? ? ? ? ? ? ? ?namespace['url'] = url >> ? ? ? ?latlngs = get_latlng.findall(record) >> ? ? ? ?for latlng in latlngs: >> ? ? ? ? ? ? ? ?namespace['latlng'] = latlng >> ? ? ? ?block_record.append(namespace) >> >> print block_record >>> >>> The def of "namespace" would be clearer imo in a single line: >>> ? ?namespace = {title:t, url:url, lat:g} >> >> i am not sure how this will fit into the code! >> >>> This also reveals a kind of name confusion, doesn't it? >>> >>> >>> Denis >>> >>> >>> >>> >>> ________________________________ >>> >>> la vita e estrany >>> >>> http://spir.wikidot.com/ >>> _______________________________________________ >>> Tutor maillist ?- ?Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > From kent37 at tds.net Tue Feb 2 16:12:04 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 2 Feb 2010 10:12:04 -0500 Subject: [Tutor] how to pass data to aother function from a class? In-Reply-To: <266765dc1002020504u4415c991r7b3c7cc7fc70e7e5@mail.gmail.com> References: <266765dc1002020504u4415c991r7b3c7cc7fc70e7e5@mail.gmail.com> Message-ID: <1c2a2c591002020712l7a324b09se558addb5a03cb86@mail.gmail.com> On Tue, Feb 2, 2010 at 8:04 AM, Zheng Jiekai wrote: > I'm beginning my python learning. My python version is 3.1 > > I?v never learnt OOP before. > So I'm confused by the HTMLParser > > Here's the code: >>>> from html.parser import HTMLParser >>>> class parser(HTMLParser): > def handle_data(self, data): > ???????? print(data) > >>>> p = parser() >>>> page = """

Title

I'm a paragraph!

""" >>>> p.feed(page) > Title > I'm a paragraph! > > > I'm wondering if I can pass the data generated by ' handle_data' to a > function instead of just print the data. Sure. In fact print() is a function. Just replace print(data) with my_function(data). Kent From kent37 at tds.net Tue Feb 2 16:19:07 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 2 Feb 2010 10:19:07 -0500 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1002020633k31dc5810yddc204df660e7c50@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <9c2c8ffb1001311543h63b7935el13f99f2bebc06526@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> <9c2c8ffb1002020633k31dc5810yddc204df660e7c50@mail.gmail.com> Message-ID: <1c2a2c591002020719h438c8f8bgdc607395bf843c0c@mail.gmail.com> On Tue, Feb 2, 2010 at 9:33 AM, Norman Khine wrote: > On Tue, Feb 2, 2010 at 1:27 PM, Kent Johnson wrote: >> On Tue, Feb 2, 2010 at 4:16 AM, Norman Khine wrote: >> >>> here are the changes: >>> >>> import re >>> file=open('producers_google_map_code.txt', 'r') >>> data = ?repr( file.read().decode('utf-8') ) >> >> Why do you use repr() here? > > i have latin-1 chars in the producers_google_map_code.txt' file and > this is the only way to get it to read the data. > > is this incorrect? Well, the repr() call is after the file read. If your data is latin-1 you should decode it as latin-1, not utf-8: data = file.read().decode('latin-1') Though if the decode('utf-8') succeeds, and you do have non-ascii characters in the data, they are probably encoded in utf-8, not latin-1. Are you sure you have latin-1? The repr() call converts back to ascii text, maybe that is what you want? Perhaps you put in the repr because you were having trouble printing? It smells of programming by guess rather than a correct solution to some problem. What happens if you take it out? Kent From fubarninja at hotmail.com Tue Feb 2 17:47:42 2010 From: fubarninja at hotmail.com (jim serson) Date: Tue, 2 Feb 2010 11:47:42 -0500 Subject: [Tutor] Shashwat Anand you helped with search Message-ID: I am trying to have the search return several numbers or words in a single sentences now. I don't know if I am using the wrong format I am trying to use the split method because I thought I could return several parts of a sentence with it. For example if it had 1 2 3 4 5 I thought I could search and return 1 3 5 or if it had ?to set the function? I could return ?set function? from that line, but I can?t get it working properly. I have tried several different approaches with split. I have tried to split it at the raw_input() line, at the if statement, putting it in a loop and declaring it separately. I have looked up, in the python library to make sure I am entering it properly. It will ether run trough and not work like I expect or it will come up with an error. I think I am using the right method in the wrong way. If you could tell me if I am trying the correct method or give me a push in the right direction that would be grate thanks. look_in = raw_input ("Enter the search file to look in ") search = raw_input ("Enter your search item ") c = open(look_in, "r").read().count(search.split() if c: print search, ",", c,"Of your search was found" else: print "Your search was not found" _________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From grigor.kolev at gmail.com Tue Feb 2 18:07:11 2010 From: grigor.kolev at gmail.com (=?windows-1251?B?w/Do4+7w?=) Date: Tue, 2 Feb 2010 19:07:11 +0200 Subject: [Tutor] Question about importing Message-ID: Hi all. How can I import a module which is located in the upper directory. -- ????? ???? ???? ???, ???? ???? ??????? ?? ???? ?? ???? ! From dwightdhutto at yahoo.com Tue Feb 2 19:33:31 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Tue, 2 Feb 2010 10:33:31 -0800 (PST) Subject: [Tutor] Question about importing In-Reply-To: Message-ID: <461213.14885.qm@web45301.mail.sp1.yahoo.com> --- On Tue, 2/2/10, ?????? wrote: From: ?????? Subject: [Tutor] Question about importing To: "Python Tutor" Date: Tuesday, February 2, 2010, 12:07 PM Hi all. How can I import a module which is located in the upper directory. I think the following might be what you're looking for: http://docs.python.org/tutorial/modules.html#the-module-search-path -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Tue Feb 2 19:39:33 2010 From: norman at khine.net (Norman Khine) Date: Tue, 2 Feb 2010 19:39:33 +0100 Subject: [Tutor] parse text file In-Reply-To: <1c2a2c591002020719h438c8f8bgdc607395bf843c0c@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100201105724.6c3e3af6@o> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> <9c2c8ffb1002020633k31dc5810yddc204df660e7c50@mail.gmail.com> <1c2a2c591002020719h438c8f8bgdc607395bf843c0c@mail.gmail.com> Message-ID: <9c2c8ffb1002021039r1d6d4b94j1b0f6ca5ec2a18a9@mail.gmail.com> On Tue, Feb 2, 2010 at 4:19 PM, Kent Johnson wrote: > On Tue, Feb 2, 2010 at 9:33 AM, Norman Khine wrote: >> On Tue, Feb 2, 2010 at 1:27 PM, Kent Johnson wrote: >>> On Tue, Feb 2, 2010 at 4:16 AM, Norman Khine wrote: >>> >>>> here are the changes: >>>> >>>> import re >>>> file=open('producers_google_map_code.txt', 'r') >>>> data = ?repr( file.read().decode('utf-8') ) >>> >>> Why do you use repr() here? >> >> i have latin-1 chars in the producers_google_map_code.txt' file and >> this is the only way to get it to read the data. >> >> is this incorrect? > > Well, the repr() call is after the file read. If your data is latin-1 > you should decode it as latin-1, not utf-8: > data = file.read().decode('latin-1') > > Though if the decode('utf-8') succeeds, and you do have non-ascii > characters in the data, they are probably encoded in utf-8, not > latin-1. Are you sure you have latin-1? > > The repr() call converts back to ascii text, maybe that is what you want? > > Perhaps you put in the repr because you were having trouble printing? > > It smells of programming by guess rather than a correct solution to > some problem. What happens if you take it out? when i take it out, i get an empty list. whereas both data = repr( file.read().decode('latin-1') ) and data = repr( file.read().decode('utf-8') ) returns the full list. here is the file http://cdn.admgard.org/documents/producers_google_map_code.txt > > Kent > From alan.gauld at btinternet.com Tue Feb 2 20:07:50 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Feb 2010 19:07:50 -0000 Subject: [Tutor] Shashwat Anand you helped with search References: Message-ID: "jim serson" wrote > I think I am using the right method in the wrong way. I'm not sure what you expect this to do... > If you could tell me if I am trying the correct method or give > me a push in the right direction that would be grate thanks. Maybe a push... > look_in = raw_input ("Enter the search file to look in ") > search = raw_input ("Enter your search item ") OK, so far. You want to look for search in the file. > c = open(look_in, "r").read().count(search.split() Assuming there should be another closing paren... this opens the file and reads it into memory. It then counts the occurences of a list produced by splitting the search string. This gives a Typeerror for me! Is that what you wanted? Or do you actually want to search for each item in your search string? I think you are trying to cram too much into one line - if for no other eason that it makes debugging almost impossible. Try this: txt = open(look_in).read() search2 = search.split() print search2 # is this what you expect? for item in search2: c = txt.count(item) print item, txt.count(c) # is this what you expect? if c > 0: print search, ",", c,"Of your search was found" else: print item, "was not found" It might give you clues as to what you really want. But using multiple lines is usually a good idea, especially when trying to get it working. Its much easier to see where things are breaking that way... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From grigor.kolev at gmail.com Tue Feb 2 20:28:03 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Tue, 02 Feb 2010 21:28:03 +0200 Subject: [Tutor] Question about importing In-Reply-To: <461213.14885.qm@web45301.mail.sp1.yahoo.com> References: <461213.14885.qm@web45301.mail.sp1.yahoo.com> Message-ID: <1265138883.7449.3.camel@dedal-laptop> ? 10:33 -0800 ?? 02.02.2010 (??), David Hutto ??????: > > > --- On Tue, 2/2/10, ?????? wrote: > > From: ?????? > Subject: [Tutor] Question about importing > To: "Python Tutor" > Date: Tuesday, February 2, 2010, 12:07 PM > > Hi all. > How can I import a module which is located in the upper > directory. > > > I think the following might be what you're looking for: > > http://docs.python.org/tutorial/modules.html#the-module-search-path > > Can I use something like this #-------------------------------------------------- import sys sys.path.append("/home/user/other") import module #------------------------------------------------- -- Grigor Kolev From dwightdhutto at yahoo.com Tue Feb 2 20:47:44 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Tue, 2 Feb 2010 11:47:44 -0800 (PST) Subject: [Tutor] Question about importing In-Reply-To: <1265138883.7449.3.camel@dedal-laptop> Message-ID: <761240.66152.qm@web45308.mail.sp1.yahoo.com> --- On Tue, 2/2/10, Grigor Kolev wrote: From: Grigor Kolev Subject: Re: [Tutor] Question about importing To: "David Hutto" Cc: "Python Tutor" Date: Tuesday, February 2, 2010, 2:28 PM ? 10:33 -0800 ?? 02.02.2010 (??), David Hutto ??????: > > > --- On Tue, 2/2/10, ?????? wrote: >? ? ? ??? >? ? ? ???From: ?????? >? ? ? ???Subject: [Tutor] Question about importing >? ? ? ???To: "Python Tutor" >? ? ? ???Date: Tuesday, February 2, 2010, 12:07 PM >? ? ? ??? >? ? ? ???Hi all. >? ? ? ???How can I import a module which is located in the upper >? ? ? ???directory. >? ? ? ??? >? ? ? ??? >? ? ? ???I think the following might be what you're looking for: >? ? ? ??? >? ? ? ???http://docs.python.org/tutorial/modules.html#the-module-search-path >? ? ? ??? > Can I use something like this #-------------------------------------------------- import sys sys.path.append("/home/user/other") import module #------------------------------------------------- -- Grigor Kolev ? That's exactly what it says to do, but I haven't figured out the path to append to mine yet. -------------- next part -------------- An HTML attachment was scrubbed... URL: From grigor.kolev at gmail.com Tue Feb 2 20:54:35 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Tue, 02 Feb 2010 21:54:35 +0200 Subject: [Tutor] Question about importing In-Reply-To: <761240.66152.qm@web45308.mail.sp1.yahoo.com> References: <761240.66152.qm@web45308.mail.sp1.yahoo.com> Message-ID: <1265140475.7449.5.camel@dedal-laptop> ? 11:47 -0800 ?? 02.02.2010 (??), David Hutto ??????: > > > --- On Tue, 2/2/10, Grigor Kolev wrote: > > From: Grigor Kolev > Subject: Re: [Tutor] Question about importing > To: "David Hutto" > Cc: "Python Tutor" > Date: Tuesday, February 2, 2010, 2:28 PM > > ? 10:33 -0800 ?? 02.02.2010 (??), David Hutto ??????: > > > > > > --- On Tue, 2/2/10, ?????? wrote: > > > > From: ?????? > > Subject: [Tutor] Question about importing > > To: "Python Tutor" > > Date: Tuesday, February 2, 2010, 12:07 PM > > > > Hi all. > > How can I import a module which is located in the > upper > > directory. > > > > > > I think the following might be what you're looking > for: > > > > > http://docs.python.org/tutorial/modules.html#the-module-search-path > > > > > Can I use something like this > #-------------------------------------------------- > import sys > sys.path.append("/home/user/other") > import module > #------------------------------------------------- > -- > Grigor Kolev > > > That's exactly what it says to do, but I haven't figured out > the path to append to mine yet. > > Thanks for your help -- Grigor Kolev From eike.welk at gmx.net Tue Feb 2 20:59:37 2010 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 2 Feb 2010 20:59:37 +0100 Subject: [Tutor] Question about importing In-Reply-To: <1265138883.7449.3.camel@dedal-laptop> References: <461213.14885.qm@web45301.mail.sp1.yahoo.com> <1265138883.7449.3.camel@dedal-laptop> Message-ID: <201002022059.37245.eike.welk@gmx.net> On Tuesday February 2 2010 20:28:03 Grigor Kolev wrote: > Can I use something like this > #-------------------------------------------------- > import sys > sys.path.append("/home/user/other") > import module > #------------------------------------------------- > Yes I think so. I just tried something similar: -------------------------------------------------- IPython 0.10 -- An enhanced Interactive Python. <------- snip --------> In [1]: import sys In [2]: sys.path.append("/home/eike/codedir/freeode/trunk/freeode_py/freeode/") <------- snip --------> <------- The next line is a special command of IPython: ----------------> In [8]: !ls /home/eike/codedir/freeode/trunk/freeode_py/freeode/ ast.py pygenerator.pyc test_1_interpreter.pyc test_pygenerator.pyc ast.pyc simlcompiler.py test_2_interpreter.py test_simlcompiler.py __init__.py simlcompiler.pyc test_2_interpreter.pyc <------- snip --------> In [9]: import simlcompiler --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /home/eike/ in () /home/eike/codedir/freeode/trunk/freeode_py/freeode/simlcompiler.py in () 36 import stat 37 from subprocess import Popen #, PIPE, STDOUT ---> 38 import pyparsing 39 import freeode.simlparser as simlparser 40 import freeode.interpreter as interpreter ImportError: No module named pyparsing ---------------------------------------------------------- Well... the import fails, but it finds the module and starts to import it. HTH, Eike. From dwightdhutto at yahoo.com Tue Feb 2 21:13:14 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Tue, 2 Feb 2010 12:13:14 -0800 (PST) Subject: [Tutor] Question about importing In-Reply-To: <1265140475.7449.5.camel@dedal-laptop> Message-ID: <101143.15655.qm@web45314.mail.sp1.yahoo.com> --- On Tue, 2/2/10, Grigor Kolev wrote: From: Grigor Kolev Subject: Re: [Tutor] Question about importing To: "David Hutto" Cc: "Python Tutor" Date: Tuesday, February 2, 2010, 2:54 PM ? 11:47 -0800 ?? 02.02.2010 (??), David Hutto ??????: > > > --- On Tue, 2/2/10, Grigor Kolev wrote: >? ? ? ??? >? ? ? ???From: Grigor Kolev >? ? ? ???Subject: Re: [Tutor] Question about importing >? ? ? ???To: "David Hutto" >? ? ? ???Cc: "Python Tutor" >? ? ? ???Date: Tuesday, February 2, 2010, 2:28 PM >? ? ? ??? >? ? ? ???? 10:33 -0800 ?? 02.02.2010 (??), David Hutto ??????: >? ? ? ???> >? ? ? ???> >? ? ? ???> --- On Tue, 2/2/10, ?????? wrote: >? ? ? ???>? ? ? ??? >? ? ? ???>? ? ? ???From: ?????? >? ? ? ???>? ? ? ???Subject: [Tutor] Question about importing >? ? ? ???>? ? ? ???To: "Python Tutor" >? ? ? ???>? ? ? ???Date: Tuesday, February 2, 2010, 12:07 PM >? ? ? ???>? ? ? ??? >? ? ? ???>? ? ? ???Hi all. >? ? ? ???>? ? ? ???How can I import a module which is located in the >? ? ? ???upper >? ? ? ???>? ? ? ???directory. >? ? ? ???>? ? ? ??? >? ? ? ???>? ? ? ??? >? ? ? ???>? ? ? ???I think the following might be what you're looking >? ? ? ???for: >? ? ? ???>? ? ? ??? >? ? ? ???> >? ? ? ? ? ? http://docs.python.org/tutorial/modules.html#the-module-search-path >? ? ? ???>? ? ? ??? >? ? ? ???> >? ? ? ???Can I use something like this >? ? ? ???#-------------------------------------------------- >? ? ? ???import sys >? ? ? ???sys.path.append("/home/user/other") >? ? ? ???import module >? ? ? ???#------------------------------------------------- >? ? ? ???-- >? ? ? ???Grigor Kolev >? ? ? ? ? >? ? ? ??? >? ? ? ???That's exactly what it says to do, but I haven't figured out >? ? ? ???the path to append to mine yet. >? ? ? ??? > Thanks for your help It wasn't that much help, and I was about to do something similar anyway.. So if it makes you feel better, now we both know that's how it works. -- Grigor Kolev -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Feb 2 22:11:18 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 2 Feb 2010 16:11:18 -0500 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1002021039r1d6d4b94j1b0f6ca5ec2a18a9@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <9c2c8ffb1002010329v2af712e3m206b1c167059836a@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> <9c2c8ffb1002020633k31dc5810yddc204df660e7c50@mail.gmail.com> <1c2a2c591002020719h438c8f8bgdc607395bf843c0c@mail.gmail.com> <9c2c8ffb1002021039r1d6d4b94j1b0f6ca5ec2a18a9@mail.gmail.com> Message-ID: <1c2a2c591002021311x7a152133qe6e3ed69892f1782@mail.gmail.com> On Tue, Feb 2, 2010 at 1:39 PM, Norman Khine wrote: > On Tue, Feb 2, 2010 at 4:19 PM, Kent Johnson wrote: >> On Tue, Feb 2, 2010 at 9:33 AM, Norman Khine wrote: >>> On Tue, Feb 2, 2010 at 1:27 PM, Kent Johnson wrote: >>>> On Tue, Feb 2, 2010 at 4:16 AM, Norman Khine wrote: >>>> Why do you use repr() here? >> >> It smells of programming by guess rather than a correct solution to >> some problem. What happens if you take it out? > > when i take it out, i get an empty list. > > whereas both > data = repr( file.read().decode('latin-1') ) > and > data = repr( file.read().decode('utf-8') ) > > returns the full list. Try this version: data = file.read() get_records = re.compile(r"""openInfoWindowHtml\(.*?\ticon: myIcon\n""", re.DOTALL).findall get_titles = re.compile(r"""(.*)<\/strong>""").findall get_urls = re.compile(r"""a href=\"\/(.*)\">En savoir plus""").findall get_latlngs = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\n\s*(\-?\d+\.\d*)\)""").findall then as before. Your repr() call is essentially removing newlines from the input by converting them to literal '\n' pairs. This allows your regex to work without the DOTALL modifier. Note you will get slightly different results with my version - it will give you correct utf-8 text for the titles whereas yours gives \ escapes. For example one of the titles is "CGTSM (Sat?re Maw?)". Your version returns {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804', '-79.649735'), 'title': 'CGTSM (Sat\\xe9re Maw\\xe9)'} Mine gives {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804', '-79.649735'), 'title': 'CGTSM (Sat\xc3\xa9re Maw\xc3\xa9)'} This is showing the repr() of the title so they both have \ but note that yours has two \\ indicating that the \ is in the text; mine has only one \. Kent From GOW524 at gmail.com Tue Feb 2 22:22:56 2010 From: GOW524 at gmail.com (GOW524 at gmail.com) Date: Tue, 02 Feb 2010 21:22:56 +0000 Subject: [Tutor] tracking program In-Reply-To: <4B681F43.2040405@xfr.co.uk> Message-ID: <0016e64ce5729fd008047ea4b40f@google.com> All of you guys rock, I have so much to learn before I even attempt to work on my program. Thank you again for all your help. Luis On Feb 2, 2010 4:49am, Philip Kilner wrote: > Hi Luis, > Luis Ortega wrote: > > I am fairly new to programming (which means I have never, ever, ever > > written a program). I have a book or two in Python, and so far I like > > it. I have a stupid question to ask; Is it possible to write an > > employee's internet tracking program in Python? > > > Wayne is right that you could do it as a proxy, but one question you can > ask is "which bits do I need to write in Python, and which bits can I > use an off the shelf solution for?". > One choice here is to use an existing proxy server that logs activity, > and then write a Python application to analyse the logs. > That might be a more approachable problem for you at this point. > HTH > -- > Regards, > PhilK > 'work as if you lived in the early days of a better nation' > - alasdair gray -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Tue Feb 2 22:56:22 2010 From: norman at khine.net (Norman Khine) Date: Tue, 2 Feb 2010 22:56:22 +0100 Subject: [Tutor] parse text file In-Reply-To: <1c2a2c591002021311x7a152133qe6e3ed69892f1782@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> <9c2c8ffb1002020633k31dc5810yddc204df660e7c50@mail.gmail.com> <1c2a2c591002020719h438c8f8bgdc607395bf843c0c@mail.gmail.com> <9c2c8ffb1002021039r1d6d4b94j1b0f6ca5ec2a18a9@mail.gmail.com> <1c2a2c591002021311x7a152133qe6e3ed69892f1782@mail.gmail.com> Message-ID: <9c2c8ffb1002021356y18e9292fl71f1f10ff2bd80d4@mail.gmail.com> On Tue, Feb 2, 2010 at 10:11 PM, Kent Johnson wrote: > On Tue, Feb 2, 2010 at 1:39 PM, Norman Khine wrote: >> On Tue, Feb 2, 2010 at 4:19 PM, Kent Johnson wrote: >>> On Tue, Feb 2, 2010 at 9:33 AM, Norman Khine wrote: >>>> On Tue, Feb 2, 2010 at 1:27 PM, Kent Johnson wrote: >>>>> On Tue, Feb 2, 2010 at 4:16 AM, Norman Khine wrote: > >>>>> Why do you use repr() here? > >>> >>> It smells of programming by guess rather than a correct solution to >>> some problem. What happens if you take it out? >> >> when i take it out, i get an empty list. >> >> whereas both >> data = repr( file.read().decode('latin-1') ) >> and >> data = repr( file.read().decode('utf-8') ) >> >> returns the full list. > > Try this version: > > data = file.read() > > get_records = re.compile(r"""openInfoWindowHtml\(.*?\ticon: > myIcon\n""", re.DOTALL).findall > get_titles = re.compile(r"""(.*)<\/strong>""").findall > get_urls = re.compile(r"""a href=\"\/(.*)\">En savoir plus""").findall > get_latlngs = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\n\s*(\-?\d+\.\d*)\)""").findall > > then as before. > > Your repr() call is essentially removing newlines from the input by > converting them to literal '\n' pairs. This allows your regex to work > without the DOTALL modifier. > > Note you will get slightly different results with my version - it will > give you correct utf-8 text for the titles whereas yours gives \ > escapes. For example one of the titles is "CGTSM (Sat?re Maw?)". Your > version returns > > {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804', > '-79.649735'), 'title': 'CGTSM (Sat\\xe9re Maw\\xe9)'} > > Mine gives > {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804', > '-79.649735'), 'title': 'CGTSM (Sat\xc3\xa9re Maw\xc3\xa9)'} > > This is showing the repr() of the title so they both have \ but note > that yours has two \\ indicating that the \ is in the text; mine has > only one \. i am no expert, but there seems to be a bigger difference. with repr(), i get: Sat\\xe9re Maw\\xe9 where as you get Sat\xc3\xa9re Maw\xc3\xa9 repr()'s ? == \\xe9 whereas on your version ? == \xc3\xa9 > > Kent > also, i still get an empty list when i run the code as suggested. From davea at ieee.org Tue Feb 2 23:21:19 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 02 Feb 2010 17:21:19 -0500 Subject: [Tutor] Question about importing In-Reply-To: <201002022059.37245.eike.welk@gmx.net> References: <461213.14885.qm@web45301.mail.sp1.yahoo.com> <1265138883.7449.3.camel@dedal-laptop> <201002022059.37245.eike.welk@gmx.net> Message-ID: <4B68A55F.6020803@ieee.org> Eike Welk wrote: > On Tuesday February 2 2010 20:28:03 Grigor Kolev wrote: > >> Can I use something like this >> #-------------------------------------------------- >> import sys >> sys.path.append("/home/user/other") >> import module >> #------------------------------------------------- >> >> > > Yes I think so. I just tried something similar: > -------------------------------------------------- > > > IPython 0.10 -- An enhanced Interactive Python. > > <------- snip --------> > > In [1]: import sys > > In [2]: > sys.path.append("/home/eike/codedir/freeode/trunk/freeode_py/freeode/") > > <------- snip --------> > <------- The next line is a special command of IPython: ----------------> > > In [8]: !ls /home/eike/codedir/freeode/trunk/freeode_py/freeode/ > ast.py pygenerator.pyc test_1_interpreter.pyc > test_pygenerator.pyc > ast.pyc simlcompiler.py test_2_interpreter.py > test_simlcompiler.py > __init__.py simlcompiler.pyc test_2_interpreter.pyc > > <------- snip --------> > > > In [9]: import simlcompiler > --------------------------------------------------------------------------- > ImportError Traceback (most recent call last) > > /home/eike/ in () > > /home/eike/codedir/freeode/trunk/freeode_py/freeode/simlcompiler.py in > () > 36 import stat > 37 from subprocess import Popen #, PIPE, STDOUT > ---> 38 import pyparsing > 39 import freeode.simlparser as simlparser > 40 import freeode.interpreter as interpreter > > ImportError: No module named pyparsing > > > ---------------------------------------------------------- > Well... the import fails, but it finds the module and starts to import it. > > > HTH, > Eike. > > > > I have no idea what freode looks like, but I have a guess, based on your error messages. I'd guess that you want to append without the freeode directory: sys.path.append("/home/eike/codedir/freeode/trunk/freeode_py/") and import with it. That's because freeode is a package name, not a directory name (I can tell because __init__.py is present) import freeode.simlcompiler See if that works any better. DaveA From kent37 at tds.net Tue Feb 2 23:36:26 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 2 Feb 2010 17:36:26 -0500 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1002021356y18e9292fl71f1f10ff2bd80d4@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> <9c2c8ffb1002020633k31dc5810yddc204df660e7c50@mail.gmail.com> <1c2a2c591002020719h438c8f8bgdc607395bf843c0c@mail.gmail.com> <9c2c8ffb1002021039r1d6d4b94j1b0f6ca5ec2a18a9@mail.gmail.com> <1c2a2c591002021311x7a152133qe6e3ed69892f1782@mail.gmail.com> <9c2c8ffb1002021356y18e9292fl71f1f10ff2bd80d4@mail.gmail.com> Message-ID: <1c2a2c591002021436y72b70f69qd4e8ec59c6ef3fb6@mail.gmail.com> On Tue, Feb 2, 2010 at 4:56 PM, Norman Khine wrote: > On Tue, Feb 2, 2010 at 10:11 PM, Kent Johnson wrote: >> Try this version: >> >> data = file.read() >> >> get_records = re.compile(r"""openInfoWindowHtml\(.*?\ticon: >> myIcon\n""", re.DOTALL).findall >> get_titles = re.compile(r"""(.*)<\/strong>""").findall >> get_urls = re.compile(r"""a href=\"\/(.*)\">En savoir plus""").findall >> get_latlngs = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\n\s*(\-?\d+\.\d*)\)""").findall >> >> then as before. >> >> Your repr() call is essentially removing newlines from the input by >> converting them to literal '\n' pairs. This allows your regex to work >> without the DOTALL modifier. >> >> Note you will get slightly different results with my version - it will >> give you correct utf-8 text for the titles whereas yours gives \ >> escapes. For example one of the titles is "CGTSM (Sat?re Maw?)". Your >> version returns >> >> {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804', >> '-79.649735'), 'title': 'CGTSM (Sat\\xe9re Maw\\xe9)'} >> >> Mine gives >> {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804', >> '-79.649735'), 'title': 'CGTSM (Sat\xc3\xa9re Maw\xc3\xa9)'} >> >> This is showing the repr() of the title so they both have \ but note >> that yours has two \\ indicating that the \ is in the text; mine has >> only one \. > > i am no expert, but there seems to be a bigger difference. > > with repr(), i get: > Sat\\xe9re Maw\\xe9 > > where as you get > > Sat\xc3\xa9re Maw\xc3\xa9 > > repr()'s > ? == \\xe9 > whereas on your version > ? == \xc3\xa9 Right. Your version has four actual characters in the result - \, x, e, 9. This is the escaped representation of the unicode representation of e-acute. (The \ is doubled in the repr display.) My version has two bytes in the result, with the values c3 and a9. This is the utf-8 representation of e-acute. If you want to accurately represent (i.e. print) the title at some later time you probably want the utf-8 represetation. > >> >> Kent >> > > also, i still get an empty list when i run the code as suggested. You didn't change the regexes. You have to change \\t and \\n to \t and \n because the source text now has actual tabs and newlines, not the escaped representations. I know this is confusing, I'm sorry I don't have time or patience to explain more. Kent From alan.gauld at btinternet.com Wed Feb 3 00:21:48 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Feb 2010 23:21:48 -0000 Subject: [Tutor] Question about importing References: <461213.14885.qm@web45301.mail.sp1.yahoo.com> <1265138883.7449.3.camel@dedal-laptop> Message-ID: "Grigor Kolev" wrote > Can I use something like this > #-------------------------------------------------- > import sys > sys.path.append("/home/user/other") > import module > #------------------------------------------------- Yes but if you have a lot of modules in there that you might want to use in other programs you might prefer to add the folder to your PYTHONPATH environment variable. That way Python will always look in that folder for your modules. Thats what I do - I gave a folder whee I put all my reusable modules. This folder is not under my Python install folder so that when I install a new Python and delete the old I don't lose my code... And the PYTHONPATH variable works with the new Python. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ldl08 at gmx.net Wed Feb 3 04:21:56 2010 From: ldl08 at gmx.net (David) Date: Wed, 03 Feb 2010 11:21:56 +0800 Subject: [Tutor] help with random.randint Message-ID: <4B68EBD4.4090503@gmx.net> Hello list, I thought this was easy even for me, but I was wrong, I guess. Here is what I want to do: take two random numbers between 1 and 99, and put them into a list. import random terms = [] for i in range(2): terms = random.randint(1, 99) print terms This prints just one number (the last one generated in the loop?) So I tried to change line 4 to the following: terms += random.randint(1, 99) hoping that it would add a second integer to my terms list. But I get an error: /home/david/Documents/Python-Projekt/multiplier.py in () 2 terms = [] 3 for i in range(2): ----> 4 terms += random.randint(1, 99) 5 print terms 6 TypeError: 'int' object is not iterable WARNING: Failure executing file: I understand this error thus: once an int has been placed into the list terms, no further int can be added. But: terms is a mutable list, and NOT an 'int' object! So here are my questions: what is the problem, and how can I generate two random numbers and store them (preferably in a tuple)? Many thanks, David From transmogribenno at gmail.com Wed Feb 3 05:25:20 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Wed, 3 Feb 2010 13:25:20 +0900 Subject: [Tutor] help with random.randint In-Reply-To: <4B68EBD4.4090503@gmx.net> References: <4B68EBD4.4090503@gmx.net> Message-ID: <9b00d1a91002022025p2b20ba86w18f4f6c12f9e41e2@mail.gmail.com> On Wed, Feb 3, 2010 at 12:21 PM, David wrote: > Hello list, > > I thought this was easy even for me, but I was wrong, I guess. > Here is what I want to do: take two random numbers between 1 and 99, and put > them into a list. > > import random > terms = ?[] > for i in range(2): > ? ? ? ?terms = random.randint(1, 99) All you're doing here is assigning an integer value to 'terms', twice. This assignment means 'terms' is no longer a list, but is now just an int. What you want is probably: terms.append (random.randint(1, 99)) > So I tried to change line 4 to the following: > ? ? ? ?terms += random.randint(1, 99) You can't freely mix types with python operators, i.e. a_list += an_int But you can use += with 2 ints or 2 lists, so you could do: terms += [random.randint(1, 99)] I think using append is much nicer though. > I understand this error thus: once an int has been placed into the list > terms, no further int can be added. But: terms is a mutable list, and NOT an > 'int' object! The int was never added to the list in the first place, because list += int is not something Python understands. > So here are my questions: what is the problem, and how can I generate two > random numbers and store them (preferably in a tuple)? I hope what I wrote above answers the first question. IIRC tuples are immutable, so you either to create the list first and then convert it to a tuple: terms_tuple = tuple(terms) Or you can create a tuple from the beginning (without a loop): terms_tuple = (random.randint(1, 99), random.randint(1, 99)) HTH, benno From ldl08 at gmx.net Wed Feb 3 07:12:42 2010 From: ldl08 at gmx.net (David) Date: Wed, 03 Feb 2010 14:12:42 +0800 Subject: [Tutor] help with random.randint (cont. -- now: pseudo code) In-Reply-To: <9b00d1a91002022025p2b20ba86w18f4f6c12f9e41e2@mail.gmail.com> References: <4B68EBD4.4090503@gmx.net> <9b00d1a91002022025p2b20ba86w18f4f6c12f9e41e2@mail.gmail.com> Message-ID: <4B6913DA.4020002@gmx.net> Hello Benno, list, thanks for those clarifications, which, well, clarify things ;-) This is my latest creation: import random def createTerms(): terms = [] for i in range(2): terms.append(random.randint(1, 99)) j = terms[0] k = terms[1] print "%3d\nx%2d" % (j, k) createTerms() Which works. However, it merely prints a multiplication task. Anyway, this was just a prelude. In the end, I want far more, namely to create, ask, and verify some multiplication questions. Here is my pseudo code of this little project: pool = [] correct = 0 incorrect = 0 def createQuestions: generate all multiplication combinations possible append as tuple to pool eliminate 'mirrored doubles' (i.e. 7x12 and 12x7) randomize pool def askQuestions: for question in pool: calculate solution take answer from user if user answer == solution: correct += 1 remove question from pool else: incorrect += 1 def showStats: print number of questions asked print number of questions answered correctly print percentage of correct answers def askFaultyAnswers: answer = raw_input("Try again the incorrect questions? (y/n) ") if answer == "y": aksQuestions() else: break createQuestions() askQuestions() showStats() askFaultyAnswers() print "good-bye!" I think it is sensible to * first create all possible solutions, then * kick out doublettes, and only then * ask questions I have some questions though: Is the overall structure and flow of this program okay? What are the main problems you can spot immediately? In the very end I would like to take this code as a basis for a wxPython program. Are there any structural requirements I am violating here? If I want to limit the number of questions asked, say to 20, would I operate with slicing methods on the randomised pool? How would you go about showing stats for the second run (i.e. the FaultyAnswers)? Right now I am thinking of setting the global variables correct and incorrect to 0 from _within_ askFaultyAnswers; then I would run showStats() also from _within_ askFaultyAnswers. Good idea? Many thanks for your guidance and input! David On 03/02/10 12:25, Benno Lang wrote: > On Wed, Feb 3, 2010 at 12:21 PM, David wrote: >> Hello list, >> >> I thought this was easy even for me, but I was wrong, I guess. >> Here is what I want to do: take two random numbers between 1 and 99, and put >> them into a list. >> >> import random >> terms = [] >> for i in range(2): >> terms = random.randint(1, 99) > > All you're doing here is assigning an integer value to 'terms', twice. > This assignment means 'terms' is no longer a list, but is now just an > int. What you want is probably: > terms.append (random.randint(1, 99)) > >> So I tried to change line 4 to the following: >> terms += random.randint(1, 99) > > You can't freely mix types with python operators, i.e. a_list += an_int > But you can use += with 2 ints or 2 lists, so you could do: > terms += [random.randint(1, 99)] > I think using append is much nicer though. > >> I understand this error thus: once an int has been placed into the list >> terms, no further int can be added. But: terms is a mutable list, and NOT an >> 'int' object! > > The int was never added to the list in the first place, because list > += int is not something Python understands. > >> So here are my questions: what is the problem, and how can I generate two >> random numbers and store them (preferably in a tuple)? > > I hope what I wrote above answers the first question. > IIRC tuples are immutable, so you either to create the list first and > then convert it to a tuple: > terms_tuple = tuple(terms) > > Or you can create a tuple from the beginning (without a loop): > terms_tuple = (random.randint(1, 99), random.randint(1, 99)) > > HTH, > benno > From bgailer at gmail.com Wed Feb 3 07:51:36 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 02 Feb 2010 22:51:36 -0800 Subject: [Tutor] help with random.randint In-Reply-To: <4B68EBD4.4090503@gmx.net> References: <4B68EBD4.4090503@gmx.net> Message-ID: <4B691CF8.8040509@gmail.com> David wrote: > Hello list, > > I thought this was easy even for me, but I was wrong, I guess. > Here is what I want to do: take two random numbers between 1 and 99, > and put them into a list. [snip] Or you can use list comprehension: terms = [random.randint(1, 99) for i in range(2)] or if you seek terseness: terms = [random.randint(1, 99) for i in 'ab'] -- Bob Gailer 919-636-4239 Chapel Hill NC From ldl08 at gmx.net Wed Feb 3 08:19:15 2010 From: ldl08 at gmx.net (David) Date: Wed, 03 Feb 2010 15:19:15 +0800 Subject: [Tutor] help with random.randint In-Reply-To: <4B691CF8.8040509@gmail.com> References: <4B68EBD4.4090503@gmx.net> <4B691CF8.8040509@gmail.com> Message-ID: <4B692373.3090404@gmx.net> Hello Bob, thanks for your comments! On 03/02/10 14:51, bob gailer wrote: > or if you seek terseness: > > terms = [random.randint(1, 99) for i in 'ab'] Do I understand correctly that 'ab' here merely serves to produce a 'dummy sequence' over which I can run the for loop? David From bgailer at gmail.com Wed Feb 3 08:46:59 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 02 Feb 2010 23:46:59 -0800 Subject: [Tutor] help with random.randint (cont. -- now: pseudo code) In-Reply-To: <4B6913DA.4020002@gmx.net> References: <4B68EBD4.4090503@gmx.net> <9b00d1a91002022025p2b20ba86w18f4f6c12f9e41e2@mail.gmail.com> <4B6913DA.4020002@gmx.net> Message-ID: <4B6929F3.20008@gmail.com> David wrote: [snip] My suggestion (untested): MAX = 12 NQ = 20 # of questions to ask # create a 2 dimensional array of 1's row = [1]*MAX pool = [row[:] for i in range(MAX)] incorrect = [] # store incorrectly answered combos here def askQuestions(): # generate and ask questions: for i in range(NQ): while 1: # loop till we get an unused combo x, y = [random.randint(1,MAX) for i in 'ab'] if mtable[x][y] == 1: # combo is available break askQuestion(x,y) # indicate asked mtable[x][y] = 0 mtable[y][x] = 0 showStats() def askQuestion(x,y): solution = x*y # take answer from user ok = user answer == solution if ok: correct += 1 else: incorrect.append((x,y)) return ok def askFaultyAnswers(): answer = raw_input("Try again the incorrect questions? (y/n) ") if answer == "y": correct = 0 for x,y in incorrect: ok = askQuestion(x,y) # could use ok to remove combo from incorrect list. showStats() askQuestions() askFaultyAnswers() print "good-bye!" > > > > > I think it is sensible to > > * first create all possible solutions, then > * kick out doublettes, and only then > * ask questions > > I have some questions though: > > Is the overall structure and flow of this program okay? What are the > main problems you can spot immediately Calculating kicking randomizing is overkill. My code uses a 2 dimension array to track which x,y combos are available. break is only valid within a loop. Recursively calling askQuestions is not a good idea. Save recursion for when it is is meaningful. Use a loop instead. There is no need for an incorrect counter. we can calculate it later (incorrect = NQ -correct) > > In the very end I would like to take this code as a basis for a > wxPython program. Are there any structural requirements I am violating > here? Not that I can see. It is common practice to separate logic from display. > > If I want to limit the number of questions asked, say to 20, would I > operate with slicing methods on the randomised pool? My solution does not use a randomized pool. Just a loop over range(NQ) > > How would you go about showing stats for the second run (i.e. the > FaultyAnswers)? Right now I am thinking of setting the global > variables correct and incorrect to 0 from _within_ askFaultyAnswers; > then I would run showStats() also from _within_ askFaultyAnswers. Good > idea? Yes indeed. That is what I did before reading your comment! Great minds think alike. -- Bob Gailer 919-636-4239 Chapel Hill NC From denis.spir at free.fr Wed Feb 3 09:18:23 2010 From: denis.spir at free.fr (spir) Date: Wed, 3 Feb 2010 09:18:23 +0100 Subject: [Tutor] parse text file In-Reply-To: <9c2c8ffb1002021356y18e9292fl71f1f10ff2bd80d4@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <1c2a2c591002010419n7e7eace6lcc796e4a98ac48a3@mail.gmail.com> <9c2c8ffb1002010730r4bec433n4933881a1508a270@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> <9c2c8ffb1002020633k31dc5810yddc204df660e7c50@mail.gmail.com> <1c2a2c591002020719h438c8f8bgdc607395bf843c0c@mail.gmail.com> <9c2c8ffb1002021039r1d6d4b94j1b0f6ca5ec2a18a9@mail.gmail.com> <1c2a2c591002021311x7a152133qe6e3ed69892f1782@mail.gmail.com> <9c2c8ffb1002021356y18e9292fl71f1f10ff2bd80d4@mail.gmail.com> Message-ID: <20100203091823.5d878d42@o> On Tue, 2 Feb 2010 22:56:22 +0100 Norman Khine wrote: > i am no expert, but there seems to be a bigger difference. > > with repr(), i get: > Sat\\xe9re Maw\\xe9 > > where as you get > > Sat\xc3\xa9re Maw\xc3\xa9 > > repr()'s > ? == \\xe9 > whereas on your version > ? == \xc3\xa9 This is a rather complicated issue mixing python str, unicode string, and their repr(). Kent is right in that the *python string* "\xc3\xa9" is the utf8 formatted representation of '?' (2 bytes). While \xe9 is the *unicode code* for '?', which should only appear in a unicode string. So: unicode.encode(u"\u00e9", "utf8") == "\xc3\xa9" or more simply: u"\u00e9".encode("utf8") == "\xc3\xa9" Conversely: unicode("\xc3\xa9", "utf8") == u"\u00e9" -- decoding The question is: what do you want to do with the result? You'll need either the utf8 form "\xc3\xa9" (for output) or the unicode string u"\u00e9" (for processing). But what you actually get is a kind of mix, actually the (python str) repr of a unicode string. > also, i still get an empty list when i run the code as suggested. ? Strange. Have you checked the re.DOTALL? (else regex patterns stop matching at \n by default) Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From norman at khine.net Wed Feb 3 09:35:04 2010 From: norman at khine.net (Norman Khine) Date: Wed, 3 Feb 2010 09:35:04 +0100 Subject: [Tutor] parse text file In-Reply-To: <1c2a2c591002021436y72b70f69qd4e8ec59c6ef3fb6@mail.gmail.com> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100202093057.6b48bb65@o> <9c2c8ffb1002020116t32b5e4b3tdfc9c640f40707b2@mail.gmail.com> <1c2a2c591002020427w498b7e23r433e2addbf92f9b@mail.gmail.com> <9c2c8ffb1002020633k31dc5810yddc204df660e7c50@mail.gmail.com> <1c2a2c591002020719h438c8f8bgdc607395bf843c0c@mail.gmail.com> <9c2c8ffb1002021039r1d6d4b94j1b0f6ca5ec2a18a9@mail.gmail.com> <1c2a2c591002021311x7a152133qe6e3ed69892f1782@mail.gmail.com> <9c2c8ffb1002021356y18e9292fl71f1f10ff2bd80d4@mail.gmail.com> <1c2a2c591002021436y72b70f69qd4e8ec59c6ef3fb6@mail.gmail.com> Message-ID: <9c2c8ffb1002030035i725d1320la5082b2d8e5af223@mail.gmail.com> On Tue, Feb 2, 2010 at 11:36 PM, Kent Johnson wrote: > On Tue, Feb 2, 2010 at 4:56 PM, Norman Khine wrote: >> On Tue, Feb 2, 2010 at 10:11 PM, Kent Johnson wrote: > >>> Try this version: >>> >>> data = file.read() >>> >>> get_records = re.compile(r"""openInfoWindowHtml\(.*?\ticon: >>> myIcon\n""", re.DOTALL).findall >>> get_titles = re.compile(r"""(.*)<\/strong>""").findall >>> get_urls = re.compile(r"""a href=\"\/(.*)\">En savoir plus""").findall >>> get_latlngs = re.compile(r"""GLatLng\((\-?\d+\.\d*)\,\n\s*(\-?\d+\.\d*)\)""").findall >>> >>> then as before. >>> >>> Your repr() call is essentially removing newlines from the input by >>> converting them to literal '\n' pairs. This allows your regex to work >>> without the DOTALL modifier. >>> >>> Note you will get slightly different results with my version - it will >>> give you correct utf-8 text for the titles whereas yours gives \ >>> escapes. For example one of the titles is "CGTSM (Sat?re Maw?)". Your >>> version returns >>> >>> {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804', >>> '-79.649735'), 'title': 'CGTSM (Sat\\xe9re Maw\\xe9)'} >>> >>> Mine gives >>> {'url': 'cgtsm-satere-mawe.html', 'lating': ('-2.77804', >>> '-79.649735'), 'title': 'CGTSM (Sat\xc3\xa9re Maw\xc3\xa9)'} >>> >>> This is showing the repr() of the title so they both have \ but note >>> that yours has two \\ indicating that the \ is in the text; mine has >>> only one \. >> >> i am no expert, but there seems to be a bigger difference. >> >> with repr(), i get: >> Sat\\xe9re Maw\\xe9 >> >> where as you get >> >> Sat\xc3\xa9re Maw\xc3\xa9 >> >> repr()'s >> ? == \\xe9 >> whereas on your version >> ? == \xc3\xa9 > > Right. Your version has four actual characters in the result - \, x, > e, 9. This is the escaped representation of the unicode representation > of e-acute. (The \ is doubled in the repr display.) > > My version has two bytes in the result, with the values c3 and a9. > This is the utf-8 representation of e-acute. > > If you want to accurately represent (i.e. print) the title at some > later time you probably want the utf-8 represetation. >> >>> >>> Kent >>> >> >> also, i still get an empty list when i run the code as suggested. > > You didn't change the regexes. You have to change \\t and \\n to \t > and \n because the source text now has actual tabs and newlines, not > the escaped representations. > > I know this is confusing, I'm sorry I don't have time or patience to > explain more. thanks for your time, i did realise after i posted the email that the regex needed to be changed. > > Kent > From ldl08 at gmx.net Wed Feb 3 10:06:09 2010 From: ldl08 at gmx.net (David) Date: Wed, 03 Feb 2010 17:06:09 +0800 Subject: [Tutor] help with random.randint (cont. -- now: pseudo code) In-Reply-To: <4B6929F3.20008@gmail.com> References: <4B68EBD4.4090503@gmx.net> <9b00d1a91002022025p2b20ba86w18f4f6c12f9e41e2@mail.gmail.com> <4B6913DA.4020002@gmx.net> <4B6929F3.20008@gmail.com> Message-ID: <4B693C81.5000707@gmx.net> Bob, brilliant stuff -- I am truly awed by this. Create a default-filled matrix and mark combinations used so as to take them out of the game? Wow. This is new to me. On 03/02/10 15:46, bob gailer wrote > def askQuestions(): # generate and ask questions: > for i in range(NQ): > while 1: # loop till we get an unused combo > x, y = [random.randint(1,MAX) for i in 'ab'] > if mtable[x][y] == 1: # combo is available > break > askQuestion(x,y) > # indicate asked > mtable[x][y] = 0 > mtable[y][x] = 0 Here you lose me, though. Where does mtable come from, what does it do? You don't introduce it as a variable, and when I google it, nothing much comes of if... David From hugo.yoshi at gmail.com Wed Feb 3 10:17:59 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 3 Feb 2010 10:17:59 +0100 Subject: [Tutor] help with random.randint In-Reply-To: <4B692373.3090404@gmx.net> References: <4B68EBD4.4090503@gmx.net> <4B691CF8.8040509@gmail.com> <4B692373.3090404@gmx.net> Message-ID: <29179d161002030117i519fa4dfsbf42e925a4f15d00@mail.gmail.com> On Wed, Feb 3, 2010 at 8:19 AM, David wrote: > Hello Bob, > > thanks for your comments! > > > On 03/02/10 14:51, bob gailer wrote: > >> or if you seek terseness: >> >> terms = [random.randint(1, 99) for i in 'ab'] > > Do I understand correctly that 'ab' here merely serves to produce a 'dummy > sequence' over which I can run the for loop? > That is correct. you could have used any two-character sequence. I think the range(2) call is clearer and more pythonic though. And it's not that much longer Hugo From hugo.yoshi at gmail.com Wed Feb 3 10:46:27 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 3 Feb 2010 10:46:27 +0100 Subject: [Tutor] help with random.randint (cont. -- now: pseudo code) In-Reply-To: <4B693C81.5000707@gmx.net> References: <4B68EBD4.4090503@gmx.net> <9b00d1a91002022025p2b20ba86w18f4f6c12f9e41e2@mail.gmail.com> <4B6913DA.4020002@gmx.net> <4B6929F3.20008@gmail.com> <4B693C81.5000707@gmx.net> Message-ID: <29179d161002030146l70bc2135oa3bb79d2ccc9aa4b@mail.gmail.com> On Wed, Feb 3, 2010 at 10:06 AM, David wrote: > Bob, > > brilliant stuff -- I am truly awed by this. Create a default-filled matrix > and mark combinations used so as to take them out of the game? Wow. This is > new to me. > > On 03/02/10 15:46, bob gailer wrote > >> def askQuestions(): # generate and ask questions: >> for i in range(NQ): >> while 1: # loop till we get an unused combo >> x, y = [random.randint(1,MAX) for i in 'ab'] >> if mtable[x][y] == 1: # combo is available >> break >> askQuestion(x,y) >> # indicate asked >> mtable[x][y] = 0 >> mtable[y][x] = 0 > > Here you lose me, though. Where does mtable come from, what does it do? You > don't introduce it as a variable, and when I google it, nothing much comes > of if... > I think mtable should be replaced by the pool variable defined at the top. Then it makes sense. Second, I think a two-dimensional approach is rather wasteful here, it's clearer and simpler to keep a list of generated questions (you already do that anyway), and for each new question answered, do: if (x, y) in generated: continue else: generated.append((x, y)) The random generating approach is more efficient if you're only going to use a small subset of the possible set of questions. If you're going to use almost the entire set, though, calculating them is more efficient, since the random generator will come across more and more duplicates as it fills up the array. Here's an alternative approach that uses itertools.combinations to calculate all possible sequences and then shuffles: import itertools import random # maximum number and number of questions MAX = 20 NQ = 10 def gen_questions(): # start at 2, since 0 * x and 1 * x aren't very interesting q = list(itertools.combinations(range(2, MAX), 2)) random.shuffle(q) return q Note that, if MAX is high, it will take a very long time to generate all possible questions. (1000 was a second or so on my computer, but 10.000 took longer than I was willing to wait). If you're not going to use all of those questions, (and it's likely you won't, since a range of ten numbers already provides 45 different questions), then the random generation is better. Hugo From denis.spir at free.fr Wed Feb 3 11:19:18 2010 From: denis.spir at free.fr (spir) Date: Wed, 3 Feb 2010 11:19:18 +0100 Subject: [Tutor] help with random.randint In-Reply-To: <4B68EBD4.4090503@gmx.net> References: <4B68EBD4.4090503@gmx.net> Message-ID: <20100203111918.395cea3e@o> On Wed, 03 Feb 2010 11:21:56 +0800 David wrote: > Hello list, > > I thought this was easy even for me, but I was wrong, I guess. > Here is what I want to do: take two random numbers between 1 and 99, and > put them into a list. > > import random > terms = [] > for i in range(2): > terms = random.randint(1, 99) > print terms > > This prints just one number (the last one generated in the loop?) Yo, terms now refers to a simple integer. What you want is instead: for i in range(2): term = random.randint(1, 99) terms.append(term) # put new item at end of list print terms > So I tried to change line 4 to the following: > terms += random.randint(1, 99) This is equivalent to terms = terms + random.randint(1, 99) Because the first operand is a list, python won't do an addition (yes, the operator can be misleading, I would personly prefer eg '++' to avoid ambiguity), but a so-called "concatenation" (yes, that word is ugly ;-). This "glues" together 2 sequences (lists or strings). In this case, you get an error because the second operand is not a sequence. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Wed Feb 3 11:33:20 2010 From: denis.spir at free.fr (spir) Date: Wed, 3 Feb 2010 11:33:20 +0100 Subject: [Tutor] help with random.randint (cont. -- now: pseudo code) In-Reply-To: <4B6913DA.4020002@gmx.net> References: <4B68EBD4.4090503@gmx.net> <9b00d1a91002022025p2b20ba86w18f4f6c12f9e41e2@mail.gmail.com> <4B6913DA.4020002@gmx.net> Message-ID: <20100203113320.61b28073@o> On Wed, 03 Feb 2010 14:12:42 +0800 David wrote: > Hello Benno, list, > > thanks for those clarifications, which, well, clarify things ;-) > > This is my latest creation: > > import random > > def createTerms(): > terms = [] > for i in range(2): > terms.append(random.randint(1, 99)) > j = terms[0] > k = terms[1] > print "%3d\nx%2d" % (j, k) > > createTerms() I find j,k = terms clearer. (This will automagically unpack items from terms.) > Which works. However, it merely prints a multiplication task. Anyway, > this was just a prelude. In the end, I want far more, namely to create, > ask, and verify some multiplication questions. Here is my pseudo code of > this little project: > > > > pool = [] > correct = 0 > incorrect = 0 > > def createQuestions: > generate all multiplication combinations possible > append as tuple to pool > eliminate 'mirrored doubles' (i.e. 7x12 and 12x7) Unneeded. Instead building all combinations looping with j=1..n & k=1..n, directly avoid duplicates using j=1..n & k=j..n. (not 100% sure, though) > randomize pool > > def askQuestions: > for question in pool: > calculate solution > take answer from user > if user answer == solution: > correct += 1 > remove question from pool > else: > incorrect += 1 > > def showStats: > print number of questions asked > print number of questions answered correctly > print percentage of correct answers > > def askFaultyAnswers: > answer = raw_input("Try again the incorrect questions? (y/n) ") > if answer == "y": > aksQuestions() > else: > break > > > createQuestions() > askQuestions() > showStats() > askFaultyAnswers() > print "good-bye!" > > > > I think it is sensible to > > * first create all possible solutions, then > * kick out doublettes, and only then > * ask questions > > I have some questions though: > > Is the overall structure and flow of this program okay? What are the > main problems you can spot immediately? > > In the very end I would like to take this code as a basis for a wxPython > program. Are there any structural requirements I am violating here? You should from start on organize your code into funcs that will be so-called "callback functions", meaning functions that will be called by user actions (typically button press). Hope it's clear. This does not prevent an OO structure of the code, indeed, the funcs can well be object methods if this matches the problem. > If I want to limit the number of questions asked, say to 20, would I > operate with slicing methods on the randomised pool? ? > How would you go about showing stats for the second run (i.e. the > FaultyAnswers)? Right now I am thinking of setting the global variables > correct and incorrect to 0 from _within_ askFaultyAnswers; then I would > run showStats() also from _within_ askFaultyAnswers. Good idea? I would have a kind of overall "UserTest" object with methods generating and storing test data (numbers), asking questions and getting answers, recording and outputing results. This is an OO point of view. You may organise things differently (but even then an OO pov sometimes helps structuring a pb). Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From eike.welk at gmx.net Wed Feb 3 12:08:56 2010 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 3 Feb 2010 12:08:56 +0100 Subject: [Tutor] help with random.randint In-Reply-To: <4B68EBD4.4090503@gmx.net> References: <4B68EBD4.4090503@gmx.net> Message-ID: <201002031208.56515.eike.welk@gmx.net> Hello David! On Wednesday February 3 2010 04:21:56 David wrote: > > import random > terms = [] > for i in range(2): > terms = random.randint(1, 99) > print terms Here is an other solution, which is quite easy to understand and short: import random terms = [] for i in range(2): terms += [random.randint(1, 99)] print terms Note the rectangular brackets around "[random.randint(1, 99)]". This creates a list which a single number in it. This small list can then be added to the already existing list "terms". Eike. From ldl08 at gmx.net Wed Feb 3 12:26:43 2010 From: ldl08 at gmx.net (David) Date: Wed, 03 Feb 2010 19:26:43 +0800 Subject: [Tutor] help with random.randint In-Reply-To: <201002031208.56515.eike.welk@gmx.net> References: <4B68EBD4.4090503@gmx.net> <201002031208.56515.eike.welk@gmx.net> Message-ID: <4B695D73.6080209@gmx.net> Hello Eike, thanks for the explanation, all this is really helpful -- I certainly have learned sth. today! I wonder, though, how I would get my number pairs, which I need later on, if I were to follow your solution. I am asking because as I understand your code, the list terms is a list of integers here, but not of x,y pairs, right? (I can see that this was a problem of my code right from the start, btw.) David On 03/02/10 19:08, Eike Welk wrote: > Hello David! > > On Wednesday February 3 2010 04:21:56 David wrote: >> >> import random >> terms = [] >> for i in range(2): >> terms = random.randint(1, 99) >> print terms > > Here is an other solution, which is quite easy to understand and short: > > import random > terms = [] > for i in range(2): > terms += [random.randint(1, 99)] > print terms > > > Note the rectangular brackets around "[random.randint(1, 99)]". This creates a > list which a single number in it. This small list can then be added to the > already existing list "terms". > > > Eike. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From waynejwerner at gmail.com Wed Feb 3 12:37:55 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 3 Feb 2010 05:37:55 -0600 Subject: [Tutor] help with random.randint (cont. -- now: pseudo code) In-Reply-To: <4B6913DA.4020002@gmx.net> References: <4B68EBD4.4090503@gmx.net> <9b00d1a91002022025p2b20ba86w18f4f6c12f9e41e2@mail.gmail.com> <4B6913DA.4020002@gmx.net> Message-ID: <333efb451002030337nec69d3fh856e4838998c3704@mail.gmail.com> On Wed, Feb 3, 2010 at 12:12 AM, David wrote: > def createQuestions: > generate all multiplication combinations possible > append as tuple to pool > eliminate 'mirrored doubles' (i.e. 7x12 and 12x7) > randomize pool > > I haven't really looked through most of this stuff - but your mirrored doubles has a somewhat cleaner solution than generating all then removing the duplicates, I think. Referring to here: http://docs.python.org/reference/expressions.html#notin I *think* you can create a list of all the non-mirrored pairs this way: pool = [] for x in xrange(1,13): for y in xrange(x, 13): pool.append((x,y)) Then I would shuffle the pairs and the pairs within: i.e.: for x in xrange(len(pool)): # We want the index, not just the element if random.randint(0,1): pool[x] = pool[x][::-1] # A simple reversal swaps the values else: pass now you have two options - either shuffle your pool, or pick random elements and pop them out of your list: (this worked at least once on a 10 element list): while pool: pool.pop(random.randint(0, len(pool)-1))) of course you'd probably assign that tuple to some useful value or function call. But that's what I'd do... and given the fact that I was actually planning to make a "game" somewhat like this myself, this gives me a good excuse to write some of the code ^_^ HTH, and thanks for asking a question that motivates, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Feb 3 12:47:35 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 3 Feb 2010 05:47:35 -0600 Subject: [Tutor] help with random.randint In-Reply-To: <4B695D73.6080209@gmx.net> References: <4B68EBD4.4090503@gmx.net> <201002031208.56515.eike.welk@gmx.net> <4B695D73.6080209@gmx.net> Message-ID: <333efb451002030347i63649dcct6b733bed29918169@mail.gmail.com> On Wed, Feb 3, 2010 at 5:26 AM, David wrote: > Hello Eike, > > thanks for the explanation, all this is really helpful -- I certainly have > learned sth. today! > I wonder, though, how I would get my number pairs, which I need later on, > if I were to follow your solution. I am asking because as I understand your > code, the list terms is a list of integers here, but not of x,y pairs, > right? (I can see that this was a problem of my code right from the start, > btw.) > > David I'll refer you to what I posted in (what appeared to me as) your other thread: If you want the unique pairs (i.e. (12,7) is equivalent to (7,12)), I *think* you can do a simple chain: pool = [] for x in xrange(1,13): for y in xrange(x, 13): pool.append((x,y)) because that will give you the sets ordered by the smallest - you'll get 1x1-12, then 2x2-12, etc. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From snisa.balakrishnan at gmail.com Wed Feb 3 14:19:43 2010 From: snisa.balakrishnan at gmail.com (NISA BALAKRISHNAN) Date: Wed, 3 Feb 2010 17:19:43 +0400 Subject: [Tutor] help with strings Message-ID: <8242c3db1002030519n32b5cd6fv5408e43467ac1e73@mail.gmail.com> hi I am very new to python. I have a string for example : 123B new Project i want to separate 123B as a single string and new project as another string . how can i do that. i tried using partition but couldnt do it pls help. thanks in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Feb 3 15:27:56 2010 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 3 Feb 2010 08:27:56 -0600 Subject: [Tutor] help with strings In-Reply-To: <8242c3db1002030519n32b5cd6fv5408e43467ac1e73@mail.gmail.com> References: <8242c3db1002030519n32b5cd6fv5408e43467ac1e73@mail.gmail.com> Message-ID: <1e53c511002030627j47a6e89fu58815369ba35f37f@mail.gmail.com> On Wed, Feb 3, 2010 at 7:19 AM, NISA BALAKRISHNAN < snisa.balakrishnan at gmail.com> wrote: > hi > > I am very new to python. > I have a string for example : 123B new Project > i want to separate 123B as a single string and new project as another > string . > how can i do that. > i tried using partition but couldnt do it > > pls help. > thanks in advance! > > Can we see some example code you are trying? Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From dw at darrenworrall.co.uk Wed Feb 3 16:10:59 2010 From: dw at darrenworrall.co.uk (Darren Worrall) Date: Wed, 03 Feb 2010 15:10:59 +0000 Subject: [Tutor] help with strings In-Reply-To: <8242c3db1002030519n32b5cd6fv5408e43467ac1e73@mail.gmail.com> References: <8242c3db1002030519n32b5cd6fv5408e43467ac1e73@mail.gmail.com> Message-ID: <4B699203.9040809@darrenworrall.co.uk> On 03/02/10 13:19, NISA BALAKRISHNAN wrote: > hi > > I am very new to python. > I have a string for example : 123B new Project > i want to separate 123B as a single string and new project as another > string . > how can i do that. > i tried using partition but couldnt do it > > pls help. > thanks in advance! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Assuming the whitespace isn't relevant, and is just a delimiter: >>> s = '123B new Project' >>> s.split(None, 1) ['123B', 'new Project'] The first argument to split() is the delimiter (or if None, it defaults to whitespace), and the second argument is 'maxsplit' - the amount of splits to make. It's explained well in the documentation[1]. Cheers, Daz [1]http://docs.python.org/library/stdtypes.html#str.split -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Feb 3 16:25:28 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 3 Feb 2010 10:25:28 -0500 Subject: [Tutor] help with strings In-Reply-To: <8242c3db1002030519n32b5cd6fv5408e43467ac1e73@mail.gmail.com> References: <8242c3db1002030519n32b5cd6fv5408e43467ac1e73@mail.gmail.com> Message-ID: <1c2a2c591002030725r14062776mb74b055f68e3a8b3@mail.gmail.com> On Wed, Feb 3, 2010 at 8:19 AM, NISA BALAKRISHNAN wrote: > hi > > I am very new to python. > I have a string for example : 123B? ?? new Project > i want to separate 123B as a single string and new? project as another > string . > how can i do that. > i tried using partition but couldnt do it str.split() is the thing to use. By default it splits on any white space: In [1]: s = "123B new Project" In [2]: s.split() Out[2]: ['123B', 'new', 'Project'] You can tell it to only split once (the None argument means "split on white space"): In [5]: s.split(None, 1) Out[5]: ['123B', 'new Project'] The result is a list; you can assign each element to a variable: In [6]: first, second = s.split(None, 1) In [7]: first Out[7]: '123B' In [8]: second Out[8]: 'new Project' Kent From eike.welk at gmx.net Wed Feb 3 20:34:34 2010 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 3 Feb 2010 20:34:34 +0100 Subject: [Tutor] help with random.randint In-Reply-To: <4B695D73.6080209@gmx.net> References: <4B68EBD4.4090503@gmx.net> <201002031208.56515.eike.welk@gmx.net> <4B695D73.6080209@gmx.net> Message-ID: <201002032034.34190.eike.welk@gmx.net> On Wednesday February 3 2010 12:26:43 David wrote: > thanks for the explanation, all this is really helpful -- I certainly > have learned sth. today! > I wonder, though, how I would get my number pairs, which I need later > on, if I were to follow your solution. I am asking because as I > understand your code, the list terms is a list of integers here, but not > of x,y pairs, right? (I can see that this was a problem of my code right > from the start, btw.) Maybe I don't understand you correctly; but if you know that you only need two random numbers I would create the list like this: import random xy = [random.randint(1, 99), random.randint(1, 99)] Or maybe a use tuple and a little code beautification: import random randint = random.randint xy = (randint(1, 99), randint(1, 99)) Off course you can put these small lists or tuples into another list: import random randint = random.randint num_terms = 5 terms = [] for i in range(num_terms): terms += [(randint(1, 99), randint(1, 99))] print terms Eike. From simbobo at cooptel.net Thu Feb 4 11:43:26 2010 From: simbobo at cooptel.net (Owain Clarke) Date: Thu, 04 Feb 2010 10:43:26 +0000 Subject: [Tutor] language aid In-Reply-To: References: Message-ID: <4B6AA4CE.7040702@cooptel.net> Hello, all. I am a newcomer to Python, and I know that I have much learning to do before I implement my idea, but I am working on the beginnings of a vocabulary building program. This is how I am catching new words at the moment. def newVocab(x,y): """ Add new word pair, English word second. Words to be separated by ':' """ x.append(y) I can follow this with french = [] newVocab(french,"souris:mouse") The idea is that eventually the user would be prompted to enter a french (or whatever) word, and then to enter its English equivalent. The code would then be responsible for adding the ":" storing all the words in a list which would be written to a file, and recovering them as needed. Although i don't know how at this point, I assume I can search the part of the string before the colon or after, and thus set up vocabulary tests. My question is, that if I proceed like this I will end up with a single list of potentially several hundred strings of the form "frword:engword". In terms of performance, is this a reasonable way to do it, or will the program increasingly slow down? All suggestions appreciated Owain Clarke From fomcl at yahoo.com Thu Feb 4 16:39:29 2010 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 4 Feb 2010 07:39:29 -0800 (PST) Subject: [Tutor] language aid In-Reply-To: <4B6AA4CE.7040702@cooptel.net> Message-ID: <299682.63904.qm@web110707.mail.gq1.yahoo.com> Hi, ? A dictionary (associative array of keys and values) seems a good datatype to use. vocab = {} vocab[frenchword]?= englishword ? For instance: >>> vocab = {"aimer": "love"} >>> vocab {'aimer': 'love'} >>> vocab["parler"] = "speak" >>> vocab {'aimer': 'love', 'parler': 'speak'} >>> for engword, frword in vocab.iteritems(): ?print "%s - %s" % (engword, frword) ?aimer - love parler - speak ? But if one word has different meanings in the other language, you may need to use a list of words as the values. Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the face of ambiguity, refuse the temptation to guess. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- On Thu, 2/4/10, Owain Clarke wrote: From: Owain Clarke Subject: [Tutor] language aid To: tutor at python.org Date: Thursday, February 4, 2010, 11:43 AM Hello, all. I am a newcomer to Python, and I know that I have much learning to do before I implement my idea, but I am working on the beginnings of a vocabulary building program. This is how I am catching new words at the moment. def newVocab(x,y): """ Add new word pair, English word second. Words to be separated by ':' """ x.append(y) I can follow this with french = [] newVocab(french,"souris:mouse") The idea is that eventually the user would be prompted to enter a french (or whatever) word, and then to enter its English equivalent. The code would then be responsible for adding the ":" storing all the words in a list which would be written to a file, and recovering them as needed. Although i don't know how at this point, I assume I can search the part of the string before the colon or after, and thus set up vocabulary tests. My question is, that if I proceed like this I will end up with a single list of potentially several hundred strings of the form "frword:engword". In terms of performance, is this a reasonable way to do it, or will the program increasingly slow down? All suggestions appreciated Owain Clarke _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From simbobo at cooptel.net Thu Feb 4 17:11:33 2010 From: simbobo at cooptel.net (Owain Clarke) Date: Thu, 04 Feb 2010 16:11:33 +0000 Subject: [Tutor] language aid In-Reply-To: <299682.63904.qm@web110707.mail.gq1.yahoo.com> References: <299682.63904.qm@web110707.mail.gq1.yahoo.com> Message-ID: <4B6AF1B5.9030206@cooptel.net> An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Thu Feb 4 18:11:24 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 4 Feb 2010 12:11:24 -0500 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal Message-ID: Hi folks, A few months back I posted my first (and only) "recipe" to ActiveState. It was just a little function to convert an integer or its string representation to an ordinal value: 1 to 1st, 2 to 2nd, etc. Not sure if this really qualifies as a recipe, per se, but it was a handy little function that I needed but couldn't find in Pythonic version elsewhere on the web (perhaps because it's so simple?). The inspiration for the function was a similar one in Django and some Java code I found online. So I figured I'd share the code once I got it working. I just noticed, however, that in the comments section of the ActiveState recipe that someone is getting incorrect results for certain numbers (11 and 12, specifically). But when I use the code on my own machine it still works fine. So I was hoping that you all could help me "crowdsource" the issue. If you have the time and inclination, could you look at the code and tell me if and where I've gone wrong? And of course, if there's a simpler way to perform the conversion I'd be glad to update the recipe. I certainly don't want something out in the wilds of the Web that's incorrect, inelegant or just plain confusing. Here's the link to the recipe: http://code.activestate.com/recipes/576888/ Your advice, as always, is appreciated. Regards, Serdar From denis.spir at free.fr Thu Feb 4 18:31:44 2010 From: denis.spir at free.fr (spir) Date: Thu, 4 Feb 2010 18:31:44 +0100 Subject: [Tutor] language aid In-Reply-To: <299682.63904.qm@web110707.mail.gq1.yahoo.com> References: <4B6AA4CE.7040702@cooptel.net> <299682.63904.qm@web110707.mail.gq1.yahoo.com> Message-ID: <20100204183144.6142eeb9@o> On Thu, 4 Feb 2010 07:39:29 -0800 (PST) Albert-Jan Roskam wrote: > Hi, > ? > A dictionary (associative array of keys and values) seems a good datatype to use. > vocab = {} > vocab[frenchword]?= englishword > ? > For instance: > >>> vocab = {"aimer": "love"} > >>> vocab > {'aimer': 'love'} > >>> vocab["parler"] = "speak" > >>> vocab > {'aimer': 'love', 'parler': 'speak'} > >>> for engword, frword in vocab.iteritems(): > ?print "%s - %s" % (engword, frword) > ?aimer - love > parler - speak > ? > But if one word has different meanings in the other language, you may need to use a list of words as the values. > > Cheers!! > Albert-Jan Sure, a dict is the obvious choice. For saving into file, if the app is to be used internally, you can even print it in the form of a python dict (with the '{}', ':' & ',') so that reading the dict data is just importing: import french_english Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Thu Feb 4 18:34:25 2010 From: denis.spir at free.fr (spir) Date: Thu, 4 Feb 2010 18:34:25 +0100 Subject: [Tutor] language aid In-Reply-To: <4B6AF1B5.9030206@cooptel.net> References: <299682.63904.qm@web110707.mail.gq1.yahoo.com> <4B6AF1B5.9030206@cooptel.net> Message-ID: <20100204183425.483442b0@o> On Thu, 04 Feb 2010 16:11:33 +0000 Owain Clarke wrote: > But if one word has different meanings in the other language, you may need to use a list of words as the values. ? You can have a more sophisticated structure for you dict. For instance, "love" is both a noun and a verb, and each has several acception. The value for each word may be structured to reflect this possibility. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From alan.gauld at btinternet.com Thu Feb 4 18:39:37 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Feb 2010 17:39:37 -0000 Subject: [Tutor] language aid References: <299682.63904.qm@web110707.mail.gq1.yahoo.com> <4B6AF1B5.9030206@cooptel.net> Message-ID: "Owain Clarke" wrote > I had discounted the idea of a dictionary because all the keys need to be > unique, Thats true but the values can be lists and do not need to be unique. Its probably a better starting point that search through a list looking at every item. > so whether the key is the English or non-English word, it couldn't cope > with > for example "too", or a similar word in the other language. Why not? There is only one word 'too'? I'm not sure what you see as the problem here? I can see an issue where the word can be translated multiple ways, but I don't see how your list of colon separated pairs is any better? You still have the same issues to deal with - I think? However, if you do want to pursue that route it would be better to save the pairs as tuples rather than as x:y strings. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From denis.spir at free.fr Thu Feb 4 18:42:26 2010 From: denis.spir at free.fr (spir) Date: Thu, 4 Feb 2010 18:42:26 +0100 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: References: Message-ID: <20100204184226.552240f0@o> On Thu, 4 Feb 2010 12:11:24 -0500 Serdar Tumgoren wrote: > Hi folks, > > A few months back I posted my first (and only) "recipe" to > ActiveState. It was just a little function to convert an integer or > its string representation to an ordinal value: 1 to 1st, 2 to 2nd, > etc. > > Not sure if this really qualifies as a recipe, per se, but it was a > handy little function that I needed but couldn't find in Pythonic > version elsewhere on the web (perhaps because it's so simple?). The > inspiration for the function was a similar one in Django and some Java > code I found online. So I figured I'd share the code once I got it > working. > > I just noticed, however, that in the comments section of the > ActiveState recipe that someone is getting incorrect results for > certain numbers (11 and 12, specifically). > > But when I use the code on my own machine it still works fine. So I > was hoping that you all could help me "crowdsource" the issue. If you > have the time and inclination, could you look at the code and tell me > if and where I've gone wrong? And of course, if there's a simpler way > to perform the conversion I'd be glad to update the recipe. I > certainly don't want something out in the wilds of the Web that's > incorrect, inelegant or just plain confusing. > > Here's the link to the recipe: > > http://code.activestate.com/recipes/576888/ > > Your advice, as always, is appreciated. > > Regards, > Serdar No time to search for the issue, but here are some trials (hole from 10 --> 19): for i in range(21): print "%s\t: %s" %(i,ordinal(i)) for i in (-1,22,33,99,100,101,199,200,999,1000): print "%s\t: %s" %(i,ordinal(i)) ==> 0 : 0th 1 : 1st 2 : 2nd 3 : 3rd 4 : 4th 5 : 5th 6 : 6th 7 : 7th 8 : 8th 9 : 9th 10 : None 11 : None 12 : None 13 : None 14 : None 15 : None 16 : None 17 : None 18 : None 19 : None 20 : 20th -1 : -1th 22 : 22nd 33 : 33rd 99 : 99th 100 : 100th 101 : 101st 102 : 102nd 103 : 103rd 199 : 199th 200 : 200th 999 : 999th 1000 : 1000th Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From waynejwerner at gmail.com Thu Feb 4 18:45:09 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 4 Feb 2010 11:45:09 -0600 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: References: Message-ID: <333efb451002040945v5334e303r9cff5f884c1b38c9@mail.gmail.com> On Thu, Feb 4, 2010 at 11:11 AM, Serdar Tumgoren wrote: > Hi folks, > > I just noticed, however, that in the comments section of the > ActiveState recipe that someone is getting incorrect results for > certain numbers (11 and 12, specifically). > > But when I use the code on my own machine it still works fine. So I > was hoping that you all could help me "crowdsource" the issue. If you > have the time and inclination, could you look at the code and tell me > if and where I've gone wrong? And of course, if there's a simpler way > to perform the conversion I'd be glad to update the recipe. I > certainly don't want something out in the wilds of the Web that's > incorrect, inelegant or just plain confusing. > > Here's the link to the recipe: > > http://code.activestate.com/recipes/576888/ > > Well at first I was getting "None" for 11 and 12. The following conversion fixed that problem: if value % 100/10 <> 1: to if value % 100/10.0 <> 1: But I'm still getting weird output: for x in (1,2,3,11,4, 12,19,101): print ordinal(x) Follows: 1st 2nd 3rd 11st 4th 12nd 19th 101st Where 11 and 12 should be 11th and 12th. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From aharrisreid at googlemail.com Thu Feb 4 18:47:02 2010 From: aharrisreid at googlemail.com (Alan Harris-Reid) Date: Thu, 04 Feb 2010 17:47:02 +0000 Subject: [Tutor] Help with cursors please In-Reply-To: References: Message-ID: <4B6B0816.5000106@googlemail.com> Hi, I have a SQLite cursor which I want to traverse more than once, eg... for row in MyCursor: method1(row) then later... for row in MyCursor: method2(row) Method2 is never run, I guess because the pointer is at the bottom of the row 'stack' after the first 'for' loop How can I move the pointer back to the top of the stack? Or do I have to reload the cursor first? Any help would be appreciated. Alan From denis.spir at free.fr Thu Feb 4 18:35:01 2010 From: denis.spir at free.fr (spir) Date: Thu, 4 Feb 2010 18:35:01 +0100 Subject: [Tutor] language aid In-Reply-To: <4B6AF1B5.9030206@cooptel.net> References: <299682.63904.qm@web110707.mail.gq1.yahoo.com> <4B6AF1B5.9030206@cooptel.net> Message-ID: <20100204183501.63843032@o> On Thu, 04 Feb 2010 16:11:33 +0000 Owain Clarke wrote: > But if one word has different meanings in the other language, you may need to use a list of words as the values. ? You can have a more sophisticated structure for you dict. For instance, "love" is both a noun and a verb, and each has several acception. The value for each word may be structured to reflect this possibility. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From alan.gauld at btinternet.com Thu Feb 4 18:52:25 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Feb 2010 17:52:25 -0000 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal References: Message-ID: "Serdar Tumgoren" wrote > was hoping that you all could help me "crowdsource" the issue. If you > have the time and inclination, could you look at the code and tell me > if and where I've gone wrong? Not sure about the reported bugs but some comments: What happens if if value % 100/10 <> 1is false? eg. 110-119There is no else so the function will return None.Or do you have future divisuion turned on?In that case the if will only error on 110...Also <> is deprecated - and not allowed in v3 so you should probably change it to !=-- Alan GauldAuthor of the Learn to Program web sitehttp://www.alan-g.me.uk/ From kent37 at tds.net Thu Feb 4 19:02:04 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Feb 2010 13:02:04 -0500 Subject: [Tutor] language aid In-Reply-To: <4B6AA4CE.7040702@cooptel.net> References: <4B6AA4CE.7040702@cooptel.net> Message-ID: <1c2a2c591002041002o1398e314gcbf56459aebe8099@mail.gmail.com> On Thu, Feb 4, 2010 at 5:43 AM, Owain Clarke wrote: > My question is, that if I proceed like this I will end up with a single list > of potentially several hundred strings of the form "frword:engword". In > terms of performance, is this a reasonable way to do it, or will the program > increasingly slow down? Python can easily handle lists of several hundred items. You might be interested in googling "Python flash card" to see what others have done. Kent From zstumgoren at gmail.com Thu Feb 4 19:07:04 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 4 Feb 2010 13:07:04 -0500 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: <20100204184226.552240f0@o> References: <20100204184226.552240f0@o> Message-ID: > No time to search for the issue, but here are some trials (hole from 10 --> 19): > for i in range(21): > ? ? ? ?print "%s\t: %s" %(i,ordinal(i)) > for i in (-1,22,33,99,100,101,199,200,999,1000): > ? ? ? ?print "%s\t: %s" %(i,ordinal(i)) > ==> > 0 ? ? ? : 0th > 1 ? ? ? : 1st > 2 ? ? ? : 2nd > 3 ? ? ? : 3rd > 4 ? ? ? : 4th > 5 ? ? ? : 5th > 6 ? ? ? : 6th > 7 ? ? ? : 7th > 8 ? ? ? : 8th > 9 ? ? ? : 9th > 10 ? ? ?: None > 11 ? ? ?: None > 12 ? ? ?: None > 13 ? ? ?: None > 14 ? ? ?: None > 15 ? ? ?: None > 16 ? ? ?: None > 17 ? ? ?: None > 18 ? ? ?: None > 19 ? ? ?: None > 20 ? ? ?: 20th > -1 ? ? ?: -1th > 22 ? ? ?: 22nd > 33 ? ? ?: 33rd > 99 ? ? ?: 99th > 100 ? ? : 100th > 101 ? ? : 101st > 102 ? ? : 102nd > 103 ? ? : 103rd > 199 ? ? : 199th > 200 ? ? : 200th > 999 ? ? : 999th > 1000 ? ?: 1000th > Okay, this is *really* strange. I performed the exact same tests as above in IPython and I'm getting correct results (though I'm embarrassed to admit I didn't consider negative numbers and doubly embarrassed to admit that I'm not certain whether those should be a mirror image of the positves...). Below are the results I'm getting. Is it at all possible that this could be a bug specific to my Python version, operating system or something similar? I'll admit, this one's a bit over my head... In [4]: for i in range(21): ...: print ordinal(i) ...: ...: 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th In [5]: for i in (-1,22,33,99,100,101,199,200,999,1000): ...: ordinal(i) ...: ...: Out[5]: u'-1th' Out[5]: u'22nd' Out[5]: u'33rd' Out[5]: u'99th' Out[5]: u'100th' Out[5]: u'101st' Out[5]: u'199th' Out[5]: u'200th' Out[5]: u'999th' Out[5]: u'1000th' In [7]: for i in range(21): ...: print "%s\t: %s" %(i,ordinal(i)) ...: 0 : 0th 1 : 1st 2 : 2nd 3 : 3rd 4 : 4th 5 : 5th 6 : 6th 7 : 7th 8 : 8th 9 : 9th 10 : 10th 11 : 11th 12 : 12th 13 : 13th 14 : 14th 15 : 15th 16 : 16th 17 : 17th 18 : 18th 19 : 19th 20 : 20th From jecarnell at saintfrancis.com Thu Feb 4 19:09:18 2010 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Thu, 4 Feb 2010 12:09:18 -0600 Subject: [Tutor] language aid In-Reply-To: Message-ID: > Hi, > ? > A dictionary (associative array of keys and values) seems a good > datatype to use. vocab = {} vocab[frenchword]?= englishword > ? ....... > Cheers!! > Albert-Jan Sure, a dict is the obvious choice. For saving into file, if the app is to be used internally, you can even print it in the form of a python dict (with the '{}', ':' & ',') so that reading the dict data is just importing: import french_english Denis I 3rd the dictionary choice. They (for me at least) aren't as clean on the computer screen as arrays, but once you get good at it you can even have multiple definitions and weights for how relevant that word is. You (in the future when you get comfortable with dictionaries) can take it into networkx or something and draw pictures of it, and really start messing around with it (using subnetworks to try and get context information). Google has some tech talks on youtube concerning Language Processing using networks etc if that kind of thing interests you. Sincerely, Bad answer man From kent37 at tds.net Thu Feb 4 19:09:57 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Feb 2010 13:09:57 -0500 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: References: Message-ID: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> On Thu, Feb 4, 2010 at 12:11 PM, Serdar Tumgoren wrote: > I just noticed, however, that in the comments section of the > ActiveState recipe that someone is getting incorrect results for > certain numbers (11 and 12, specifically). > > But when I use the code on my own machine it still works fine. So I > was hoping that you all could help me "crowdsource" the issue. If you > have the time and inclination, could you look at the code and tell me > if and where I've gone wrong? And of course, if there's a simpler way > to perform the conversion I'd be glad to update the recipe. ?I > certainly don't want something out in the wilds of the Web that's > incorrect, inelegant or just plain confusing. > > Here's the link to the recipe: > > http://code.activestate.com/recipes/576888/ Perhaps the code on activestate is not a correct copy of what you are running? The conditional at line 23 extends all the way to line 35 - the end of the function - so if value % 100/10 == 1 no more code is executed and None is returned. Kent From kent37 at tds.net Thu Feb 4 19:12:25 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Feb 2010 13:12:25 -0500 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> References: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> Message-ID: <1c2a2c591002041012g2d6079ceh5a84f44d3afad994@mail.gmail.com> On Thu, Feb 4, 2010 at 1:09 PM, Kent Johnson wrote: > On Thu, Feb 4, 2010 at 12:11 PM, Serdar Tumgoren wrote: >> Here's the link to the recipe: >> >> http://code.activestate.com/recipes/576888/ > > Perhaps the code on activestate is not a correct copy of what you are > running? The conditional at line 23 extends all the way to line 35 - > the end of the function - so if value % 100/10 == 1 no more code is > executed and None is returned. If I delete line 33 and move lines 34 and 35 left to match line 23 then the tests pass. Kent From kent37 at tds.net Thu Feb 4 19:14:37 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Feb 2010 13:14:37 -0500 Subject: [Tutor] Help with cursors please In-Reply-To: <4B6B0816.5000106@googlemail.com> References: <4B6B0816.5000106@googlemail.com> Message-ID: <1c2a2c591002041014y67d169fbt781f8cc06a8a5179@mail.gmail.com> On Thu, Feb 4, 2010 at 12:47 PM, Alan Harris-Reid wrote: > Hi, > > I have a SQLite cursor which I want to traverse more than once, eg... > for row in MyCursor: > ? method1(row) > ?then later... > for row in MyCursor: > ? method2(row) > ?Method2 is never run, I guess because the pointer is at the bottom of the > row 'stack' after the first 'for' loop > > How can I move the pointer back to the top of the stack? ?Or do I have to > reload the cursor first? Either reload the cursor or use fetchall() to get the results into a list and iterate the list. rows = MyCursor.fetchall() for row in rows; ... Kent From alan.plum at uni-koeln.de Thu Feb 4 19:19:47 2010 From: alan.plum at uni-koeln.de (Alan Plum) Date: Thu, 04 Feb 2010 19:19:47 +0100 Subject: [Tutor] language aid In-Reply-To: <4B6AF1B5.9030206@cooptel.net> References: <299682.63904.qm@web110707.mail.gq1.yahoo.com> <4B6AF1B5.9030206@cooptel.net> Message-ID: <1265307587.10348.5.camel@kallisti> On Do, 2010-02-04 at 16:11 +0000, Owain Clarke wrote: > Thanks for your input. I had discounted the idea of a dictionary > because all the keys need to be unique, so whether the key is the > English or non-English word, it couldn't cope with for example "too", > or a similar word in the other language. I recently began writing a word trainer myself. I used YAML files as source, but the problems were the same. If you have word pairs where either word can be duplicate (e.g. "love" as a verb or a noun) you can deal with that by using a list of tuples. words = [] w = ('aimer', 'love') words.append(w) The only problem with this approach is that it's not as easy to use as a dict, but as I was doing a word trainer, it was supposed to be randomly accessed anyway. Cheers, Alan Plum From zstumgoren at gmail.com Thu Feb 4 19:21:38 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 4 Feb 2010 13:21:38 -0500 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> References: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> Message-ID: > Perhaps the code on activestate is not a correct copy of what you are > running? The conditional at line 23 extends all the way to line 35 - > the end of the function - so if value % 100/10 == 1 no more code is > executed and None is returned. > Here is the code that I'm running locally (hopefully the formatting doesn't get screwed up): def ordinal(value): """ Converts an integer to it's ordinal as a string. For example 1 to "1st", 2 to "2nd", 3 to "3rd", etc. """ try: value = int(value) except ValueError: return value if value % 100/10 <> 1: if value % 10 == 1: ord = u"%d%s" % (value, "st") return ord elif value % 10 == 2: ord = u"%d%s" % (value, "nd") return ord elif value % 10 == 3: ord = u"%d%s" % (value, "rd") return ord else: ord = u"%d%s" % (value, "th") return ord else: ord = u"%d%s" % (value, "th") return ord I had eyeballed the ActiveCode and compared to my local code, and it looked identical...but perhaps it was too cursory a check. I'll download a copy from ActiveState and compare to my local code. If that doesn't turn up a solution, I'll also do some investigating on the modulus operator any possible differences between its implementation/operation between versions of Python. If it helps, I'm using Python 2.6.2... Thank you all for the tips so far! Serdar From zstumgoren at gmail.com Thu Feb 4 19:30:48 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 4 Feb 2010 13:30:48 -0500 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: References: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> Message-ID: On Thu, Feb 4, 2010 at 1:21 PM, Serdar Tumgoren wrote: >> Perhaps the code on activestate is not a correct copy of what you are >> running? The conditional at line 23 extends all the way to line 35 - >> the end of the function - so if value % 100/10 == 1 no more code is >> executed and None is returned. >> > > Here is the code that I'm running locally (hopefully the formatting > doesn't get screwed up): > > def ordinal(value): > ? ?""" > ? ?Converts an integer to it's ordinal as a string. > ? ?For example 1 to "1st", 2 to "2nd", 3 to "3rd", etc. > ? ?""" > ? ?try: > ? ? ? ?value = int(value) > ? ?except ValueError: > ? ? ? ?return value > > ? ?if value % 100/10 <> 1: > ? ? ? ?if value % 10 == 1: > ? ? ? ? ? ?ord = u"%d%s" % (value, "st") > ? ? ? ? ? ?return ord > ? ? ? ?elif value % 10 == 2: > ? ? ? ? ? ?ord = u"%d%s" % (value, "nd") > ? ? ? ? ? ?return ord > ? ? ? ?elif value % 10 == 3: > ? ? ? ? ? ?ord = u"%d%s" % (value, "rd") > ? ? ? ? ? ?return ord > ? ? ? ?else: > ? ? ? ? ? ?ord = u"%d%s" % (value, "th") > ? ? ? ? ? ?return ord > ? ?else: > ? ? ? ?ord = u"%d%s" % (value, "th") > ? ? ? ?return ?ord > Geez -- I think I found the (now-obvious) mistake. If you compare the above to the ActiveState recipe, it's obvious that I forgot to copy over the final, outer "else:" clause. Could you all indulge me one last time and tell me if the above version works for you? If so, I'll update the recipe to spare others a similar headache. And yes, I get the idiot award for the day... Regards, Serdar From waynejwerner at gmail.com Thu Feb 4 20:19:25 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 4 Feb 2010 13:19:25 -0600 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: References: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> Message-ID: <333efb451002041119g7db7afa8hacca05fa28821375@mail.gmail.com> On Thu, Feb 4, 2010 at 12:30 PM, Serdar Tumgoren wrote: > > Geez -- I think I found the (now-obvious) mistake. If you compare the > above to the ActiveState recipe, it's obvious that I forgot to copy > over the final, outer "else:" clause. > > Could you all indulge me one last time and tell me if the above > version works for you? If so, I'll update the recipe to spare others a > similar headache. > > Seems to work for me... > And yes, I get the idiot award for the day... > And now you'll use "diff" a little more religiously, eh? ;) I think we've all done similar things at one point or another - even if we were the only ones who knew it :P -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Thu Feb 4 20:26:25 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 04 Feb 2010 20:26:25 +0100 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: References: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> Message-ID: <1265311585.9467.33.camel@infirit> On do, 2010-02-04 at 13:30 -0500, Serdar Tumgoren wrote: > Could you all indulge me one last time and tell me if the above > version works for you? If so, I'll update the recipe to spare others a > similar headache. It now works ok but.. You should not use ord as variable as ord() is used by python already. Also this will fail in python 3 and 2 with import from future, it does division differently. >>> from __future__ import division >>> 11 % 100 / 10 1.1000000000000001 So "if value % 100/10 <> 1:" should be "if value < 10 or value > 13:". greets Sander From zstumgoren at gmail.com Thu Feb 4 20:28:50 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 4 Feb 2010 14:28:50 -0500 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: <1265311585.9467.33.camel@infirit> References: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> <1265311585.9467.33.camel@infirit> Message-ID: > It now works ok but.. > > You should not use ord as variable as ord() is used by python already. > > Also this will fail in python 3 and 2 with import from future, it does > division differently. >>>> from __future__ import division >>>> 11 % 100 / 10 > 1.1000000000000001 > > So "if value % 100/10 <> 1:" should be "if value < 10 or value > 13:". > I see. I'll update it accordingly. Many thanks! From ssiverling at gmail.com Thu Feb 4 19:19:49 2010 From: ssiverling at gmail.com (ssiverling) Date: Thu, 4 Feb 2010 10:19:49 -0800 (PST) Subject: [Tutor] Variable: From input and output Message-ID: <27457364.post@talk.nabble.com> Greetings, So I want to learn assembly. However, it can take a experienced C programmer a year to learn assembly. With me it might take longer. One thing I was reading is that alot of the tutorials assume prior programming experience. So I figure I would go with an easier language. So I looked up the MIT's opencourseware. So they are using python for their assignments. http://ocw.mit.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/EEEEAE23-29F5-4F88-9CF3-3E7A668C9846/0/pset0.pdf One of their assignments is to create a program that asks first name, and last name then puts them together. I could program it too ask the name, then just program it with my name but that wouldn't be a quality job. So I have been working on this example for a little while. I looked for the answer before posting. I tried to use two raw inputs, then use sys.stdout.write, to add them together. However I think I might need to use a variable. Any help would be appreciated. Thank you in advance. -- View this message in context: http://old.nabble.com/Variable%3A-From-input-and-output-tp27457364p27457364.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Thu Feb 4 21:40:36 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Feb 2010 15:40:36 -0500 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: References: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> Message-ID: <1c2a2c591002041240i2d7de123j1221ecbbaa9b388@mail.gmail.com> On Thu, Feb 4, 2010 at 1:21 PM, Serdar Tumgoren wrote: >> Perhaps the code on activestate is not a correct copy of what you are >> running? The conditional at line 23 extends all the way to line 35 - >> the end of the function - so if value % 100/10 == 1 no more code is >> executed and None is returned. >> > > Here is the code that I'm running locally (hopefully the formatting > doesn't get screwed up): > > def ordinal(value): > ? ?""" > ? ?Converts an integer to it's ordinal as a string. > ? ?For example 1 to "1st", 2 to "2nd", 3 to "3rd", etc. > ? ?""" > ? ?try: > ? ? ? ?value = int(value) > ? ?except ValueError: > ? ? ? ?return value > > ? ?if value % 100/10 <> 1: > ? ? ? ?if value % 10 == 1: > ? ? ? ? ? ?ord = u"%d%s" % (value, "st") > ? ? ? ? ? ?return ord > ? ? ? ?elif value % 10 == 2: > ? ? ? ? ? ?ord = u"%d%s" % (value, "nd") > ? ? ? ? ? ?return ord > ? ? ? ?elif value % 10 == 3: > ? ? ? ? ? ?ord = u"%d%s" % (value, "rd") > ? ? ? ? ? ?return ord > ? ? ? ?else: > ? ? ? ? ? ?ord = u"%d%s" % (value, "th") > ? ? ? ? ? ?return ord > ? ?else: > ? ? ? ?ord = u"%d%s" % (value, "th") > ? ? ? ?return ?ord There is no need to duplicate the last 'else' clause. All the previous cases return so just make it fall through to the general case: if value % 100/10 <> 1: if value % 10 == 1: ord = u"%d%s" % (value, "st") return ord elif value % 10 == 2: ord = u"%d%s" % (value, "nd") return ord elif value % 10 == 3: ord = u"%d%s" % (value, "rd") return ord ord = u"%d%s" % (value, "th") return ord If you want value % 100/10 to give the same result in Python 2.6 and Python 3 you can use value % 100//10 which will always use integer division. Kent From waynejwerner at gmail.com Thu Feb 4 21:49:04 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 4 Feb 2010 14:49:04 -0600 Subject: [Tutor] Variable: From input and output In-Reply-To: <27457364.post@talk.nabble.com> References: <27457364.post@talk.nabble.com> Message-ID: <333efb451002041249k795e76b6w87af9e2242c5234b@mail.gmail.com> On Thu, Feb 4, 2010 at 12:19 PM, ssiverling wrote: > > Greetings, > > So I want to learn assembly. However, it can take a experienced C > programmer a year to learn assembly. With me it might take longer. One > thing I was reading is that alot of the tutorials assume prior programming > experience. So I figure I would go with an easier language. So I looked > up > the MIT's opencourseware. > > So they are using python for their assignments. > > http://ocw.mit.edu/NR/rdonlyres/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/EEEEAE23-29F5-4F88-9CF3-3E7A668C9846/0/pset0.pdf > One of their assignments is to create a program that asks first name, and > last name then puts them together. I could program it too ask the name, > then just program it with my name but that wouldn't be a quality job. > > So I have been working on this example for a little while. I looked for > the > answer before posting. I tried to use two raw inputs, then use > sys.stdout.write, to add them together. However I think I might need to > use > a variable. Any help would be appreciated. Thank you in advance. > See if this might help: http://docs.python.org/reference/simple_stmts.html#the-print-statement -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Thu Feb 4 21:51:47 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 4 Feb 2010 15:51:47 -0500 Subject: [Tutor] correcting an Active State Recipe for conversion to ordinal In-Reply-To: <1c2a2c591002041240i2d7de123j1221ecbbaa9b388@mail.gmail.com> References: <1c2a2c591002041009r792c8283kf2db938456e1bea7@mail.gmail.com> <1c2a2c591002041240i2d7de123j1221ecbbaa9b388@mail.gmail.com> Message-ID: > If you want value % 100/10 to give the same result in Python 2.6 and > Python 3 you can use value % 100//10 which will always use integer > division. > Kent, thanks for anticipating this. I actually was struggling to figure out how to update the division and wasn't certain how. Below is the fully revised code based on all of your suggestions. At some point I'll try my hand at an update that handles negative integers as well. Meantime, thanks to everyone for the help! As always, you never fail to come through! def ordinal(value): """ Converts a *postivie* integer or its string representation to an ordinal value. >>> for i in range(1,13): ... ordinal(i) ... u'1st' u'2nd' u'3rd' u'4th' u'5th' u'6th' u'7th' u'8th' u'9th' u'10th' u'11th' u'12th' >>> for i in (100, '111', '112',1011): ... ordinal(i) ... u'100th' u'111th' u'112th' u'1011th' """ try: value = int(value) except ValueError: return value if value % 100//10 != 1: if value % 10 == 1: ordval = u"%d%s" % (value, "st") elif value % 10 == 2: ordval = u"%d%s" % (value, "nd") elif value % 10 == 3: ordval = u"%d%s" % (value, "rd") else: ordval = u"%d%s" % (value, "th") else: ordval = u"%d%s" % (value, "th") return ordval if __name__ == '__main__': import doctest doctest.testmod() From kent37 at tds.net Thu Feb 4 21:59:22 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 4 Feb 2010 15:59:22 -0500 Subject: [Tutor] Variable: From input and output In-Reply-To: <27457364.post@talk.nabble.com> References: <27457364.post@talk.nabble.com> Message-ID: <1c2a2c591002041259r604f0b60j341910f644256def@mail.gmail.com> On Thu, Feb 4, 2010 at 1:19 PM, ssiverling wrote: > So I have been working on this example for a little while. ?I looked for the > answer before posting. ?I tried to use two raw inputs, then use > sys.stdout.write, to add them together. ?However I think I might need to use > a variable. ?Any help would be appreciated. ?Thank you in advance. What have you done so far? If you show us some code we can better help you. Kent From alan.gauld at btinternet.com Thu Feb 4 23:22:00 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Feb 2010 22:22:00 -0000 Subject: [Tutor] Variable: From input and output References: <27457364.post@talk.nabble.com> Message-ID: "ssiverling" wrote > So I want to learn assembly. However, it can take a experienced C > programmer a year to learn assembly. Dunno where you got that from. An experienced C programmer should pick up assembler in a few days. C is just "portable assembler" It is almost a textual replacement for assembler. All the different addressing modes of assembler - which confuse higher order language programmers - are all directly translateable into C pointers etc. (Note, I'm talking about pure C, not C++, which is a very different animal!) > thing I was reading is that alot of the tutorials assume prior > programming Thats true of Python too, but there are a few asembler tutorials that still assume zero programming. Unfortunately they do all need you to understand the basics of how a computer is put together - arithmetic unit, memory, registers, IO ports etc Assembler is inextricably tied to the machine. One brilliant book if you can get it (via a library?) is "The Soul of CP/M" Obviously way out of datae since its based on CP/M but the writing style is brilliant and it teaches real world assembler - withh use of BIOS functions to read the keyboard etc and builds a usabletext editor by the end. Some of the very early Peter Norton books are good too, aimed at DOS and the original IBM PC. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Feb 4 23:25:18 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Feb 2010 22:25:18 -0000 Subject: [Tutor] Variable: From input and output References: <27457364.post@talk.nabble.com> Message-ID: "ssiverling" wrote > thing I was reading is that alot of the tutorials assume prior > programming I just checked and Amazon have the Soul of CP/M still available second hand for less than a dollar! Gotta be a bargain! OH, yes, If you want a free PC assembler you can use DOS debug. Its still there in XP, dunno about Vista or Win7. But there are loads of freeware ones too. Alan G. From ssiverling at gmail.com Thu Feb 4 23:29:31 2010 From: ssiverling at gmail.com (ssiverling) Date: Thu, 4 Feb 2010 14:29:31 -0800 (PST) Subject: [Tutor] Variable: From input and output In-Reply-To: <27457364.post@talk.nabble.com> References: <27457364.post@talk.nabble.com> Message-ID: <27460786.post@talk.nabble.com> Greetings, Thank you all for you help. I appreciate your help. Anyway, I thought I was answer something. "Dunno where you got that from. " It was from the book on assembly I was reading. -- View this message in context: http://old.nabble.com/Variable%3A-From-input-and-output-tp27457364p27460786.html Sent from the Python - tutor mailing list archive at Nabble.com. From ssiverling at gmail.com Thu Feb 4 23:39:58 2010 From: ssiverling at gmail.com (ssiverling) Date: Thu, 4 Feb 2010 14:39:58 -0800 (PST) Subject: [Tutor] Variable: From input and output In-Reply-To: <1c2a2c591002041259r604f0b60j341910f644256def@mail.gmail.com> References: <27457364.post@talk.nabble.com> <1c2a2c591002041259r604f0b60j341910f644256def@mail.gmail.com> Message-ID: <27460922.post@talk.nabble.com> I uploaded a file. I know it's not very impressive. Kent Johnson wrote: > > On Thu, Feb 4, 2010 at 1:19 PM, ssiverling wrote: > >> So I have been working on this example for a little while. ?I looked for >> the >> answer before posting. ?I tried to use two raw inputs, then use >> sys.stdout.write, to add them together. ?However I think I might need to >> use >> a variable. ?Any help would be appreciated. ?Thank you in advance. > > What have you done so far? If you show us some code we can better help > you. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > http://old.nabble.com/file/p27460922/psy psy -- View this message in context: http://old.nabble.com/Variable%3A-From-input-and-output-tp27457364p27460922.html Sent from the Python - tutor mailing list archive at Nabble.com. From ssiverling at gmail.com Thu Feb 4 23:42:34 2010 From: ssiverling at gmail.com (ssiverling) Date: Thu, 4 Feb 2010 14:42:34 -0800 (PST) Subject: [Tutor] Variable: From input and output In-Reply-To: References: <27457364.post@talk.nabble.com> Message-ID: <27460955.post@talk.nabble.com> Thank you, yes I still have xp. I heard alot of bad things about vista. Then my parents bought a new computer and they I saw why. Anyway, I'm going to atleast wait till the first service pack come out for Windows 7. Though I am going to upgrade to xp pro. A dollar you said? Hmm.. I might have to check it out. Usually I try and snag free shipping. Alan Gauld wrote: > > > "ssiverling" wrote > >> thing I was reading is that alot of the tutorials assume prior >> programming > > I just checked and Amazon have the Soul of CP/M still available second > hand for less than a dollar! > > Gotta be a bargain! > > OH, yes, If you want a free PC assembler you can use DOS debug. > Its still there in XP, dunno about Vista or Win7. > > But there are loads of freeware ones too. > > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://old.nabble.com/Variable%3A-From-input-and-output-tp27457364p27460955.html Sent from the Python - tutor mailing list archive at Nabble.com. From aharrisreid at googlemail.com Fri Feb 5 04:22:12 2010 From: aharrisreid at googlemail.com (Alan Harris-Reid) Date: Fri, 05 Feb 2010 03:22:12 +0000 Subject: [Tutor] Help with cursors please In-Reply-To: <1c2a2c591002041014y67d169fbt781f8cc06a8a5179@mail.gmail.com> References: <4B6B0816.5000106@googlemail.com> <1c2a2c591002041014y67d169fbt781f8cc06a8a5179@mail.gmail.com> Message-ID: <4B6B8EE4.1080407@googlemail.com> Kent Johnson wrote: > On Thu, Feb 4, 2010 at 12:47 PM, Alan Harris-Reid > wrote: > >> Hi, >> >> I have a SQLite cursor which I want to traverse more than once, eg... >> for row in MyCursor: >> method1(row) >> then later... >> for row in MyCursor: >> method2(row) >> Method2 is never run, I guess because the pointer is at the bottom of the >> row 'stack' after the first 'for' loop >> >> How can I move the pointer back to the top of the stack? Or do I have to >> reload the cursor first? >> > > Either reload the cursor or use fetchall() to get the results into a > list and iterate the list. > > rows = MyCursor.fetchall() > for row in rows; > ... > > > Kent Thanks for the reply Kent. I used fetchall() to get the results into a list and everything works fine now. Regards, Alan -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikunjbadjatya at gmail.com Fri Feb 5 11:08:57 2010 From: nikunjbadjatya at gmail.com (nikunj badjatya) Date: Fri, 5 Feb 2010 15:38:57 +0530 Subject: [Tutor] python function to know the path of the program in execution Message-ID: Hi , Is there any python function to know the path of the python program under execution.? If someone executes a program , he should come to know the path of the program..!! ex. suppose a user ABC is running prog.py which is in ~ directory, the user currently is in XYZ directory. [ ABC at localhost XYZ ]$ python ~/prog.py The program's location is ~/prog.py This should be the outcome of the program. I tried with os.getcwd() os.getcwd() will return /path/to/folder/XYZ. Any suggestions? Thanks, Nikunj Badjatya Bangalore, India -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at yahoo.com Fri Feb 5 11:43:34 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Fri, 5 Feb 2010 02:43:34 -0800 (PST) Subject: [Tutor] python function to know the path of the program in execution In-Reply-To: Message-ID: <54320.17491.qm@web45304.mail.sp1.yahoo.com> --- On Fri, 2/5/10, nikunj badjatya wrote: From: nikunj badjatya Subject: [Tutor] python function to know the path of the program in execution To: tutor at python.org Date: Friday, February 5, 2010, 5:08 AM Hi , Is there any python function to know the path of the python program under execution.? If someone executes a program , he should come to know the path of the program..!! ex. suppose a user ABC is running prog.py which is in ~ directory, the user currently is in XYZ directory. [ ABC at localhost XYZ ]$ python ~/prog.py???????? The program's location is ~/prog.py This should be the outcome of the program. I tried with os.getcwd() os.getcwd() will return /path/to/folder/XYZ. Any suggestions? ? Thanks, Nikunj Badjatya Bangalore, India -----Inline Attachment Follows----- _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor I think this is what you want: >>> import sys >>> sys.argv[0] 'C:\\Python26\\testingscripts\\lowdir.py' >>> David -------------- next part -------------- An HTML attachment was scrubbed... URL: From rohitraj007 at gmail.com Fri Feb 5 12:59:49 2010 From: rohitraj007 at gmail.com (Rohit Roger$) Date: Fri, 5 Feb 2010 17:29:49 +0530 Subject: [Tutor] python function to know the path of the program in execution * In-Reply-To: <-6847908149281105391@unknownmsgid> References: <-6847908149281105391@unknownmsgid> Message-ID: Answer : >>> import sys >>> rohit = sys.argv[0] >>> print rohit it returns the name of the path On Fri, Feb 5, 2010 at 4:13 PM, David Hutto wrote: > Junk Score: 2 out of 10 (below your Auto Allow threshold) > | Approve sender | Block > sender | Block > domain > > > > --- On *Fri, 2/5/10, nikunj badjatya * wrote: > > > From: nikunj badjatya > Subject: [Tutor] python function to know the path of the program in > execution > To: tutor at python.org > Date: Friday, February 5, 2010, 5:08 AM > > Hi , > Is there any python function to know the path of the python program under > execution.? > If someone executes a program , he should come to know the path of the > program..!! > ex. suppose a user ABC is running prog.py which is in ~ directory, the user > currently is in XYZ directory. > [ ABC at localhost XYZ ]$ python ~/prog.py > The program's location is ~/prog.py > > This should be the outcome of the program. > > I tried with os.getcwd() > os.getcwd() will return /path/to/folder/XYZ. > > Any suggestions? > > Thanks, > Nikunj Badjatya > Bangalore, India > > -----Inline Attachment Follows----- > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > I think this is what you want: > > >>> import sys > >>> sys.argv[0] > 'C:\\Python26\\testingscripts\\lowdir.py' > >>> > > David > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From spoorthi.ms at gmail.com Fri Feb 5 13:06:09 2010 From: spoorthi.ms at gmail.com (Spoorthi) Date: Fri, 5 Feb 2010 17:36:09 +0530 Subject: [Tutor] python function to know the path of the program in execution * In-Reply-To: References: <-6847908149281105391@unknownmsgid> Message-ID: <6c9f52051002050406l2664403dlf6eb19a712c10284@mail.gmail.com> sys.path[0] should be serving the purpose effectively I guess On Fri, Feb 5, 2010 at 5:29 PM, Rohit Roger$ wrote: > Answer : > >>> import sys > >>> rohit = sys.argv[0] > >>> print rohit > it returns the name of the path > > On Fri, Feb 5, 2010 at 4:13 PM, David Hutto wrote: > >> Junk Score: 2 out of 10 (below your Auto Allow threshold) >> | Approve sender | Block >> sender | Block >> domain >> >> >> >> --- On *Fri, 2/5/10, nikunj badjatya * wrote: >> >> >> From: nikunj badjatya >> Subject: [Tutor] python function to know the path of the program in >> execution >> To: tutor at python.org >> Date: Friday, February 5, 2010, 5:08 AM >> >> Hi , >> Is there any python function to know the path of the python program under >> execution.? >> If someone executes a program , he should come to know the path of the >> program..!! >> ex. suppose a user ABC is running prog.py which is in ~ directory, the >> user currently is in XYZ directory. >> [ ABC at localhost XYZ ]$ python ~/prog.py >> The program's location is ~/prog.py >> >> This should be the outcome of the program. >> >> I tried with os.getcwd() >> os.getcwd() will return /path/to/folder/XYZ. >> >> Any suggestions? >> >> Thanks, >> Nikunj Badjatya >> Bangalore, India >> >> -----Inline Attachment Follows----- >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> I think this is what you want: >> >> >>> import sys >> >>> sys.argv[0] >> 'C:\\Python26\\testingscripts\\lowdir.py' >> >>> >> >> David >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Spoorthi -------------- next part -------------- An HTML attachment was scrubbed... URL: From rohitraj007 at gmail.com Fri Feb 5 13:08:23 2010 From: rohitraj007 at gmail.com (Rohit Roger$) Date: Fri, 5 Feb 2010 17:38:23 +0530 Subject: [Tutor] python function to know the path of the program in execution * In-Reply-To: <6c9f52051002050406l2664403dlf6eb19a712c10284@mail.gmail.com> References: <-6847908149281105391@unknownmsgid> <6c9f52051002050406l2664403dlf6eb19a712c10284@mail.gmail.com> Message-ID: sys.path[0] returns none On Fri, Feb 5, 2010 at 5:36 PM, Spoorthi wrote: > sys.path[0] should be serving the purpose effectively I guess > > > On Fri, Feb 5, 2010 at 5:29 PM, Rohit Roger$ wrote: > >> Answer : >> >>> import sys >> >>> rohit = sys.argv[0] >> >>> print rohit >> it returns the name of the path >> >> On Fri, Feb 5, 2010 at 4:13 PM, David Hutto wrote: >> >>> Junk Score: 2 out of 10 (below your Auto Allow threshold) >>> | Approve sender | Block >>> sender | Block >>> domain >>> >>> >>> >>> --- On *Fri, 2/5/10, nikunj badjatya * wrote: >>> >>> >>> From: nikunj badjatya >>> Subject: [Tutor] python function to know the path of the program in >>> execution >>> To: tutor at python.org >>> Date: Friday, February 5, 2010, 5:08 AM >>> >>> Hi , >>> Is there any python function to know the path of the python program under >>> execution.? >>> If someone executes a program , he should come to know the path of the >>> program..!! >>> ex. suppose a user ABC is running prog.py which is in ~ directory, the >>> user currently is in XYZ directory. >>> [ ABC at localhost XYZ ]$ python ~/prog.py >>> The program's location is ~/prog.py >>> >>> This should be the outcome of the program. >>> >>> I tried with os.getcwd() >>> os.getcwd() will return /path/to/folder/XYZ. >>> >>> Any suggestions? >>> >>> Thanks, >>> Nikunj Badjatya >>> Bangalore, India >>> >>> -----Inline Attachment Follows----- >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> I think this is what you want: >>> >>> >>> import sys >>> >>> sys.argv[0] >>> 'C:\\Python26\\testingscripts\\lowdir.py' >>> >>> >>> >>> David >>> >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Spoorthi > -------------- next part -------------- An HTML attachment was scrubbed... URL: From spoorthi.ms at gmail.com Fri Feb 5 13:13:37 2010 From: spoorthi.ms at gmail.com (Spoorthi) Date: Fri, 5 Feb 2010 17:43:37 +0530 Subject: [Tutor] python function to know the path of the program in execution * In-Reply-To: References: <-6847908149281105391@unknownmsgid> <6c9f52051002050406l2664403dlf6eb19a712c10284@mail.gmail.com> Message-ID: <6c9f52051002050413o57bd76bax7ac5986b17304725@mail.gmail.com> The below data(in blue) made me converge upon sys.path[0] for this particular problem...I dont think it returns None if a Python script is used. Can anyone please correct me if I am wrong *As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.* On Fri, Feb 5, 2010 at 5:38 PM, Rohit Roger$ wrote: > > sys.path[0] returns none > > > > On Fri, Feb 5, 2010 at 5:36 PM, Spoorthi wrote: > >> sys.path[0] should be serving the purpose effectively I guess >> >> >> On Fri, Feb 5, 2010 at 5:29 PM, Rohit Roger$ wrote: >> >>> Answer : >>> >>> import sys >>> >>> rohit = sys.argv[0] >>> >>> print rohit >>> it returns the name of the path >>> >>> On Fri, Feb 5, 2010 at 4:13 PM, David Hutto wrote: >>> >>>> Junk Score: 2 out of 10 (below your Auto Allow threshold) >>>> | Approve sender | >>>> Block sender| Block >>>> domain >>>> >>>> >>>> >>>> --- On *Fri, 2/5/10, nikunj badjatya * wrote: >>>> >>>> >>>> From: nikunj badjatya >>>> Subject: [Tutor] python function to know the path of the program in >>>> execution >>>> To: tutor at python.org >>>> Date: Friday, February 5, 2010, 5:08 AM >>>> >>>> Hi , >>>> Is there any python function to know the path of the python program >>>> under execution.? >>>> If someone executes a program , he should come to know the path of the >>>> program..!! >>>> ex. suppose a user ABC is running prog.py which is in ~ directory, the >>>> user currently is in XYZ directory. >>>> [ ABC at localhost XYZ ]$ python ~/prog.py >>>> The program's location is ~/prog.py >>>> >>>> This should be the outcome of the program. >>>> >>>> I tried with os.getcwd() >>>> os.getcwd() will return /path/to/folder/XYZ. >>>> >>>> Any suggestions? >>>> >>>> Thanks, >>>> Nikunj Badjatya >>>> Bangalore, India >>>> >>>> -----Inline Attachment Follows----- >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> I think this is what you want: >>>> >>>> >>> import sys >>>> >>> sys.argv[0] >>>> 'C:\\Python26\\testingscripts\\lowdir.py' >>>> >>> >>>> >>>> David >>>> >>>> >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> >> -- >> Spoorthi >> > > -- Spoorthi -------------- next part -------------- An HTML attachment was scrubbed... URL: From rohitraj007 at gmail.com Fri Feb 5 13:17:29 2010 From: rohitraj007 at gmail.com (Rohit Roger$) Date: Fri, 5 Feb 2010 17:47:29 +0530 Subject: [Tutor] python function to know the path of the program in execution * In-Reply-To: <6c9f52051002050413o57bd76bax7ac5986b17304725@mail.gmail.com> References: <-6847908149281105391@unknownmsgid> <6c9f52051002050406l2664403dlf6eb19a712c10284@mail.gmail.com> <6c9f52051002050413o57bd76bax7ac5986b17304725@mail.gmail.com> Message-ID: it tell the path upto the python file.. On Fri, Feb 5, 2010 at 5:43 PM, Spoorthi wrote: > The below data(in blue) made me converge upon sys.path[0] for this > particular problem...I dont think it returns None if a Python script is > used. Can anyone please correct me if I am wrong > > *As initialized upon program startup, the first item of this list, path[0], > is the directory containing the script that was used to invoke the Python > interpreter. If the script directory is not available (e.g. if the > interpreter is invoked interactively or if the script is read from standard > input), path[0] is the empty string, which directs Python to search > modules in the current directory first. Notice that the script directory is > inserted before the entries inserted as a result of PYTHONPATH.* > > > On Fri, Feb 5, 2010 at 5:38 PM, Rohit Roger$ wrote: > >> >> sys.path[0] returns none >> >> >> >> On Fri, Feb 5, 2010 at 5:36 PM, Spoorthi wrote: >> >>> sys.path[0] should be serving the purpose effectively I guess >>> >>> >>> On Fri, Feb 5, 2010 at 5:29 PM, Rohit Roger$ wrote: >>> >>>> Answer : >>>> >>> import sys >>>> >>> rohit = sys.argv[0] >>>> >>> print rohit >>>> it returns the name of the path >>>> >>>> On Fri, Feb 5, 2010 at 4:13 PM, David Hutto wrote: >>>> >>>>> Junk Score: 2 out of 10 (below your Auto Allow threshold) >>>>> | Approve sender | Block >>>>> sender | Block >>>>> domain >>>>> >>>>> >>>>> >>>>> --- On *Fri, 2/5/10, nikunj badjatya *wrote: >>>>> >>>>> >>>>> From: nikunj badjatya >>>>> Subject: [Tutor] python function to know the path of the program in >>>>> execution >>>>> To: tutor at python.org >>>>> Date: Friday, February 5, 2010, 5:08 AM >>>>> >>>>> Hi , >>>>> Is there any python function to know the path of the python program >>>>> under execution.? >>>>> If someone executes a program , he should come to know the path of the >>>>> program..!! >>>>> ex. suppose a user ABC is running prog.py which is in ~ directory, the >>>>> user currently is in XYZ directory. >>>>> [ ABC at localhost XYZ ]$ python ~/prog.py >>>>> The program's location is ~/prog.py >>>>> >>>>> This should be the outcome of the program. >>>>> >>>>> I tried with os.getcwd() >>>>> os.getcwd() will return /path/to/folder/XYZ. >>>>> >>>>> Any suggestions? >>>>> >>>>> Thanks, >>>>> Nikunj Badjatya >>>>> Bangalore, India >>>>> >>>>> -----Inline Attachment Follows----- >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> I think this is what you want: >>>>> >>>>> >>> import sys >>>>> >>> sys.argv[0] >>>>> 'C:\\Python26\\testingscripts\\lowdir.py' >>>>> >>> >>>>> >>>>> David >>>>> >>>>> >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >>> >>> -- >>> Spoorthi >>> >> >> > > > -- > Spoorthi > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Feb 5 13:34:50 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 5 Feb 2010 07:34:50 -0500 Subject: [Tutor] Variable: From input and output In-Reply-To: <27460922.post@talk.nabble.com> References: <27457364.post@talk.nabble.com> <1c2a2c591002041259r604f0b60j341910f644256def@mail.gmail.com> <27460922.post@talk.nabble.com> Message-ID: <1c2a2c591002050434v14f9a4e7ic3a530f5ea0a83f6@mail.gmail.com> On Thu, Feb 4, 2010 at 5:39 PM, ssiverling wrote: > > > I uploaded a file. ?I know it's not very impressive. Where did you upload it? For short programs you can just include them in your email. Also, please don't top-post, and please subscribe to the list. Kent > > > Kent Johnson wrote: >> >> On Thu, Feb 4, 2010 at 1:19 PM, ssiverling wrote: >> >>> So I have been working on this example for a little while. ?I looked for >>> the >>> answer before posting. ?I tried to use two raw inputs, then use >>> sys.stdout.write, to add them together. ?However I think I might need to >>> use >>> a variable. ?Any help would be appreciated. ?Thank you in advance. >> >> What have you done so far? If you show us some code we can better help >> you. >> >> Kent >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > http://old.nabble.com/file/p27460922/psy psy > -- > View this message in context: http://old.nabble.com/Variable%3A-From-input-and-output-tp27457364p27460922.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rohitraj007 at gmail.com Fri Feb 5 13:44:32 2010 From: rohitraj007 at gmail.com (Rohit Roger$) Date: Fri, 5 Feb 2010 18:14:32 +0530 Subject: [Tutor] Variable: From input and output In-Reply-To: <1c2a2c591002050434v14f9a4e7ic3a530f5ea0a83f6@mail.gmail.com> References: <27457364.post@talk.nabble.com> <1c2a2c591002041259r604f0b60j341910f644256def@mail.gmail.com> <27460922.post@talk.nabble.com> <1c2a2c591002050434v14f9a4e7ic3a530f5ea0a83f6@mail.gmail.com> Message-ID: Answer: Here is the code : >>> firstname = raw_input("\n Enter your first name : ") >>> lastname = raw_input("\n Enter your last name : ") >>> print (" Printing Your Complete name.............") >>> print firstname + " " + lastname Regards, Rohit On Fri, Feb 5, 2010 at 6:04 PM, Kent Johnson wrote: > On Thu, Feb 4, 2010 at 5:39 PM, ssiverling wrote: > > > > > > I uploaded a file. I know it's not very impressive. > > Where did you upload it? > > For short programs you can just include them in your email. > > Also, please don't top-post, and please subscribe to the list. > > Kent > > > > > > Kent Johnson wrote: > >> > >> On Thu, Feb 4, 2010 at 1:19 PM, ssiverling > wrote: > >> > >>> So I have been working on this example for a little while. I looked > for > >>> the > >>> answer before posting. I tried to use two raw inputs, then use > >>> sys.stdout.write, to add them together. However I think I might need > to > >>> use > >>> a variable. Any help would be appreciated. Thank you in advance. > >> > >> What have you done so far? If you show us some code we can better help > >> you. > >> > >> Kent > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > >> > >> > > http://old.nabble.com/file/p27460922/psy psy > > -- > > View this message in context: > http://old.nabble.com/Variable%3A-From-input-and-output-tp27457364p27460922.html > > Sent from the Python - tutor mailing list archive at Nabble.com. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dsarmientos at gmail.com Fri Feb 5 13:53:32 2010 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Fri, 5 Feb 2010 07:53:32 -0500 (COT) Subject: [Tutor] python function to know the path of the program in execution * In-Reply-To: References: Message-ID: > Date: Fri, 5 Feb 2010 17:43:37 +0530 > From: Spoorthi > To: "Rohit Roger$" > Cc: tutor > Subject: Re: [Tutor] python function to know the path of the program > in execution * > Message-ID: > <6c9f52051002050413o57bd76bax7ac5986b17304725 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > The below data(in blue) made me converge upon sys.path[0] for this > particular problem...I dont think it returns None if a Python script is > used. Can anyone please correct me if I am wrong > > *As initialized upon program startup, the first item of this list, path[0], > is the directory containing the script that was used to invoke the Python > interpreter. If the script directory is not available (e.g. if the > interpreter is invoked interactively or if the script is read from standard > input), path[0] is the empty string, which directs Python to search modules > in the current directory first. Notice that the script directory is inserted > before the entries inserted as a result of PYTHONPATH.* > > On Fri, Feb 5, 2010 at 5:38 PM, Rohit Roger$ wrote: > >> >> sys.path[0] returns none >> >> >> >> On Fri, Feb 5, 2010 at 5:36 PM, Spoorthi wrote: >> >>> sys.path[0] should be serving the purpose effectively I guess >>> >>> >>> On Fri, Feb 5, 2010 at 5:29 PM, Rohit Roger$ wrote: >>> >>>> Answer : >>>> >>> import sys >>>>>>> rohit = sys.argv[0] >>>>>>> print rohit >>>> it returns the name of the path >>>> >>>> On Fri, Feb 5, 2010 at 4:13 PM, David Hutto wrote: >>>> >>>>> Junk Score: 2 out of 10 (below your Auto Allow threshold) >>>>> | Approve sender | >>>>> Block sender| Block >>>>> domain >>>>> >>>>> >>>>> >>>>> --- On *Fri, 2/5/10, nikunj badjatya * wrote: >>>>> >>>>> >>>>> From: nikunj badjatya >>>>> Subject: [Tutor] python function to know the path of the program in >>>>> execution >>>>> To: tutor at python.org >>>>> Date: Friday, February 5, 2010, 5:08 AM >>>>> >>>>> Hi , >>>>> Is there any python function to know the path of the python program >>>>> under execution.? >>>>> If someone executes a program , he should come to know the path of the >>>>> program..!! >>>>> ex. suppose a user ABC is running prog.py which is in ~ directory, the >>>>> user currently is in XYZ directory. >>>>> [ ABC at localhost XYZ ]$ python ~/prog.py >>>>> The program's location is ~/prog.py >>>>> >>>>> This should be the outcome of the program. >>>>> >>>>> I tried with os.getcwd() >>>>> os.getcwd() will return /path/to/folder/XYZ. >>>>> >>>>> Any suggestions? >>>>> >>>>> Thanks, >>>>> Nikunj Badjatya >>>>> Bangalore, India >>>>> >>>>> -----Inline Attachment Follows----- >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> I think this is what you want: >>>>> >>>>>>>> import sys >>>>>>>> sys.argv[0] >>>>> 'C:\\Python26\\testingscripts\\lowdir.py' >>>>>>>> >>>>> >>>>> David >>>>> >>>>> >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >>> >>> -- >>> Spoorthi >>> >> >> > > > -- > Spoorthi > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ I remember using the __file__ attribute in Django once. I don't know if that's what you are looking for. You might want to take a loook at http://pyref.infogami.com/__file__ HTH Daniel From rohitraj007 at gmail.com Fri Feb 5 14:05:52 2010 From: rohitraj007 at gmail.com (Rohit Roger$) Date: Fri, 5 Feb 2010 18:35:52 +0530 Subject: [Tutor] python function to know the path of the program in execution * * In-Reply-To: <7191497950553152223@unknownmsgid> References: <7191497950553152223@unknownmsgid> Message-ID: ok.. On Fri, Feb 5, 2010 at 6:23 PM, Daniel Sarmiento wrote: > Junk Score: 2 out of 10 (below your Auto Allow threshold) > | Approve sender | Block > sender | Block > domain > > > > Date: Fri, 5 Feb 2010 17:43:37 +0530 >> From: Spoorthi >> To: "Rohit Roger$" >> Cc: tutor >> Subject: Re: [Tutor] python function to know the path of the program >> in execution * >> Message-ID: >> <6c9f52051002050413o57bd76bax7ac5986b17304725 at mail.gmail.com> >> Content-Type: text/plain; charset="iso-8859-1" >> >> The below data(in blue) made me converge upon sys.path[0] for this >> particular problem...I dont think it returns None if a Python script is >> used. Can anyone please correct me if I am wrong >> >> *As initialized upon program startup, the first item of this list, >> path[0], >> is the directory containing the script that was used to invoke the Python >> interpreter. If the script directory is not available (e.g. if the >> interpreter is invoked interactively or if the script is read from >> standard >> input), path[0] is the empty string, which directs Python to search >> modules >> in the current directory first. Notice that the script directory is >> inserted >> before the entries inserted as a result of PYTHONPATH.* >> >> On Fri, Feb 5, 2010 at 5:38 PM, Rohit Roger$ >> wrote: >> >> >>> sys.path[0] returns none >>> >>> >>> >>> On Fri, Feb 5, 2010 at 5:36 PM, Spoorthi wrote: >>> >>> sys.path[0] should be serving the purpose effectively I guess >>>> >>>> >>>> On Fri, Feb 5, 2010 at 5:29 PM, Rohit Roger$ >>> >wrote: >>>> >>>> Answer : >>>>> >>> import sys >>>>> >>>>>> rohit = sys.argv[0] >>>>>>>> print rohit >>>>>>>> >>>>>>> it returns the name of the path >>>>> >>>>> On Fri, Feb 5, 2010 at 4:13 PM, David Hutto >>>> >wrote: >>>>> >>>>> Junk Score: 2 out of 10 (below your Auto Allow threshold< >>>>>> https://www.boxbe.com/mail-screening>) >>>>>> | Approve sender >>>>>> | >>>>>> Block sender< >>>>>> https://www.boxbe.com/anno?tc=1529381613_418589136&disp=b>| Block >>>>>> domain >>>>> > >>>>>> >>>>>> >>>>>> >>>>>> --- On *Fri, 2/5/10, nikunj badjatya * >>>>>> wrote: >>>>>> >>>>>> >>>>>> From: nikunj badjatya >>>>>> Subject: [Tutor] python function to know the path of the program in >>>>>> execution >>>>>> To: tutor at python.org >>>>>> Date: Friday, February 5, 2010, 5:08 AM >>>>>> >>>>>> Hi , >>>>>> Is there any python function to know the path of the python program >>>>>> under execution.? >>>>>> If someone executes a program , he should come to know the path of the >>>>>> program..!! >>>>>> ex. suppose a user ABC is running prog.py which is in ~ directory, the >>>>>> user currently is in XYZ directory. >>>>>> [ ABC at localhost XYZ ]$ python ~/prog.py >>>>>> The program's location is ~/prog.py >>>>>> >>>>>> This should be the outcome of the program. >>>>>> >>>>>> I tried with os.getcwd() >>>>>> os.getcwd() will return /path/to/folder/XYZ. >>>>>> >>>>>> Any suggestions? >>>>>> >>>>>> Thanks, >>>>>> Nikunj Badjatya >>>>>> Bangalore, India >>>>>> >>>>>> -----Inline Attachment Follows----- >>>>>> >>>>>> _______________________________________________ >>>>>> Tutor maillist - Tutor at python.org< >>>>>> http://mc/compose?to=Tutor at python.org> >>>>>> To unsubscribe or change subscription options: >>>>>> http://mail.python.org/mailman/listinfo/tutor >>>>>> >>>>>> >>>>>> I think this is what you want: >>>>>> >>>>>> import sys >>>>>>>>> sys.argv[0] >>>>>>>>> >>>>>>>> 'C:\\Python26\\testingscripts\\lowdir.py' >>>>>> >>>>>>> >>>>>>>>> >>>>>> David >>>>>> >>>>>> >>>>>> >>>>>> _______________________________________________ >>>>>> Tutor maillist - Tutor at python.org >>>>>> To unsubscribe or change subscription options: >>>>>> http://mail.python.org/mailman/listinfo/tutor >>>>>> >>>>>> >>>>>> >>>>> _______________________________________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> >>>> >>>> -- >>>> Spoorthi >>>> >>>> >>> >>> >> >> -- >> Spoorthi >> -------------- next part -------------- >> An HTML attachment was scrubbed... >> URL: < >> http://mail.python.org/pipermail/tutor/attachments/20100205/8272d339/attachment-0001.htm >> > >> >> ------------------------------ >> > > I remember using the __file__ attribute in Django once. I don't know if > that's what you are looking for. You might want to take a loook at > http://pyref.infogami.com/__file__ > > HTH > > Daniel > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at yahoo.com Fri Feb 5 14:12:03 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Fri, 5 Feb 2010 05:12:03 -0800 (PST) Subject: [Tutor] python function to know the path of the program in execution * In-Reply-To: Message-ID: <914321.48115.qm@web45312.mail.sp1.yahoo.com> If you want to know the file you're script is running from then print sys.argv[0] this is the script I ran from a file named lowerdir.py: import sys print "This is sys.path:" print print sys.path print print "This is sys.path[0], the current working directory:" print print sys.path[0] print print "This is sys.path[1], the first in the PYTHONOPATH string after the current directory your script is running in:" print print sys.path[1] print print "This is sys.path[-1] the last in the PYTHONPATH list:" print print sys.path[-1] print print "This is sys.argv[0] your current running scripts full path:" print print sys.argv[0] This is my output: IDLE 2.6.4????? >>> ================================ RESTART ================================ >>> This is sys.path: ['C:\\Python26\\testingscripts\\lowerdir', 'C:\\Python26\\Lib\\idlelib', 'C:\\Windows\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'C:\\Python26\\lib\\site-packages\\Pythonwin'] This is sys.path[0], the current working directory: C:\Python26\testingscripts\lowerdir This is sys.path[1], the first in the PYTHONOPATH string after the current directory your script is running in: C:\Python26\Lib\idlelib This is sys.path[-1] the last in the PYTHONPATH list: C:\Python26\lib\site-packages\Pythonwin This is sys.argv[0] your current running scripts full path: C:\Python26\testingscripts\lowerdir\lowerdir.py >>> As long as you have sys imported at somepoint, then all you have to do is print sys.argv[0], and that should be the exact name and location of the current running script, David --- On Fri, 2/5/10, Daniel Sarmiento wrote: From: Daniel Sarmiento Subject: Re: [Tutor] python function to know the path of the program in execution * To: tutor at python.org Date: Friday, February 5, 2010, 7:53 AM > Date: Fri, 5 Feb 2010 17:43:37 +0530 > From: Spoorthi > To: "Rohit Roger$" > Cc: tutor > Subject: Re: [Tutor] python function to know the path of the program > ??? in??? execution * > Message-ID: > ??? <6c9f52051002050413o57bd76bax7ac5986b17304725 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > The below data(in blue) made me converge upon sys.path[0] for this > particular problem...I dont think it returns None if a Python script is > used. Can anyone please correct me if I am wrong > > *As initialized upon program startup, the first item of this list, path[0], > is the directory containing the script that was used to invoke the Python > interpreter. If the script directory is not available (e.g. if the > interpreter is invoked interactively or if the script is read from standard > input), path[0] is the empty string, which directs Python to search modules > in the current directory first. Notice that the script directory is inserted > before the entries inserted as a result of PYTHONPATH.* > > On Fri, Feb 5, 2010 at 5:38 PM, Rohit Roger$ wrote: > >> >> sys.path[0] returns none >> >> >> >> On Fri, Feb 5, 2010 at 5:36 PM, Spoorthi wrote: >> >>> sys.path[0] should be serving the purpose effectively I guess >>> >>> >>> On Fri, Feb 5, 2010 at 5:29 PM, Rohit Roger$ wrote: >>> >>>> Answer : >>>> >>> import sys >>>>>>> rohit = sys.argv[0] >>>>>>> print rohit >>>>? it returns the name of the path >>>> >>>> On Fri, Feb 5, 2010 at 4:13 PM, David Hutto wrote: >>>> >>>>>? Junk Score: 2 out of 10 (below your Auto Allow threshold) >>>>> | Approve sender | >>>>> Block sender| Block >>>>> domain >>>>> >>>>> >>>>> >>>>> --- On *Fri, 2/5/10, nikunj badjatya * wrote: >>>>> >>>>> >>>>> From: nikunj badjatya >>>>> Subject: [Tutor] python function to know the path of the program in >>>>> execution >>>>> To: tutor at python.org >>>>> Date: Friday, February 5, 2010, 5:08 AM >>>>> >>>>> Hi , >>>>> Is there any python function to know the path of the python program >>>>> under execution.? >>>>> If someone executes a program , he should come to know the path of the >>>>> program..!! >>>>> ex. suppose a user ABC is running prog.py which is in ~ directory, the >>>>> user currently is in XYZ directory. >>>>> [ ABC at localhost XYZ ]$ python ~/prog.py >>>>> The program's location is ~/prog.py >>>>> >>>>> This should be the outcome of the program. >>>>> >>>>> I tried with os.getcwd() >>>>> os.getcwd() will return /path/to/folder/XYZ. >>>>> >>>>> Any suggestions? >>>>> >>>>> Thanks, >>>>> Nikunj Badjatya >>>>> Bangalore, India >>>>> >>>>> -----Inline Attachment Follows----- >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist? -? Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> I think this is what you want: >>>>> >>>>>>>> import sys >>>>>>>> sys.argv[0] >>>>> 'C:\\Python26\\testingscripts\\lowdir.py' >>>>>>>> >>>>> >>>>> David >>>>> >>>>> >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist? -? Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>> >>>> _______________________________________________ >>>> Tutor maillist? -? Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >>> >>> -- >>> Spoorthi >>> >> >> > > > -- > Spoorthi > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ I remember using the __file__ attribute in Django once. I don't know if that's what you are looking for. You might want to take a loook at http://pyref.infogami.com/__file__ HTH Daniel _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at yahoo.com Fri Feb 5 14:13:18 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Fri, 5 Feb 2010 05:13:18 -0800 (PST) Subject: [Tutor] python function to know the path of the program in execution * In-Reply-To: Message-ID: <643232.12312.qm@web45313.mail.sp1.yahoo.com> If you want to know the file you're script is running from then print sys.argv[0] this is the script I ran from a file named lowerdir.py: import sys print "This is sys.path:" print print sys.path print print "This is sys.path[0], the current working directory:" print print sys.path[0] print print "This is sys.path[1], the first in the PYTHONOPATH string after the current directory your script is running in:" print print sys.path[1] print print "This is sys.path[-1] the last in the PYTHONPATH list:" print print sys.path[-1] print print "This is sys.argv[0] your current running scripts full path:" print print sys.argv[0] This is my output: IDLE 2.6.4????? >>> ================================ RESTART ================================ >>> This is sys.path: ['C:\\Python26\\testingscripts\\lowerdir', 'C:\\Python26\\Lib\\idlelib', 'C:\\Windows\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\win32', 'C:\\Python26\\lib\\site-packages\\win32\\lib', 'C:\\Python26\\lib\\site-packages\\Pythonwin'] This is sys.path[0], the current working directory: C:\Python26\testingscripts\lowerdir This is sys.path[1], the first in the PYTHONOPATH string after the current directory your script is running in: C:\Python26\Lib\idlelib This is sys.path[-1] the last in the PYTHONPATH list: C:\Python26\lib\site-packages\Pythonwin This is sys.argv[0] your current running scripts full path: C:\Python26\testingscripts\lowerdir\lowerdir.py >>> As long as you have sys imported at somepoint, then all you have to do is print sys.argv[0], and that should be the exact name and location of the current running script, David --- On Fri, 2/5/10, Daniel Sarmiento wrote: From: Daniel Sarmiento Subject: Re: [Tutor] python function to know the path of the program in execution * To: tutor at python.org Date: Friday, February 5, 2010, 7:53 AM > Date: Fri, 5 Feb 2010 17:43:37 +0530 > From: Spoorthi > To: "Rohit Roger$" > Cc: tutor > Subject: Re: [Tutor] python function to know the path of the program > ??? in??? execution * > Message-ID: > ??? <6c9f52051002050413o57bd76bax7ac5986b17304725 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > The below data(in blue) made me converge upon sys.path[0] for this > particular problem...I dont think it returns None if a Python script is > used. Can anyone please correct me if I am wrong > > *As initialized upon program startup, the first item of this list, path[0], > is the directory containing the script that was used to invoke the Python > interpreter. If the script directory is not available (e.g. if the > interpreter is invoked interactively or if the script is read from standard > input), path[0] is the empty string, which directs Python to search modules > in the current directory first. Notice that the script directory is inserted > before the entries inserted as a result of PYTHONPATH.* > > On Fri, Feb 5, 2010 at 5:38 PM, Rohit Roger$ wrote: > >> >> sys.path[0] returns none >> >> >> >> On Fri, Feb 5, 2010 at 5:36 PM, Spoorthi wrote: >> >>> sys.path[0] should be serving the purpose effectively I guess >>> >>> >>> On Fri, Feb 5, 2010 at 5:29 PM, Rohit Roger$ wrote: >>> >>>> Answer : >>>> >>> import sys >>>>>>> rohit = sys.argv[0] >>>>>>> print rohit >>>>? it returns the name of the path >>>> >>>> On Fri, Feb 5, 2010 at 4:13 PM, David Hutto wrote: >>>> >>>>>? Junk Score: 2 out of 10 (below your Auto Allow threshold) >>>>> | Approve sender | >>>>> Block sender| Block >>>>> domain >>>>> >>>>> >>>>> >>>>> --- On *Fri, 2/5/10, nikunj badjatya * wrote: >>>>> >>>>> >>>>> From: nikunj badjatya >>>>> Subject: [Tutor] python function to know the path of the program in >>>>> execution >>>>> To: tutor at python.org >>>>> Date: Friday, February 5, 2010, 5:08 AM >>>>> >>>>> Hi , >>>>> Is there any python function to know the path of the python program >>>>> under execution.? >>>>> If someone executes a program , he should come to know the path of the >>>>> program..!! >>>>> ex. suppose a user ABC is running prog.py which is in ~ directory, the >>>>> user currently is in XYZ directory. >>>>> [ ABC at localhost XYZ ]$ python ~/prog.py >>>>> The program's location is ~/prog.py >>>>> >>>>> This should be the outcome of the program. >>>>> >>>>> I tried with os.getcwd() >>>>> os.getcwd() will return /path/to/folder/XYZ. >>>>> >>>>> Any suggestions? >>>>> >>>>> Thanks, >>>>> Nikunj Badjatya >>>>> Bangalore, India >>>>> >>>>> -----Inline Attachment Follows----- >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist? -? Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> I think this is what you want: >>>>> >>>>>>>> import sys >>>>>>>> sys.argv[0] >>>>> 'C:\\Python26\\testingscripts\\lowdir.py' >>>>>>>> >>>>> >>>>> David >>>>> >>>>> >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist? -? Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>> >>>> _______________________________________________ >>>> Tutor maillist? -? Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >>> >>> -- >>> Spoorthi >>> >> >> > > > -- > Spoorthi > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ I remember using the __file__ attribute in Django once. I don't know if that's what you are looking for. You might want to take a loook at http://pyref.infogami.com/__file__ HTH Daniel _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mike.Hansen at atmel.com Fri Feb 5 17:40:51 2010 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Fri, 5 Feb 2010 09:40:51 -0700 Subject: [Tutor] Variable declaration Message-ID: <7941B2693F32294AAF16C26B679A258D0EB266F6@csomb01.corp.atmel.com> Perl has "use strict;" to force variable declaration. My insane Perl loving co-workers think it's evil that Python doesn't have variable declaration. =) What are some of the reasons/arguments on why Python doesn't need variable declaration? I've gotten around it in Python by using Pyflakes to check my code and catch those silly mis-spelling of a variable. Mike From toni at muybien.org Fri Feb 5 17:54:59 2010 From: toni at muybien.org (Antonio de la Fuente) Date: Fri, 5 Feb 2010 16:54:59 +0000 Subject: [Tutor] Simple variable type question Message-ID: <20100205165459.GD22615@cateto> Hi all, I'm trying to do exercises from: http://openbookproject.net/thinkcs/python/english2e/ch05.html exercise number 3 (slope function) and when I run it: python ch05.py -v the doctest for the slope function failed, because is expecting a floating point value and not an integer: Failed example: slope(2, 4, 1, 2) Expected: 2.0 Got: 2 This is the function, and how I modified so it would return a floating point value (multiply by 1.0). But this doesn't feel the right way to do things, or is it? def slope(x1, y1, x2, y2): """ >>> slope(5, 3, 4, 2) 1.0 >>> slope(1, 2, 3, 2) 0.0 >>> slope(1, 2, 3, 3) 0.5 >>> slope(2, 4, 1, 2) 2.0 """ result_slope = ((y2 - y1) / (x2 - x1)) * 1.0 return result_slope Another question is, anybody knows if these questions from this online book are answered somewhere? I can't manage to find them? Thank you for your time. Antonio. -- ----------------------------- Antonio de la Fuente Mart?nez E-mail: toni at muybien.org ----------------------------- Guarda que comer y no que hacer. From waynejwerner at gmail.com Fri Feb 5 19:09:15 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 5 Feb 2010 12:09:15 -0600 Subject: [Tutor] Variable declaration In-Reply-To: <7941B2693F32294AAF16C26B679A258D0EB266F6@csomb01.corp.atmel.com> References: <7941B2693F32294AAF16C26B679A258D0EB266F6@csomb01.corp.atmel.com> Message-ID: <333efb451002051009y40169bf7u2675d1e2480cc11f@mail.gmail.com> On Fri, Feb 5, 2010 at 10:40 AM, Hansen, Mike wrote: > Perl has "use strict;" to force variable declaration. > > My insane Perl loving co-workers think it's evil that Python doesn't have > variable declaration. =) > > What are some of the reasons/arguments on why Python doesn't need variable > declaration? I've gotten around it in Python by using Pyflakes to check my > code and catch those silly mis-spelling of a variable. I've never had any serious problems (though I've never worked on huge projects with Python), but here are some of the reasons that pop into my mind: 1) We're big boys and girls - we're responsible enough to pay attention to our variables 2) I have no clue, but it may make it easier on the garbage collection - once a value/object no longer has a reference it can probably be cleared up. But those c variables you declared way back in the beginning of your program? Still there (though an anti-argument would be that you're not using scope properly in this case) 3) If you're writing a small program you should be able to see everything, but if you're using a big enough program you should be using an IDE that keeps track of that sort of thing. I don't know how valid those reasons would be considered... but I, for one, like the freedom of not having to type: int a = 0; or int a; MyClass(){ a = 0; } or any other waste of keystrokes. If I want a new variable, I'll make it responsibly - whether I need it here or there... but that's my two cents -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Fri Feb 5 19:13:44 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 5 Feb 2010 12:13:44 -0600 Subject: [Tutor] Simple variable type question In-Reply-To: <20100205165459.GD22615@cateto> References: <20100205165459.GD22615@cateto> Message-ID: <333efb451002051013j105cee28m6f59f19bbc030619@mail.gmail.com> On Fri, Feb 5, 2010 at 10:54 AM, Antonio de la Fuente wrote: > Hi all, > > I'm trying to do exercises from: > > http://openbookproject.net/thinkcs/python/english2e/ch05.html > > exercise number 3 (slope function) and when I run it: > > python ch05.py -v > > the doctest for the slope function failed, because is expecting a > floating point value and not an integer: > try to cast your values as float instead: try: x1 = float(x1) x2 = float(x2) y1 = float(y1) y2 = float(y2) except ValueError: print "Error, not a floating point!" raise Then you don't need to worry about the * 1.0 HTH, Wayne > > Failed example: > slope(2, 4, 1, 2) > Expected: > 2.0 > Got: > 2 > > This is the function, and how I modified so it would return a floating > point value (multiply by 1.0). But this doesn't feel the right way to > do things, or is it? > > def slope(x1, y1, x2, y2): > """ > >>> slope(5, 3, 4, 2) > 1.0 > >>> slope(1, 2, 3, 2) > 0.0 > >>> slope(1, 2, 3, 3) > 0.5 > >>> slope(2, 4, 1, 2) > 2.0 > """ > result_slope = ((y2 - y1) / (x2 - x1)) * 1.0 > return result_slope > > Another question is, anybody knows if these questions from this online > book are answered somewhere? I can't manage to find them? > > Thank you for your time. > Antonio. > > -- > ----------------------------- > Antonio de la Fuente Mart?nez > E-mail: toni at muybien.org > ----------------------------- > > Guarda que comer y no que hacer. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > 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 sander.sweers at gmail.com Fri Feb 5 19:15:10 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 05 Feb 2010 19:15:10 +0100 Subject: [Tutor] Simple variable type question In-Reply-To: <20100205165459.GD22615@cateto> References: <20100205165459.GD22615@cateto> Message-ID: <1265393710.17542.8.camel@infirit> On vr, 2010-02-05 at 16:54 +0000, Antonio de la Fuente wrote: > http://openbookproject.net/thinkcs/python/english2e/ch05.html > > exercise number 3 (slope function) and when I run it: > > python ch05.py -v > > the doctest for the slope function failed, because is expecting a > floating point value and not an integer: > > Failed example: > slope(2, 4, 1, 2) > Expected: > 2.0 > Got: > 2 Python handles integers a bit counter intuitive. It does not automatically converts you devision from an int to a float number. >>> 1 / 2 0 >>> 3 / 2 1 You would expect this to become 0.5 and 1.5. > This is the function, and how I modified so it would return a floating > point value (multiply by 1.0). But this doesn't feel the right way to > do things, or is it? Not is is not, if you would type this into a python shell or idle you will still fail the 3rd test. >>> (3-2)/(3-1) * 1.0 0.0 > def slope(x1, y1, x2, y2): > """ > >>> slope(5, 3, 4, 2) > 1.0 > >>> slope(1, 2, 3, 2) > 0.0 > >>> slope(1, 2, 3, 3) > 0.5 > >>> slope(2, 4, 1, 2) > 2.0 > """ > result_slope = ((y2 - y1) / (x2 - x1)) * 1.0 > return result_slope You will need to find a way to convert your int numbers to float numbers *before* doing the calculation. Greets Sander From rabidpoobear at gmail.com Fri Feb 5 19:39:55 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 5 Feb 2010 12:39:55 -0600 Subject: [Tutor] Simple variable type question In-Reply-To: <20100205165459.GD22615@cateto> References: <20100205165459.GD22615@cateto> Message-ID: You want to promote one of your variables to float before you do the calculation, this will make all other variables automatically cast. So (float(y2) - y1) / (x2-x1). if you do the float cast after the calculation, you will do the calculation as integers and so even though you'll get "2.0" you won't ever be able to get "2.2" for example. On 2/5/10, Antonio de la Fuente wrote: > Hi all, > > I'm trying to do exercises from: > > http://openbookproject.net/thinkcs/python/english2e/ch05.html > > exercise number 3 (slope function) and when I run it: > > python ch05.py -v > > the doctest for the slope function failed, because is expecting a > floating point value and not an integer: > > Failed example: > slope(2, 4, 1, 2) > Expected: > 2.0 > Got: > 2 > > This is the function, and how I modified so it would return a floating > point value (multiply by 1.0). But this doesn't feel the right way to > do things, or is it? > > def slope(x1, y1, x2, y2): > """ > >>> slope(5, 3, 4, 2) > 1.0 > >>> slope(1, 2, 3, 2) > 0.0 > >>> slope(1, 2, 3, 3) > 0.5 > >>> slope(2, 4, 1, 2) > 2.0 > """ > result_slope = ((y2 - y1) / (x2 - x1)) * 1.0 > return result_slope > > Another question is, anybody knows if these questions from this online > book are answered somewhere? I can't manage to find them? > > Thank you for your time. > Antonio. > > -- > ----------------------------- > Antonio de la Fuente Mart?nez > E-mail: toni at muybien.org > ----------------------------- > > Guarda que comer y no que hacer. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sent from my mobile device From alan.gauld at btinternet.com Fri Feb 5 19:45:30 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Feb 2010 18:45:30 -0000 Subject: [Tutor] Simple variable type question References: <20100205165459.GD22615@cateto> Message-ID: "Antonio de la Fuente" wrote > the doctest for the slope function failed, because is expecting a > floating point value and not an integer: So convert it to a float. > def slope(x1, y1, x2, y2): > result_slope = ((y2 - y1) / (x2 - x1)) * 1.0 > return result_slope return float(result_slope) Or just return float(y2-y1/x2-x1) You might want to use a try/except to catch a zero division error too? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Fri Feb 5 20:25:47 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 5 Feb 2010 13:25:47 -0600 Subject: [Tutor] Simple variable type question In-Reply-To: References: <20100205165459.GD22615@cateto> Message-ID: On Fri, Feb 5, 2010 at 12:45 PM, Alan Gauld wrote: > > "Antonio de la Fuente" wrote > >> the doctest for the slope function failed, because is expecting a >> >> floating point value and not an integer: >> > > So convert it to a float. > > Or just > return float(y2-y1/x2-x1) > > Alan why are you suggesting this, surely this will cause the decimal values to be truncated? Or does this somehow work differently in Python 3? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 5 21:39:09 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 5 Feb 2010 20:39:09 +0000 (GMT) Subject: [Tutor] Simple variable type question In-Reply-To: References: <20100205165459.GD22615@cateto> Message-ID: <619662.80187.qm@web86701.mail.ird.yahoo.com> >>>>Or just >>>> return float(y2-y1/x2-x1) >> >> >Alan why are you suggesting this, surely this will cause the decimal values to be truncated? Or does this somehow work differently in Python 3? > It would work different in v3 because / is no longer interger division. However, I just misplaced the ) It should have been after y1. return float(x1-y1)/(x2-y2) Sorry about that. Alan G. From sander.sweers at gmail.com Fri Feb 5 22:22:54 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 05 Feb 2010 22:22:54 +0100 Subject: [Tutor] Simple variable type question In-Reply-To: <619662.80187.qm@web86701.mail.ird.yahoo.com> References: <20100205165459.GD22615@cateto> <619662.80187.qm@web86701.mail.ird.yahoo.com> Message-ID: <1265404974.19004.8.camel@infirit> On vr, 2010-02-05 at 20:39 +0000, ALAN GAULD wrote: > return float(x1-y1)/(x2-y2) Does not work properly in version 2. Example is the 3rd doc test: float((3-2)/(3-1)) gives 0.0 instead of 0.5. Greets Sander From alan.gauld at btinternet.com Sat Feb 6 00:44:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Feb 2010 23:44:56 -0000 Subject: [Tutor] Simple variable type question References: <20100205165459.GD22615@cateto> <619662.80187.qm@web86701.mail.ird.yahoo.com> <1265404974.19004.8.camel@infirit> Message-ID: "Sander Sweers" wrote > On vr, 2010-02-05 at 20:39 +0000, ALAN GAULD wrote: >> return float(x1-y1)/(x2-y2) > > Does not work properly in version 2. Example is the 3rd doc test: > float((3-2)/(3-1)) gives 0.0 instead of 0.5. That's what I did wrong dfirst time round, I had the parens round the whole, it should only be round the first expression. Alan G. From ldl08 at gmx.net Sat Feb 6 08:55:26 2010 From: ldl08 at gmx.net (David) Date: Sat, 06 Feb 2010 15:55:26 +0800 Subject: [Tutor] how to graph percentile -- matplotlib, Inkscape, or what? Message-ID: <4B6D206E.90508@gmx.net> Dear List, given a list of scores (n = 20, say) a group students received in an exam, I can use sarray = [list of scores] score = student's score scipy.stats.percentileofscore(sarray, score, kind='mean') to calculate the percentile for a given student. What I would like to do is to create a graph in which on the horizontal axis the student's precentile (i.e. performance vis-a-vis her classmates) is indicated by means of a needle stuck into the axis: O (63%) |__________________________|______________| | | 0 100 I suspect that I cannot plot this with matplotlib, and my next best guess would be Inkscape, with which I have no scripting experience whatsoever. Is Inkscape the way forward for this little project? What are my alternatives? Thanks for your ideas! David From alan.gauld at btinternet.com Sat Feb 6 10:15:21 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Feb 2010 09:15:21 -0000 Subject: [Tutor] how to graph percentile -- matplotlib, Inkscape, or what? References: <4B6D206E.90508@gmx.net> Message-ID: "David" wrote > is to create a graph in which on the horizontal axis the student's > precentile (i.e. performance vis-a-vis her classmates) is indicated by > means of a needle stuck into the axis: > > O (63%) > |__________________________|______________| > | | > 0 100 > > I suspect that I cannot plot this with matplotlib, and my next best > guess would be Inkscape, with which I have no scripting experience > whatsoever. Why do you think you couldn't do it with matplotlib? It seems a fairly basic request. I have no experience with either package but matplotlib is the first place I'd look for this. There is also gnuplot which I've used outside Pytthon, but it could do this too I'm sure. OTOH It would be fairly easy to roll your own in a vanilla GUI Canvas widget. Its only a few stratight lines and text after all. Or even to use a scroll bar or progress bar widget to indicate the result. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ldl08 at gmx.net Sat Feb 6 10:35:32 2010 From: ldl08 at gmx.net (David) Date: Sat, 06 Feb 2010 17:35:32 +0800 Subject: [Tutor] how to graph percentile -- matplotlib, Inkscape, or what? In-Reply-To: References: <4B6D206E.90508@gmx.net> Message-ID: <4B6D37E4.9050606@gmx.net> Hello Alan, thanks for the guidance, I will then dig a little deeper into matplotlib. I guess the reason why I discarded it before is that I understood matplotlib to be a curve plotting tool, and not so much a tool to draw graphics. I will investigate! David On 06/02/10 17:15, Alan Gauld wrote: > > "David" wrote >> is to create a graph in which on the horizontal axis the student's >> precentile (i.e. performance vis-a-vis her classmates) is indicated by >> means of a needle stuck into the axis: >> >> O (63%) |__________________________|______________| >> | | >> 0 100 >> >> I suspect that I cannot plot this with matplotlib, and my next best >> guess would be Inkscape, with which I have no scripting experience >> whatsoever. > > Why do you think you couldn't do it with matplotlib? > It seems a fairly basic request. > I have no experience with either package but matplotlib is the first > place I'd look for this. > > There is also gnuplot which I've used outside Pytthon, but it could do > this too I'm sure. > > OTOH It would be fairly easy to roll your own in a vanilla GUI Canvas > widget. Its only a few stratight lines and text after all. > Or even to use a scroll bar or progress bar widget to indicate the result. > From simbobo at cooptel.net Fri Feb 5 12:29:30 2010 From: simbobo at cooptel.net (Owain Clarke) Date: Fri, 05 Feb 2010 11:29:30 +0000 Subject: [Tutor] language aid (various) In-Reply-To: References: Message-ID: <4B6C011A.8090104@cooptel.net> On Thu, Feb 4, 2010 at 5:43 AM, Owain Clarke wrote: > >> My question is, that if I proceed like this I will end up with a single list >> of potentially several hundred strings of the form "frword:engword". In >> terms of performance, is this a reasonable way to do it, or will the program >> increasingly slow down? >> > From: "Carnell, James E" > >> A dictionary (associative array of keys and values) seems a good >> datatype to use. vocab = {} vocab[frenchword]?= englishword >> ? >> > ....... > >> Cheers!! >> Albert-Jan >> > > Sure, a dict is the obvious choice. For saving into file, if the app is > to be used internally, you can even print it in the form of a python > dict (with the '{}', ':' & ',') so that reading the dict data is just > importing: > import french_english > > Denis > > I 3rd the dictionary choice. They (for me at least) aren't as clean on > the computer screen as arrays, but once you get good at it you can even > have multiple definitions and weights for how relevant that word is. You > (in the future when you get comfortable with dictionaries) can take it > into networkx or something and draw pictures of it, and really start > messing around with it (using subnetworks to try and get context > information). Google has some tech talks on youtube concerning Language > Processing using networks etc if that kind of thing interests you. > > Sincerely, > > Bad answer man > What a helpful forum - much thanks to all who've commented. Seems to be a bit of a consensus here about dictionaries. Let me just restate my reluctance, using examples from Spanish. esperar = to hope esperar = to wait tambien = too [i.e. also] demasiado = too [i.e. excessive] So there are repeats in both languages. I would like to end up with a file which I can use to generate flash cards, either to or from English, and I suppose I want the flexibility to have 1 word with 1 definition. Having said that, I obviously recognise the expertise of the group, so I will probably pursue this option. Owain From toni at muybien.org Sat Feb 6 11:53:30 2010 From: toni at muybien.org (Antonio de la Fuente) Date: Sat, 6 Feb 2010 10:53:30 +0000 Subject: [Tutor] Simple variable type question In-Reply-To: <20100205165459.GD22615@cateto> References: <20100205165459.GD22615@cateto> Message-ID: <20100206105330.GA2140@cateto> * Antonio de la Fuente [2010-02-05 16:54:59 +0000]: > Date: Fri, 5 Feb 2010 16:54:59 +0000 > From: Antonio de la Fuente > To: Python Tutor mailing list > Subject: [Tutor] Simple variable type question > Organization: (muybien.org) > User-Agent: Mutt/1.5.20 (2009-06-14) > Message-ID: <20100205165459.GD22615 at cateto> [...] > > Another question is, anybody knows if these questions from this online > book are answered somewhere? I can't manage to find them? > I've got it. Thank you all! :-) -- ----------------------------- Antonio de la Fuente Mart?nez E-mail: toni at muybien.org ----------------------------- The Anglo-Saxon conscience does not prevent the Anglo-Saxon from sinning, it merely prevents him from enjoying his sin. -- Salvador De Madariaga From stijnnederland at hotmail.com Sat Feb 6 11:56:28 2010 From: stijnnederland at hotmail.com (Stijn .) Date: Sat, 6 Feb 2010 10:56:28 +0000 Subject: [Tutor] "else:" triggering a Syntax Error Message-ID: First of all I'd like to say that I'm new to python, and new to mailinglists. So if I make any mistakes, please correct me. Now, onto my issue: I am trying to put an "else:" statement inside a class: class Line(): #The class def __init__( self, start_dot, end_dot, width): #init function self.start_dot = start_dot self.surface = pygame.Surface((w, h), SRCALPHA) self.surface.fill((0,0,0,0)) self.end_dot = end_dot self.width = width self.selected = 0 self.tempX1 = start_dot.x self.tempY1 = start_dot.y self.tempX2 = end_dot.x self.tempY2 = end_dot.y self.visibleTemp1 = self.start_dot.visible self.visibleTemp2 = self.end_dot.visible self.draw = 0 self.lastWasMove = 0 self.Draw(1) self.rico = 0 def Draw ( self, typeOf ): #draw function if ((self.start_dot.x > self.end_dot.x) and (self.start_dot.y != self.end_dot.y)): self.rico = (self.start_dot.x - self.end_dot.x / abs(self.start_dot.y - self.end_dot.y) else: #<-causes error message if ((self.start_dot.x < self.end_dot.x and self.start_dot.y != self.end_dot.y)) self.rico = (self.end_dot.x - self.start_dot.x) / abs(self.start_dot.y - self.end_dot.y) else: self.rico = 0 the first "else" statement in the Draw() function triggers a syntax error. Could anyone please enlighten me why this is happening? Thanks in advance! Stijn _________________________________________________________________ 25GB gratis online harde schijf http://skydrive.live.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From transmogribenno at gmail.com Sat Feb 6 12:18:53 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Sat, 6 Feb 2010 20:18:53 +0900 Subject: [Tutor] "else:" triggering a Syntax Error In-Reply-To: References: Message-ID: <9b00d1a91002060318i2427e4b1g5135a3e41924b588@mail.gmail.com> On Sat, Feb 6, 2010 at 7:56 PM, Stijn . wrote: > class Line(): #The class > ??? def __init__( self, start_dot, end_dot, width): #init function > ??????? self.start_dot = start_dot > ??????? self.surface = pygame.Surface((w, h), SRCALPHA) > ??????? self.surface.fill((0,0,0,0)) > ??????? self.end_dot = end_dot > ??????? self.width = width > ??????? self.selected = 0 > ??????? self.tempX1 = start_dot.x > ??????? self.tempY1 = start_dot.y > ??????? self.tempX2 = end_dot.x > ??????? self.tempY2 = end_dot.y > ??????? self.visibleTemp1 = self.start_dot.visible > ??????? self.visibleTemp2 = self.end_dot.visible > ??????? self.draw = 0 > ??????? self.lastWasMove = 0 > ??????? self.Draw(1) > ??????? self.rico = 0 > ??? def Draw ( self, typeOf ): #draw function > ???????? if ((self.start_dot.x > self.end_dot.x) and (self.start_dot.y != > self.end_dot.y)): (1) Are you sure you want all those superfluous parentheses? > ????????????? self.rico = (self.start_dot.x - self.end_dot.x / > abs(self.start_dot.y - self.end_dot.y) (2) You're missing a closing parenthesis. > ???????? else: #<-causes error message > ????????????? if ((self.start_dot.x < self.end_dot.x and self.start_dot.y != > self.end_dot.y)) (3) Don't forget the colon. (4) See (1) > ?????????????????? self.rico = (self.end_dot.x - self.start_dot.x) / > abs(self.start_dot.y - self.end_dot.y) > ????????????? else: > ?????????????????? self.rico = 0 HTH, benno. From eike.welk at gmx.net Sat Feb 6 13:10:25 2010 From: eike.welk at gmx.net (Eike Welk) Date: Sat, 6 Feb 2010 13:10:25 +0100 Subject: [Tutor] language aid (various) In-Reply-To: <4B6C011A.8090104@cooptel.net> References: <4B6C011A.8090104@cooptel.net> Message-ID: <201002061310.25772.eike.welk@gmx.net> On Friday February 5 2010 12:29:30 Owain Clarke wrote: > What a helpful forum - much thanks to all who've commented. Seems to be > a bit of a consensus here about dictionaries. Let me just restate my > reluctance, using examples from Spanish. > > esperar = to hope > esperar = to wait You could have a dict that maps: word -> list of translations d = {"esperar":["to hope", "to wait"]} > tambien = too [i.e. also] > demasiado = too [i.e. excessive] > > So there are repeats in both languages. I would like to end up with a > file which I can use to generate flash cards, either to or from English, > and I suppose I want the flexibility to have 1 word with 1 definition. You should possibly have an object for each term: class LangEntity(object): def __init__(self, word_en, word_es, definition_en=None, definition_es=None, image=None): self.word_en = word_en self.word_es = word_es self.definition_en = definition_en self.definition_es = definition_es self.image = image #TODO: def __repr__(self) so you can see what you are doing. all_entities = [LangEntity("too", "tambien"), LangEntity("to hope", "esperar")] Then you can create dictionaries that map from the words to the LangEntity objects: def make_en_dict(all_ents): res_dict = {} for ent in all_ents: key = ent.word_en ent_list = res_dict.get(key, []) ent_list.append(ent) res_dict[key] = ent_list return res_dict en_dict = make_en_dict(all_entities) WARNING: I didn't try the code, I just typed it into the mail client! So there might be bugs! For useful ways how to model terms of a dictionary, maybe look at these projects, and talk to their developers. http://edu.kde.org/parley/ http://www.voxhumanitatis.org/content/ambaradan-owm2-storage-engine http://www.omegawiki.org/Meta:Main_Page Eike. From denis.spir at free.fr Sat Feb 6 13:09:37 2010 From: denis.spir at free.fr (spir) Date: Sat, 6 Feb 2010 13:09:37 +0100 Subject: [Tutor] language aid (various) In-Reply-To: <4B6C011A.8090104@cooptel.net> References: <4B6C011A.8090104@cooptel.net> Message-ID: <20100206130937.2059c954@o> On Fri, 05 Feb 2010 11:29:30 +0000 Owain Clarke wrote: > On Thu, Feb 4, 2010 at 5:43 AM, Owain Clarke wrote: > > > >> My question is, that if I proceed like this I will end up with a single list > >> of potentially several hundred strings of the form "frword:engword". In > >> terms of performance, is this a reasonable way to do it, or will the program > >> increasingly slow down? > >> > > From: "Carnell, James E" > > > >> A dictionary (associative array of keys and values) seems a good > >> datatype to use. vocab = {} vocab[frenchword]?= englishword > >> ? > >> > > ....... > > > >> Cheers!! > >> Albert-Jan > >> > > > > Sure, a dict is the obvious choice. For saving into file, if the app is > > to be used internally, you can even print it in the form of a python > > dict (with the '{}', ':' & ',') so that reading the dict data is just > > importing: > > import french_english > > > > Denis > > > > I 3rd the dictionary choice. They (for me at least) aren't as clean on > > the computer screen as arrays, but once you get good at it you can even > > have multiple definitions and weights for how relevant that word is. You > > (in the future when you get comfortable with dictionaries) can take it > > into networkx or something and draw pictures of it, and really start > > messing around with it (using subnetworks to try and get context > > information). Google has some tech talks on youtube concerning Language > > Processing using networks etc if that kind of thing interests you. > > > > Sincerely, > > > > Bad answer man > > > What a helpful forum - much thanks to all who've commented. Seems to be > a bit of a consensus here about dictionaries. Let me just restate my > reluctance, using examples from Spanish. > > esperar = to hope > esperar = to wait > tambien = too [i.e. also] > demasiado = too [i.e. excessive] > > So there are repeats in both languages. I would like to end up with a > file which I can use to generate flash cards, either to or from English, > and I suppose I want the flexibility to have 1 word with 1 definition. > > Having said that, I obviously recognise the expertise of the group, so I > will probably pursue this option. > > Owain If you store simple one-to-one pairs, then it will be both more difficult and less efficient to retrieve several matching forms. I guess you'd better store in a dict all possible matches for each single form, eg {..., "esperar":["to hope", "to wait", ...} The issue is how to output that in a clear and practicle format. But this point is about the same whatever your choice about storing (and retrieving) information. The cleanest way to cope with this may be to subtype dict and establish a custom output format using the __str__ "magic" method. You can also use __repr__ for development feedback. Also, your application can be much more complex than it seems at first sight. Look at the hierarchy of acceptions in a paper dict: from word nature to style variant. I would reproduce that in my storage and output formats. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Sat Feb 6 13:19:14 2010 From: denis.spir at free.fr (spir) Date: Sat, 6 Feb 2010 13:19:14 +0100 Subject: [Tutor] "else:" triggering a Syntax Error In-Reply-To: <9b00d1a91002060318i2427e4b1g5135a3e41924b588@mail.gmail.com> References: <9b00d1a91002060318i2427e4b1g5135a3e41924b588@mail.gmail.com> Message-ID: <20100206131914.5a7178ce@o> On Sat, 6 Feb 2010 20:18:53 +0900 Benno Lang wrote: > > if ((self.start_dot.x > self.end_dot.x) and (self.start_dot.y != self.end_dot.y)): > (1) Are you sure you want all those superfluous parentheses? @ Benno: I do not find the _inner_ ones superfluous at all... @ Stijn: When you ask about an error, please copy-paste the (whole) error message to the list, together with (the relevant part of) the code. I will help us not only "diagnosing" the issue, but also showing you how to interpret python error messages. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From transmogribenno at gmail.com Sat Feb 6 13:40:30 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Sat, 6 Feb 2010 21:40:30 +0900 Subject: [Tutor] "else:" triggering a Syntax Error In-Reply-To: <20100206131914.5a7178ce@o> References: <9b00d1a91002060318i2427e4b1g5135a3e41924b588@mail.gmail.com> <20100206131914.5a7178ce@o> Message-ID: <9b00d1a91002060440p4b40d7f7na279bb0b64583ec6@mail.gmail.com> On Sat, Feb 6, 2010 at 9:19 PM, spir wrote: > On Sat, 6 Feb 2010 20:18:53 +0900 > Benno Lang wrote: > >> > if ((self.start_dot.x > self.end_dot.x) and (self.start_dot.y != ?self.end_dot.y)): >> (1) Are you sure you want all those superfluous parentheses? > > @ Benno: I do not find the _inner_ ones superfluous at all... Fair enough. I do, but obviously with the inner ones it's just a question of style. Either way, it should be consistent for both ifs. Cheers, benno From sierra_mtnview at sbcglobal.net Sat Feb 6 16:36:07 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 06 Feb 2010 07:36:07 -0800 Subject: [Tutor] Uninstalling MatPlotLib? (Win7) Message-ID: <4B6D8C67.3010103@sbcglobal.net> I should have installed NumPy before MPL. How do I uninstall it. I'm pretty sure it was an msi file. My guess is to go to site-packages, and delete individual pieces. Possibly these: C:\Python25\Lib\site-packages\pylab.py C:\Python25\Lib\site-packages\matplotlib C:\Python25\Lib\site-packages\mpl_toolkits C:\Python25\Lib\site-packages\matplotlib*.egg-info C:\Python25\Removematplotlib.exe C:\Python25\matplotlib-wininst.log I'm surprised this isn't described somewhere. I've Googled for it and looked in Python docs and haven't found anything about uninstalling these packages. -- My life in two words. "Interrupted Projects." -- WTW (quote originator) From emmanuel.ruellan at laposte.net Sat Feb 6 17:20:06 2010 From: emmanuel.ruellan at laposte.net (Emmanuel Ruellan) Date: Sat, 6 Feb 2010 17:20:06 +0100 Subject: [Tutor] language aid (various) In-Reply-To: <4B6C011A.8090104@cooptel.net> References: <4B6C011A.8090104@cooptel.net> Message-ID: <7296745c1002060820l549962es88e5e7dea04ad6b0@mail.gmail.com> On Fri, Feb 5, 2010 at 12:29 PM, Owain Clarke wrote: > > > Seems to be a bit of a consensus here about dictionaries. Let me just > restate my reluctance, using examples from Spanish. > > esperar = to hope > esperar = to wait > tambien = too [i.e. also] > demasiado = too [i.e. excessive] > > So there are repeats in both languages. I would like to end up with a file > which I can use to generate flash cards, either to or from English, and I > suppose I want the flexibility to have 1 word with 1 definition. > > I'd use a database table to handle the many-to-many relationships between English words and Spanish words. You can use the lightweight SQLite database engine, which comes with Python (http://docs.python.org/library/sqlite3.html ). The table would have just two columns: one for the English word and one for the Spanish word. Each row represents a possible association of an English word with a Spanish word. en es dream so?ar hope esperar wait esperar too tambi?n too demasiado With a table structured like this, you can retrieve all the English words associated with a particular Spanish word, or all the Spanish words associated with a particular English word. For example, with the data above, stored in a table named 'translation' with columns named 'en' and 'es', the following SQL query, select en from translations where es = 'esperar' ... would return: hope wait -- Emmanuel -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldl08 at gmx.net Sat Feb 6 17:35:07 2010 From: ldl08 at gmx.net (David) Date: Sun, 07 Feb 2010 00:35:07 +0800 Subject: [Tutor] if item.find(extension)!= -1: -- what's the -1? Message-ID: <4B6D9A3B.3060509@gmx.net> Hello again, in Knowlton's 2008 book "Python: Create, Modify, Reuse" the author makes frequent use of the term -1 in his code, but doesn't tell to what aim. For want of search terms Google is not helpful. Could someone please enlighten me by means of a one-liner as a reply? Thank you! David Example Code: for item in filelist: if item.find(extension)!= -1: snaplist.append(item) From waynejwerner at gmail.com Sat Feb 6 17:50:00 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 6 Feb 2010 10:50:00 -0600 Subject: [Tutor] if item.find(extension)!= -1: -- what's the -1? In-Reply-To: <4B6D9A3B.3060509@gmx.net> References: <4B6D9A3B.3060509@gmx.net> Message-ID: <333efb451002060850q291e11e2paada37fd22545bd0@mail.gmail.com> On Sat, Feb 6, 2010 at 10:35 AM, David wrote: > Hello again, > > in Knowlton's 2008 book "Python: Create, Modify, Reuse" the author makes > frequent use of the term -1 in his code, but doesn't tell to what aim. For > want of search terms Google is not helpful. Could someone please enlighten > me by means of a one-liner as a reply? > > In [1]: item = 'some string' In [3]: help(item.find) Help on built-in function find: find(...) S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. HTH, Wayne > Thank you! > > David > > > Example Code: > > for item in filelist: > if item.find(extension)!= -1: > snaplist.append(item) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > 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 kent37 at tds.net Sat Feb 6 18:10:41 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 6 Feb 2010 12:10:41 -0500 Subject: [Tutor] if item.find(extension)!= -1: -- what's the -1? In-Reply-To: <4B6D9A3B.3060509@gmx.net> References: <4B6D9A3B.3060509@gmx.net> Message-ID: <1c2a2c591002060910y42ec04bcg8e106dca321900ba@mail.gmail.com> On Sat, Feb 6, 2010 at 11:35 AM, David wrote: > Hello again, > > in Knowlton's 2008 book "Python: Create, Modify, Reuse" the author makes > frequent use of the term -1 in his code, but doesn't tell to what aim. For > want of search terms Google is not helpful. Could someone please enlighten > me by means of a one-liner as a reply? > > Example Code: > > for item in filelist: > ? ? ? ?if item.find(extension)!= -1: > ? ? ? ? ? ?snaplist.append(item) Wayne has explained the -1; I will add that a more idiomatic way to write this is for item in filelist: if extension in item: snaplist.append(item) or using a list comprehension (assuming snaplist starts out empty): snaplist = [ item for item in filelist if extension in item ] Assuming extension is a file extension, I would actually use endswith() to filter the items: snaplist = [ item for item in filelist if item.endswith(extension) ] Kent From alan.gauld at btinternet.com Sat Feb 6 19:29:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Feb 2010 18:29:59 -0000 Subject: [Tutor] how to graph percentile -- matplotlib, Inkscape, or what? References: <4B6D206E.90508@gmx.net> <4B6D37E4.9050606@gmx.net> Message-ID: "David" wrote in message news:4B6D37E4.9050606 at gmx.net... > matplotlib. I guess the reason why I discarded it before is that I > understood matplotlib to be a curve plotting tool, and not so much a > tool to draw graphics. I will investigate! It is but a single point on a an axis is a pretty basic curve! But as I say, I've never used it, I just assumed this should be verging on the trivial for it. Alan G. From alan.gauld at btinternet.com Sat Feb 6 19:33:36 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Feb 2010 18:33:36 -0000 Subject: [Tutor] Uninstalling MatPlotLib? (Win7) References: <4B6D8C67.3010103@sbcglobal.net> Message-ID: "Wayne Watson" wrote >I should have installed NumPy before MPL. How do I uninstall it. I'm >pretty sure it was an msi file. In that case it should be listed under Add/Remove programs in Control Panel. Alan G From mammar at gmail.com Sat Feb 6 19:48:49 2010 From: mammar at gmail.com (Muhammad Ammar) Date: Sat, 6 Feb 2010 23:48:49 +0500 Subject: [Tutor] Subprocess Stdout Redirection Message-ID: Hi, Hope you will be fine and good. Following is a snippet of python code i am using for a regression testing. def StartProc(dir, parm): global proc proc_log = open(dir + os.sep + "MyLog.txt","w") #new path for each file if parm: proc = subprocess.Popen(path, 0, None, subprocess.PIPE, proc_log, None) else: MyReset(proc) #reset the process(proc) to its default values proc.stdout = proc_log #no effect print "fptr ", proc.stdout #endif #enddef prm = True for i in range(0, 5): StartProc(i, prm) prm = False #endfor What I want to do is to start an executable only once, but on each iteration I want to redirect the process output to a different file. What is happening, is that files are created in the different path, but output is redirected to the file that is created first time. Note: MyReset() initializes the process (executable) to its default values after the first iteration. Will the following line change the process stdout to new file? proc.stdout = proc_log If no, than can you kindly guide me to the right way * Note: In the StartProc() if i create a new process everytime **StartProc**() is called. Output is correctly redirected to proper file.* Waiting for you kind reply. Warm Regards, -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldl08 at gmx.net Sun Feb 7 02:29:20 2010 From: ldl08 at gmx.net (David) Date: Sun, 07 Feb 2010 09:29:20 +0800 Subject: [Tutor] if item.find(extension)!= -1: -- what's the -1? In-Reply-To: <4B6D9A3B.3060509@gmx.net> References: <4B6D9A3B.3060509@gmx.net> Message-ID: <4B6E1770.9070000@gmx.net> Thank you Wayne, Kent, it's easy to see clearly once told what to focus on ;-) David On 07/02/10 00:35, David wrote: > Hello again, > > in Knowlton's 2008 book "Python: Create, Modify, Reuse" the author makes > frequent use of the term -1 in his code, but doesn't tell to what aim. > For want of search terms Google is not helpful. Could someone please > enlighten me by means of a one-liner as a reply? > > Thank you! > > David > > > Example Code: > > for item in filelist: > if item.find(extension)!= -1: > snaplist.append(item) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From sierra_mtnview at sbcglobal.net Sun Feb 7 11:43:58 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Feb 2010 02:43:58 -0800 Subject: [Tutor] Uninstalling MatPlotLib? (Win7) In-Reply-To: <23739e0a1002070111l62deac71sa011778a073dbf69@mail.gmail.com> References: <4B6D8C67.3010103@sbcglobal.net> <23739e0a1002070111l62deac71sa011778a073dbf69@mail.gmail.com> Message-ID: <4B6E996E.4040905@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Feb 7 12:20:39 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Feb 2010 03:20:39 -0800 Subject: [Tutor] Uninstalling MatPlotLib? (Win7) In-Reply-To: <4B6E996E.4040905@sbcglobal.net> References: <4B6D8C67.3010103@sbcglobal.net> <23739e0a1002070111l62deac71sa011778a073dbf69@mail.gmail.com> <4B6E996E.4040905@sbcglobal.net> Message-ID: <4B6EA207.6080505@sbcglobal.net> An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sun Feb 7 13:24:30 2010 From: denis.spir at free.fr (spir) Date: Sun, 7 Feb 2010 13:24:30 +0100 Subject: [Tutor] why inline-only string literals? Message-ID: <20100207132430.7752e961@o> Hello, I recently wrote a parser for a (game scripting) language in which ordinary strings inside quotes can hold (literal) newlines: s = "Hello, how do you do?" So, I wonder why most languages do not allow that from scratch; and some, like python, need a special syntax for multi-line strings. This is no parsing issue: instead, the pattern is simpler for it does need to refuse newlines! Note: Like python, this languages takes end-of-line (outside quotes) as end-of-statement token. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From ssiverling at gmail.com Fri Feb 5 23:14:49 2010 From: ssiverling at gmail.com (ssiverling) Date: Fri, 5 Feb 2010 14:14:49 -0800 (PST) Subject: [Tutor] Variable: From input and output In-Reply-To: References: <27457364.post@talk.nabble.com> <1c2a2c591002041259r604f0b60j341910f644256def@mail.gmail.com> <27460922.post@talk.nabble.com> <1c2a2c591002050434v14f9a4e7ic3a530f5ea0a83f6@mail.gmail.com> Message-ID: <27474641.post@talk.nabble.com> Greetings, Thanks, and I will try and not to toppost. I've joined the mailing list also. sincerely, steve Rohit Roger$ wrote: > > Answer: > Here is the code : > >>>> firstname = raw_input("\n Enter your first name : ") >>>> lastname = raw_input("\n Enter your last name : ") >>>> print (" Printing Your Complete name.............") >>>> print firstname + " " + lastname > > Regards, > Rohit > > On Fri, Feb 5, 2010 at 6:04 PM, Kent Johnson wrote: > >> On Thu, Feb 4, 2010 at 5:39 PM, ssiverling wrote: >> > >> > >> > I uploaded a file. I know it's not very impressive. >> >> Where did you upload it? >> >> For short programs you can just include them in your email. >> >> Also, please don't top-post, and please subscribe to the list. >> >> Kent >> > >> > >> > Kent Johnson wrote: >> >> >> >> On Thu, Feb 4, 2010 at 1:19 PM, ssiverling >> wrote: >> >> >> >>> So I have been working on this example for a little while. I looked >> for >> >>> the >> >>> answer before posting. I tried to use two raw inputs, then use >> >>> sys.stdout.write, to add them together. However I think I might need >> to >> >>> use >> >>> a variable. Any help would be appreciated. Thank you in advance. >> >> >> >> What have you done so far? If you show us some code we can better help >> >> you. >> >> >> >> Kent >> >> _______________________________________________ >> >> Tutor maillist - Tutor at python.org >> >> To unsubscribe or change subscription options: >> >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> >> > http://old.nabble.com/file/p27460922/psy psy >> > -- >> > View this message in context: >> http://old.nabble.com/Variable%3A-From-input-and-output-tp27457364p27460922.html >> > Sent from the Python - tutor mailing list archive at Nabble.com. >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> > http://mail.python.org/mailman/listinfo/tutor >> > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://old.nabble.com/Variable%3A-From-input-and-output-tp27457364p27474641.html Sent from the Python - tutor mailing list archive at Nabble.com. From chester_lab at fltg.net Sat Feb 6 22:36:39 2010 From: chester_lab at fltg.net (FT) Date: Sat, 6 Feb 2010 16:36:39 -0500 Subject: [Tutor] SYS Long File Names? Message-ID: <001e01caa774$8d3cafd0$6401a8c0@brucetower> Hi! I was looking at the sys.argv(1) file name and it is the short 8 char name. How do you place it into the long file name format? I was reading music files and comparing the name to the directory listing and always comes back as not found because the name was shortened. So, how do you get it to read long file names? Bruce From denis.spir at free.fr Sun Feb 7 13:58:20 2010 From: denis.spir at free.fr (spir) Date: Sun, 7 Feb 2010 13:58:20 +0100 Subject: [Tutor] Variable: From input and output In-Reply-To: <27474641.post@talk.nabble.com> References: <27457364.post@talk.nabble.com> <1c2a2c591002041259r604f0b60j341910f644256def@mail.gmail.com> <27460922.post@talk.nabble.com> <1c2a2c591002050434v14f9a4e7ic3a530f5ea0a83f6@mail.gmail.com> <27474641.post@talk.nabble.com> Message-ID: <20100207135820.52c7e449@o> On Fri, 5 Feb 2010 14:14:49 -0800 (PST) ssiverling wrote: > > Greetings, > > Thanks, and I will try and not to toppost. You just did it right now ;-) Also, a good practice is to cut out irrelevant parts of previous massage(s) in thread. Both work together to make threads fast/easy/pleasant to follow. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From mail at timgolden.me.uk Sun Feb 7 15:10:40 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 07 Feb 2010 14:10:40 +0000 Subject: [Tutor] SYS Long File Names? In-Reply-To: <001e01caa774$8d3cafd0$6401a8c0@brucetower> References: <001e01caa774$8d3cafd0$6401a8c0@brucetower> Message-ID: <4B6EC9E0.3030003@timgolden.me.uk> On 06/02/2010 21:36, FT wrote: > I was looking at the sys.argv(1) file name and it is the short 8 char > name. How do you place it into the long file name format? I was reading > music files and comparing the name to the directory listing and always comes > back as not found because the name was shortened. I'm assuming you're on Windows (because I don't think *nix has a long/short-name concept). I've never seen sys.argv return an 8.3 name, but taking your word for it: import win32api print win32api.GetLongPathName ("eight.thr") If you don't have the pywin32 packages installed (and you don't want to) then you can do the same using ctypes by accessing the kernel32 DLL: http://msdn.microsoft.com/en-us/library/aa364980%28VS.85%29.aspx TJG From sierra_mtnview at sbcglobal.net Sun Feb 7 17:49:16 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Feb 2010 08:49:16 -0800 Subject: [Tutor] Uninstalling MatPlotLib? (Win7)--Package Install Order In-Reply-To: <4B6EA207.6080505@sbcglobal.net> References: <4B6D8C67.3010103@sbcglobal.net> <23739e0a1002070111l62deac71sa011778a073dbf69@mail.gmail.com> <4B6E996E.4040905@sbcglobal.net> <4B6EA207.6080505@sbcglobal.net> Message-ID: <4B6EEF0C.1050703@sbcglobal.net> An HTML attachment was scrubbed... URL: From ldl08 at gmx.net Sun Feb 7 18:34:20 2010 From: ldl08 at gmx.net (David) Date: Mon, 08 Feb 2010 01:34:20 +0800 Subject: [Tutor] how to graph percentile -- matplotlib, Inkscape, or what? In-Reply-To: References: <4B6D206E.90508@gmx.net> <4B6D37E4.9050606@gmx.net> Message-ID: <4B6EF99C.8030504@gmx.net> Yes, you are right, I initially certainly didn't think of it as a function. Right now I am wondering if it would not be more straight forward to take for the 'axis' a bitmap background and place the needle (another bitmap) at the right position of the background. Come to think of it, PyX might be a good choice for this sort of thing. But again, I have not practical experience with that tool. David On 07/02/10 02:29, Alan Gauld wrote: > > "David" wrote in message news:4B6D37E4.9050606 at gmx.net... >> matplotlib. I guess the reason why I discarded it before is that I >> understood matplotlib to be a curve plotting tool, and not so much a >> tool to draw graphics. I will investigate! > > It is but a single point on a an axis is a pretty basic curve! > But as I say, I've never used it, I just assumed this should be verging > on the trivial for it. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at alchemy.com Sun Feb 7 18:54:12 2010 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 7 Feb 2010 09:54:12 -0800 Subject: [Tutor] why inline-only string literals? Message-ID: <20100207175412.GA47367@dragon.alchemy.com> > So, I wonder why most languages do not allow that from scratch; > and some, like python, need a special syntax for multi-line strings. > This is no parsing issue: instead, the pattern is simpler for it > does need to refuse newlines! I believe it's a deliberate design decision, not lack of ability to parse multi-line strings. You're right, it's easy for the compiler to handle the case. What happens too often, though, is that people forget a quote somewhere, so the compiler interprets that, plus a lot of lines of code following it, as a valid multi-line string, leading to confusion and possibly misleading error messages. So by making you explicitly state when you wanted multi-line strings, it makes it easier to spot this common mistake as well as making your intent more clear when just looking at the code. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From simbobo at cooptel.net Sun Feb 7 07:20:41 2010 From: simbobo at cooptel.net (Owain Clarke) Date: Sun, 07 Feb 2010 06:20:41 +0000 Subject: [Tutor] language aid (various) In-Reply-To: References: Message-ID: <4B6E5BB9.9030103@cooptel.net> Thanks to all. I will now try to absorb suggestions and follow up links - and no doubt get back to you with my next problem! Owain From alan.gauld at btinternet.com Mon Feb 8 00:52:44 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Feb 2010 23:52:44 -0000 Subject: [Tutor] why inline-only string literals? References: <20100207175412.GA47367@dragon.alchemy.com> Message-ID: "Steve Willoughby" wrote >> So, I wonder why most languages do not allow that from scratch; >> and some, like python, need a special syntax for multi-line strings. > > to handle the case. What happens too often, though, is that people > forget a quote somewhere, so the compiler interprets that, plus a > lot of lines of code following it, as a valid multi-line string, > leading to confusion and possibly misleading error messages. Thats a good reason and I hadn't thought of it. My initial thought was that it was just historical since most early interpreters/compilers processed programs line by line. Recall the dreaded line numbers of BASIC? So it made sense for strings (and comments) to be limited to a single line. But modern languages are much more fluid (and Lisp was always so) and multi line comments and strings are more common. (As Python proves with its triple quote syntax) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Mon Feb 8 01:09:21 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 07 Feb 2010 19:09:21 -0500 Subject: [Tutor] SYS Long File Names? In-Reply-To: <001e01caa774$8d3cafd0$6401a8c0@brucetower> References: <001e01caa774$8d3cafd0$6401a8c0@brucetower> Message-ID: <4B6F5631.2080005@ieee.org> FT wrote: > Hi! > > I was looking at the sys.argv(1) file name and it is the short 8 char > name. How do you place it into the long file name format? I was reading > music files and comparing the name to the directory listing and always comes > back as not found because the name was shortened. > > So, how do you get it to read long file names? > > Bruce > > > You need square brackets, not parentheses on the sys.argv. But I'm guessing that's a typo in your message. Some more information, please. What version of Python, and what OS ? And how are you running this script? If you're typing the script name at a DOS box, then the string you're seeing in sys.argv[1] is the one you typed on the command line. If you start it some other way, please tell us how. DaveA From x7-g5W_rt at earthlink.net Mon Feb 8 03:45:32 2010 From: x7-g5W_rt at earthlink.net (Gil Johnson) Date: Mon, 8 Feb 2010 02:45:32 +0000 (UTC) Subject: [Tutor] Subprocess Stdout Redirection References: Message-ID: Muhammad, I am no expert, but I think you have to call proc_log.close() in your StartProc() to make sure that the file is written out to disk. If I understand what you are doing, you are trying to generate a new path for each pass through the loop, of the form 0/, 1/,... and write "MyLog.txt" to the new directory. When I did something like this in the past I put the files MyLog0.txt, MyLog1.txt, MyLog2.txt,... in a single directory, which was simpler and more convenient for me when I gathered the information together for analysis: def NewProc(FileNum): filename = "MyLog" + repr(FileNum) + ".txt" proc_log = open(filename,"w") proc_log.write("Output here") proc_log.close() return for i in range(0, 5): NewProc(i) From sierra_mtnview at sbcglobal.net Mon Feb 8 05:11:16 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 07 Feb 2010 20:11:16 -0800 Subject: [Tutor] Closing a matplotlib window after show() Message-ID: <4B6F8EE4.3040003@sbcglobal.net> The code below is a typical example of matplotlib use. I've used it both in xp and win7 in IDLE. It produces the required plos and stop with the plot display. If I close the plot window with the x in the upper right corner, the shell window is left open. I have to do the same to close it. If I run it again, and look at the shell window, it looks hung up with the cursor below the >>> prompt. Ctrl-c doesn't break it, and I have to resort to x again. There must be some mechanism to insert below that allows the program to continue on and thus complete. Supposedly fig.close() will but I've put it in several places and have gotten unknown attribute to figure. Comments? ================ from matplotlib.pyplot import figure, show from numpy import arange, pi, cos, sin, pi from numpy.random import rand # unit area ellipse rx, ry = 3., 1. area = rx * ry * pi theta = arange(0, 2*pi+0.01, 0.1) verts = zip(rx/area*cos(theta), ry/area*sin(theta)) x,y,s,c = rand(4, 30) s*= 10**2. fig = figure() ax = fig.add_subplot(111) ax.scatter(x,y,s,c,marker=None,verts =verts) show() -- My life in two words. "Interrupted Projects." -- WTW (quote originator) From denis.spir at free.fr Mon Feb 8 09:29:30 2010 From: denis.spir at free.fr (spir) Date: Mon, 8 Feb 2010 09:29:30 +0100 Subject: [Tutor] why inline-only string literals? In-Reply-To: <20100207175412.GA47367@dragon.alchemy.com> References: <20100207175412.GA47367@dragon.alchemy.com> Message-ID: <20100208092930.27609d02@o> [sorry, Steve, first replied to sender instead of list] On Sun, 7 Feb 2010 09:54:12 -0800 Steve Willoughby wrote: > I believe it's a deliberate design decision, [...] > So by making you explicitly state when you wanted multi-line strings, > it makes it easier to spot this common mistake as well as making > your intent more clear when just looking at the code. Thank you. I guess this really makes sense. Or rather it did make sense at the time of python design. Nowadays most editors (even not programming editors) are able to _very_ clearly show such errors (when I add a quote, the whole rest of the code becomes a string ;-). It seems such a change would be backwards-compatible, no? I thought there may be a (for me) hidden issue due to lexer+parser separation. My parser was PEG-based, so with a single grammar and a single pass. I'm not used to reason about lexers and token strings. But since python does have multi-line strings, anyway... Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From sierra_mtnview at sbcglobal.net Mon Feb 8 20:54:27 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 08 Feb 2010 11:54:27 -0800 Subject: [Tutor] Closing a matplotlib window after show() In-Reply-To: <4B6F8EE4.3040003@sbcglobal.net> References: <4B6F8EE4.3040003@sbcglobal.net> Message-ID: <4B706BF3.107@sbcglobal.net> When I installed matplotlib2.5 on my W7 machine last were a few error msgs about missing about missing files. Is that usual for matplotlib. BTW, I've posted details of my problem to the MPL list. Here I'm interested in the basic of install and use with IDLE, and not the details of the use of MPL. Supposedly an uninstall is provided by a Python setup tool. I hae not used it yet. The basic problem is the show(). One person checked out the examples I provided and found show() to operate fine. On my XP machine the program I'm modifying has plot code someone put in a year or two ago, and it all works fine. My code produces the desired plot, but gets hung up on show(). On 2/7/2010 8:11 PM, Wayne Watson wrote: > The code below is a typical example of matplotlib use. I've used it > both in xp and win7 in IDLE. It produces the required plots and stop > with the plot display. If I close the plot window with the x in the > upper right corner, the shell window is left open. I have to do the > same to close it. If I run it again, and look at the shell window, it > looks hung up with the cursor below the >>> prompt. Ctrl-c doesn't > break it, and I have to resort to x again. There must be some > mechanism to insert below that allows the program to continue on and > thus complete. Supposedly fig.close() will but I've put it in several > places and have gotten unknown attribute to figure. > Comments? > > ================ > from matplotlib.pyplot import figure, show > from numpy import arange, pi, cos, sin, pi > from numpy.random import rand > > # unit area ellipse > rx, ry = 3., 1. > area = rx * ry * pi > theta = arange(0, 2*pi+0.01, 0.1) > verts = zip(rx/area*cos(theta), ry/area*sin(theta)) > > x,y,s,c = rand(4, 30) > s*= 10**2. > > fig = figure() > ax = fig.add_subplot(111) > ax.scatter(x,y,s,c,marker=None,verts =verts) > > show() > > > > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From bevan07 at gmail.com Mon Feb 8 22:02:46 2010 From: bevan07 at gmail.com (bevan j) Date: Mon, 8 Feb 2010 13:02:46 -0800 (PST) Subject: [Tutor] datetime a.m. not AM Message-ID: <27506228.post@talk.nabble.com> Hello, I have an issue with data that I am trying to convert to datetime. It has 'a.m.' rather than 'am' and the %p format doesn't seem to work. I am pretty sure there should be an easy solution. That said I can not see it at the moment. the following illustrates the issue. test1 and test2 work BUT my data is in the format of 'data below: import StringIO import datetime test1 = '1/09/1978 1:00:00 ' test2 = '1/09/1978 1:00:00 am' data = '1/09/1978 1:00:00 a.m.' print datetime.datetime.strptime(test1,('%d/%m/%Y %I:%M:%S ')) print datetime.datetime.strptime(test2,('%d/%m/%Y %I:%M:%S %p')) print datetime.datetime.strptime(data,('%d/%m/%Y %I:%M:%S %p')) Thank you for your time, bevan -- View this message in context: http://old.nabble.com/datetime-a.m.-not-AM-tp27506228p27506228.html Sent from the Python - tutor mailing list archive at Nabble.com. From sander.sweers at gmail.com Mon Feb 8 23:00:40 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 08 Feb 2010 23:00:40 +0100 Subject: [Tutor] datetime a.m. not AM In-Reply-To: <27506228.post@talk.nabble.com> References: <27506228.post@talk.nabble.com> Message-ID: <1265666440.28498.1.camel@infirit> On ma, 2010-02-08 at 13:02 -0800, bevan j wrote: > data = '1/09/1978 1:00:00 a.m.' If you know this will always be in the form of 'a.m.' you can replace it with 'am' by data.replace('a.m.','am'). Greets Sander From bevan07 at gmail.com Mon Feb 8 22:55:47 2010 From: bevan07 at gmail.com (bevan j) Date: Mon, 8 Feb 2010 13:55:47 -0800 (PST) Subject: [Tutor] datetime a.m. not AM In-Reply-To: <27506228.post@talk.nabble.com> References: <27506228.post@talk.nabble.com> Message-ID: <27506926.post@talk.nabble.com> Well, I have managed to get it working by using the locale setting. It would be nice to use the am/pm setting only and leave the rest unset. Will have to look into it further. Any tips? import locale #to set locale to use a.m. instead of AM locale.setlocale(locale.LC_ALL, '') bevan j wrote: > > Hello, > > I have an issue with data that I am trying to convert to datetime. It has > 'a.m.' rather than 'am' and the %p format doesn't seem to work. I am > pretty sure there should be an easy solution. That said I can not see it > at the moment. the following illustrates the issue. test1 and test2 work > BUT my data is in the format of 'data below: > > import StringIO > import datetime > > test1 = '1/09/1978 1:00:00 ' > test2 = '1/09/1978 1:00:00 am' > data = '1/09/1978 1:00:00 a.m.' > > print datetime.datetime.strptime(test1,('%d/%m/%Y %I:%M:%S ')) > print datetime.datetime.strptime(test2,('%d/%m/%Y %I:%M:%S %p')) > print datetime.datetime.strptime(data,('%d/%m/%Y %I:%M:%S %p')) > > Thank you for your time, > > bevan > > -- View this message in context: http://old.nabble.com/datetime-a.m.-not-AM-tp27506228p27506926.html Sent from the Python - tutor mailing list archive at Nabble.com. From internets at shaneferguson.com Mon Feb 8 23:15:33 2010 From: internets at shaneferguson.com (internets at shaneferguson.com) Date: Mon, 8 Feb 2010 14:15:33 -0800 Subject: [Tutor] List Comprehension question Message-ID: I've been trying to work my way through some 'beginner projects' I found around the web, one of them involves generating some random numbers. I decided to use a list of lists, and I'm wondering if this is a valid comprehension...IDLE doesn't seem to mind, but maybe I lack the experience to know better: numbers = [[random.randint(1, 10) for x in range(5)] for y in range(5)] I'm using Python 3.1. If this is valid, is there a shorter version or better way? Thanks! From eike.welk at gmx.net Mon Feb 8 23:23:09 2010 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 8 Feb 2010 23:23:09 +0100 Subject: [Tutor] Closing a matplotlib window after show() In-Reply-To: <4B706BF3.107@sbcglobal.net> References: <4B6F8EE4.3040003@sbcglobal.net> <4B706BF3.107@sbcglobal.net> Message-ID: <201002082323.10059.eike.welk@gmx.net> Hello Wayne! On Monday February 8 2010 20:54:27 Wayne Watson wrote: > The basic problem is the show(). One person checked out the examples I > provided and found show() to operate fine. On my XP machine the program > I'm modifying has plot code someone put in a year or two ago, and it all > works fine. My code produces the desired plot, but gets hung up on show(). The behavior that you describe, is the normal behavior of Matplotlib: When you call show(), the program gets stuck. Therefore the call to show is always the last statement in the example programs. Show returns when the last plot window is closed, and in principle the program could then continue. If you want to look at plots while the program is running, you must use Ipython. This is a modified Python interpreter, that contains special code to change the way how Matplotlib works. http://ipython.scipy.org/moin/ Eike. From rabidpoobear at gmail.com Tue Feb 9 00:30:12 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 8 Feb 2010 17:30:12 -0600 Subject: [Tutor] List Comprehension question In-Reply-To: References: Message-ID: On Mon, Feb 8, 2010 at 4:15 PM, wrote: > I've been trying to work my way through some 'beginner projects' I found > around the web, one of them involves generating some random numbers. I > decided to use a list of lists, and I'm wondering if this is a valid > comprehension...IDLE doesn't seem to mind, but maybe I lack the experience > to know better: > > numbers = [[random.randint(1, 10) for x in range(5)] for y in range(5)] > > I'm using Python 3.1. If this is valid, is there a shorter version or > better way? > If Python executes it without throwing exceptions that means it's syntactically valid. Are you asking if it's semantically valid? Well, that depends what you're trying to do. Are you trying to make a 5x5 matrix of random numbers chosen from [1,2,3,4,5,6,7,8,9,10]? In that case I'd say it does what you want. most people opt to use randrange rather than randint though as it makes more sense when related to other range functions. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ailxroot at gmail.com Tue Feb 9 03:54:06 2010 From: ailxroot at gmail.com (ailx ailx) Date: Tue, 9 Feb 2010 10:54:06 +0800 Subject: [Tutor] python Message-ID: <5fc821071002081854k2fa92309ned9389b9f3d915e5@mail.gmail.com> python -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Tue Feb 9 04:09:59 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 8 Feb 2010 21:09:59 -0600 Subject: [Tutor] python In-Reply-To: <5fc821071002081854k2fa92309ned9389b9f3d915e5@mail.gmail.com> References: <5fc821071002081854k2fa92309ned9389b9f3d915e5@mail.gmail.com> Message-ID: quite. On Mon, Feb 8, 2010 at 8:54 PM, ailx ailx wrote: > python > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Feb 9 06:53:39 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 08 Feb 2010 21:53:39 -0800 Subject: [Tutor] Closing a matplotlib window after show() In-Reply-To: <201002082323.10059.eike.welk@gmx.net> References: <4B6F8EE4.3040003@sbcglobal.net> <4B706BF3.107@sbcglobal.net> <201002082323.10059.eike.welk@gmx.net> Message-ID: <4B70F863.1070407@sbcglobal.net> Hi, I'm not so sure that's true. I have a large 900 line program where some original plot code just continues beyond plot() and show(), after the user closes the plot window. New code that I put in gets knotted up, as far as I can tell. In both cases, I've put print statements after show(), but nothing appears in the shell or, if run by clicking the program file, in the DOS-like window that appears. Further, I posted this elsewhere, and someone claims to have tried a few simple examples with show() at the ended,and they did not get tied up in knots when the user closed the window. I'm going to assume he used IDLE, or a straight execute of the file. On 2/8/2010 2:23 PM, Eike Welk wrote: > Hello Wayne! > > On Monday February 8 2010 20:54:27 Wayne Watson wrote: > >> The basic problem is the show(). One person checked out the examples I >> provided and found show() to operate fine. On my XP machine the program >> I'm modifying has plot code someone put in a year or two ago, and it all >> works fine. My code produces the desired plot, but gets hung up on show(). >> > The behavior that you describe, is the normal behavior of Matplotlib: When you > call show(), the program gets stuck. > > Therefore the call to show is always the last statement in the example > programs. Show returns when the last plot window is closed, and in principle > the program could then continue. > > If you want to look at plots while the program is running, you must use > Ipython. This is a modified Python interpreter, that contains special code to > change the way how Matplotlib works. > > http://ipython.scipy.org/moin/ > > > Eike. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From beachkid at insightbb.com Tue Feb 9 16:28:43 2010 From: beachkid at insightbb.com (Ken G.) Date: Tue, 09 Feb 2010 10:28:43 -0500 Subject: [Tutor] rstrip in list? Message-ID: <4B717F2B.7050209@insightbb.com> I printed out some random numbers to a list and use 'print mylist' and they came out like this: ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] I was using 'print mylist.rstrip()' to strip off the '\n' but kept getting an error of : AttributeError: 'list' object has no attribute 'rstrip' My memory must be hazy but I thought I had it working several months ago. Any idea or suggestion? TIA, Ken From zhengqinggan at gmail.com Tue Feb 9 16:41:58 2010 From: zhengqinggan at gmail.com (zhengqing gan) Date: Tue, 9 Feb 2010 09:41:58 -0600 Subject: [Tutor] Closing a matplotlib window after show() Message-ID: <4375c4a41002090741m5b2cfack71e317f970a6f092@mail.gmail.com> Hi, recently I have the same problem with Matplotlib. I wrote a wxpython program which can plot a graph when click a button. When I click the button first time, I got the plot correct, but when I closed the figure, and clicked the button again, the code crashed. I have to reopen the program, and the same problem happened. The solution is that put "import matplotlib.pyplot as plt" before you plot anything. Then everything works fine. I don't know why. It seems that when you close the figure, the imported module or function stop working. It has to be imported every time. On Tue, Feb 9, 2010 at 5:00 AM, wrote: > 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. python (ailx ailx) > 2. Re: python (Luke Paireepinart) > 3. Re: Closing a matplotlib window after show() (Wayne Watson) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 9 Feb 2010 10:54:06 +0800 > From: ailx ailx > To: tutor at python.org > Subject: [Tutor] python > Message-ID: > <5fc821071002081854k2fa92309ned9389b9f3d915e5 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > python > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20100209/a46c4683/attachment-0001.htm > > > > ------------------------------ > > Message: 2 > Date: Mon, 8 Feb 2010 21:09:59 -0600 > From: Luke Paireepinart > To: ailx ailx > Cc: tutor at python.org > Subject: Re: [Tutor] python > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > quite. > > On Mon, Feb 8, 2010 at 8:54 PM, ailx ailx wrote: > > > python > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20100208/b19399fe/attachment-0001.htm > > > > ------------------------------ > > Message: 3 > Date: Mon, 08 Feb 2010 21:53:39 -0800 > From: Wayne Watson > To: Eike Welk > Cc: tutor at python.org > Subject: Re: [Tutor] Closing a matplotlib window after show() > Message-ID: <4B70F863.1070407 at sbcglobal.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Hi, I'm not so sure that's true. I have a large 900 line program where > some original plot code just continues beyond plot() and show(), after > the user closes the plot window. New code that I put in gets knotted up, > as far as I can tell. In both cases, I've put print statements after > show(), but nothing appears in the shell or, if run by clicking the > program file, in the DOS-like window that appears. > > Further, I posted this elsewhere, and someone claims to have tried a few > simple examples with show() at the ended,and they did not get tied up in > knots when the user closed the window. I'm going to assume he used IDLE, > or a straight execute of the file. > > On 2/8/2010 2:23 PM, Eike Welk wrote: > > Hello Wayne! > > > > On Monday February 8 2010 20:54:27 Wayne Watson wrote: > > > >> The basic problem is the show(). One person checked out the examples I > >> provided and found show() to operate fine. On my XP machine the program > >> I'm modifying has plot code someone put in a year or two ago, and it all > >> works fine. My code produces the desired plot, but gets hung up on > show(). > >> > > The behavior that you describe, is the normal behavior of Matplotlib: > When you > > call show(), the program gets stuck. > > > > Therefore the call to show is always the last statement in the example > > programs. Show returns when the last plot window is closed, and in > principle > > the program could then continue. > > > > If you want to look at plots while the program is running, you must use > > Ipython. This is a modified Python interpreter, that contains special > code to > > change the way how Matplotlib works. > > > > http://ipython.scipy.org/moin/ > > > > > > Eike. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > "Crime is way down. War is declining. And that's far from the good > news." -- Steven Pinker (and other sources) Why is this true, but yet > the media says otherwise? The media knows very well how to manipulate us > (see limbic, emotion, $$). -- WTW > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 72, Issue 34 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Feb 9 16:45:19 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 9 Feb 2010 10:45:19 -0500 Subject: [Tutor] rstrip in list? In-Reply-To: <4B717F2B.7050209@insightbb.com> References: <4B717F2B.7050209@insightbb.com> Message-ID: <1c2a2c591002090745q3c003bb6x93f506d1653930d1@mail.gmail.com> On Tue, Feb 9, 2010 at 10:28 AM, Ken G. wrote: > I printed out some random numbers to a list and use 'print mylist' and > they came out like this: > > ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] How are you generating this list? You should be able to create it without the \n. That would be better than stripping them out. > I was using 'print mylist.rstrip()' to strip off the '\n' > > but kept getting an error of : > > AttributeError: 'list' object has no attribute 'rstrip' > > My memory must be hazy but I thought I had it working several months ago. > > Any idea or suggestion? Use a list comprehension or map(): In [1]: l = ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] In [2]: [ i.rstrip() for i in l ] Out[2]: ['102', '231', '463', '487', '555', '961'] In [3]: map(str.rstrip, l) Out[3]: ['102', '231', '463', '487', '555', '961'] Kent From steve at pearwood.info Tue Feb 9 16:55:01 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Feb 2010 02:55:01 +1100 Subject: [Tutor] rstrip in list? In-Reply-To: <4B717F2B.7050209@insightbb.com> References: <4B717F2B.7050209@insightbb.com> Message-ID: <201002100255.01717.steve@pearwood.info> On Wed, 10 Feb 2010 02:28:43 am Ken G. wrote: > I printed out some random numbers to a list and use 'print mylist' > and they came out like this: > > ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] > > I was using 'print mylist.rstrip()' to strip off the '\n' > > but kept getting an error of : > > AttributeError: 'list' object has no attribute 'rstrip' You have to apply rstrip to each item in the list, not the list itself. Here are two ways to do it: #1: modify the list in a for-loop for i, item in enumerate(mylist): mylist[i] = item.rstrip() #2: make a new list with a list comprehension mylist = [item.rstrip() for item in mylist] Of the two, I prefer the second. -- Steven D'Aprano From sander.sweers at gmail.com Tue Feb 9 16:56:38 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 9 Feb 2010 16:56:38 +0100 Subject: [Tutor] rstrip in list? In-Reply-To: <4B717F2B.7050209@insightbb.com> References: <4B717F2B.7050209@insightbb.com> Message-ID: <201002091656.38491.Sander.Sweers@gmail.com> On Tuesday 09 February 2010 16:28:43 Ken G. wrote: > ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] > > I was using 'print mylist.rstrip()' to strip off the '\n' > > but kept getting an error of : > > AttributeError: 'list' object has no attribute 'rstrip' A string has attribute rstrip not a list. You will need to loop over the list and update each item of the list with rstrip(). This, mylist = [s.rstrip('\n') for s in mylist], should do it. It might be that before making the list you did rstrip() on the individual strings..? Greets Sander From beachkid at insightbb.com Tue Feb 9 17:09:28 2010 From: beachkid at insightbb.com (Ken G.) Date: Tue, 09 Feb 2010 11:09:28 -0500 Subject: [Tutor] rstrip in list? In-Reply-To: <1c2a2c591002090745q3c003bb6x93f506d1653930d1@mail.gmail.com> References: <4B717F2B.7050209@insightbb.com> <1c2a2c591002090745q3c003bb6x93f506d1653930d1@mail.gmail.com> Message-ID: <4B7188B8.2060105@insightbb.com> Kent Johnson wrote: > On Tue, Feb 9, 2010 at 10:28 AM, Ken G. wrote: > >> I printed out some random numbers to a datafile and use 'print mylist' and >> they came out like this: >> >> ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] >> > > How are you generating this list? You should be able to create it > without the \n. That would be better than stripping them out. > I inputting some random numbers into a database and then created a list and appended the list as it read the database. > >> I was using 'print mylist.rstrip()' to strip off the '\n' >> >> but kept getting an error of : >> >> AttributeError: 'list' object has no attribute 'rstrip' >> >> My memory must be hazy but I thought I had it working several months ago. >> >> Any idea or suggestion? >> > > Use a list comprehension or map(): > > In [1]: l = ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] > > In [2]: [ i.rstrip() for i in l ] > Out[2]: ['102', '231', '463', '487', '555', '961'] > > In [3]: map(str.rstrip, l) > Out[3]: ['102', '231', '463', '487', '555', '961'] > > Kent > My database file has numbers of the same exact length that need to be sorted. I am using 'mylist.sort()' as one of the command. Actually, I will be using 'mylist.reverse' after that command. I am still in a learning mode. Thanks. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Feb 9 17:15:29 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 09 Feb 2010 11:15:29 -0500 Subject: [Tutor] rstrip in list? In-Reply-To: <4B717F2B.7050209@insightbb.com> References: <4B717F2B.7050209@insightbb.com> Message-ID: <4B718A21.8010908@gmail.com> Ken G. wrote: > I printed out some random numbers to a list and use 'print mylist' and > they came out like this: > > ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] > > I was using 'print mylist.rstrip()' to strip off the '\n' > > but kept getting an error of : > > AttributeError: 'list' object has no attribute 'rstrip' rstrip is a string method, not a list method. You must apply it to each element in the list. One way is: print [item.rstrip() for iten in mylist] -- Bob Gailer 919-636-4239 Chapel Hill NC From bermanrl at cfl.rr.com Tue Feb 9 17:15:33 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 9 Feb 2010 11:15:33 -0500 Subject: [Tutor] rstrip in list? In-Reply-To: <4B717F2B.7050209@insightbb.com> References: <4B717F2B.7050209@insightbb.com> Message-ID: <006201caa9a3$1b460ee0$51d22ca0$@rr.com> -----Original Message----- From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor-bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Ken G. Sent: Tuesday, February 09, 2010 10:29 AM To: tutor at python.org Subject: [Tutor] rstrip in list? I printed out some random numbers to a list and use 'print mylist' and they came out like this: ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] I was using 'print mylist.rstrip()' to strip off the '\n' but kept getting an error of : AttributeError: 'list' object has no attribute 'rstrip' My memory must be hazy but I thought I had it working several months ago. Any idea or suggestion? TIA, Ken In [14]: mylist Out[14]: ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] In [15]: for item in mylist: ....: print item.strip('\n') ....: ....: 102 231 463 487 555 961 I get the impression you can strip something from the elements in the list, but that it balks at a change to the entire list in a single statement? Robert _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Feb 9 17:49:37 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 9 Feb 2010 11:49:37 -0500 Subject: [Tutor] rstrip in list? In-Reply-To: <4B7188B8.2060105@insightbb.com> References: <4B717F2B.7050209@insightbb.com> <1c2a2c591002090745q3c003bb6x93f506d1653930d1@mail.gmail.com> <4B7188B8.2060105@insightbb.com> Message-ID: <1c2a2c591002090849w75196ff5ke7758ce948039f03@mail.gmail.com> On Tue, Feb 9, 2010 at 11:09 AM, Ken G. wrote: > > Kent Johnson wrote: > > On Tue, Feb 9, 2010 at 10:28 AM, Ken G. wrote: > > > I printed out some random numbers to a datafile and use 'print mylist' and > they came out like this: > > ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] > > > How are you generating this list? You should be able to create it > without the \n. That would be better than stripping them out. > > > I inputting some random numbers into a database and then created a list > and appended the list as it read the database. If you show the code for this perhaps we can figure out where the newlines are coming from. Kent From sierra_mtnview at sbcglobal.net Tue Feb 9 18:04:42 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 09 Feb 2010 09:04:42 -0800 Subject: [Tutor] Closing a matplotlib window after show() In-Reply-To: <4B70F863.1070407@sbcglobal.net> References: <4B6F8EE4.3040003@sbcglobal.net> <4B706BF3.107@sbcglobal.net> <201002082323.10059.eike.welk@gmx.net> <4B70F863.1070407@sbcglobal.net> Message-ID: <4B7195AA.50106@sbcglobal.net> Well, you are correct. Finally, my latest post to the MPL list caught the eye of John Hunter. I think he wrote MPL. The way out is interactive use. One problem I've had with Python packages they "seem" to based on some other product, which one is supposed to know. I sight Tkinter and now MPL. I last used MatLab five years ago, and wrote some simple programs in it, so at least I have a very modest idea of how it works. I may have to use it to grsp the interactive mode. This problem has been a difficult one get a grip on. I've had socket error problems, difficulty getting Matlab back up on my machine, a possible install problem, and a host of ambiguities about this use. The end is near. On 2/8/2010 9:53 PM, Wayne Watson wrote: > Hi, I'm not so sure that's true. I have a large 900 line program where > some original plot code just continues beyond plot() and show(), after > the user closes the plot window. New code that I put in gets knotted > up, as far as I can tell. In both cases, I've put print statements > after show(), but nothing appears in the shell or, if run by clicking > the program file, in the DOS-like window that appears. > > Further, I posted this elsewhere, and someone claims to have tried a > few simple examples with show() at the ended,and they did not get tied > up in knots when the user closed the window. I'm going to assume he > used IDLE, or a straight execute of the file. > > On 2/8/2010 2:23 PM, Eike Welk wrote: >> Hello Wayne! >> >> On Monday February 8 2010 20:54:27 Wayne Watson wrote: >>> The basic problem is the show(). One person checked out the examples I >>> provided and found show() to operate fine. On my XP machine the program >>> I'm modifying has plot code someone put in a year or two ago, and it >>> all >>> works fine. My code produces the desired plot, but gets hung up on >>> show(). >> The behavior that you describe, is the normal behavior of Matplotlib: >> When you >> call show(), the program gets stuck. >> >> Therefore the call to show is always the last statement in the example >> programs. Show returns when the last plot window is closed, and in >> principle >> the program could then continue. >> >> If you want to look at plots while the program is running, you must use >> Ipython. This is a modified Python interpreter, that contains special >> code to >> change the way how Matplotlib works. >> >> http://ipython.scipy.org/moin/ >> >> >> Eike. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From beachkid at insightbb.com Tue Feb 9 18:14:54 2010 From: beachkid at insightbb.com (Ken G.) Date: Tue, 09 Feb 2010 12:14:54 -0500 Subject: [Tutor] rstrip in list? (SOLVED) In-Reply-To: <201002100255.01717.steve@pearwood.info> References: <4B717F2B.7050209@insightbb.com> <201002100255.01717.steve@pearwood.info> Message-ID: <4B71980E.1070608@insightbb.com> There was so many different solutions presented here to me. Thanks to all. By adding '.strip('\n') to the last two lines below, it came out: Sorted List ['102', '231', '463', '487', '555', '961'] for line in file.readlines(): print line.strip('\n'), mylist.append(line.strip('\n')) Further work and studying needed here. LOL. Ken Steven D'Aprano wrote: > On Wed, 10 Feb 2010 02:28:43 am Ken G. wrote: > >> I printed out some random numbers to a list and use 'print mylist' >> and they came out like this: >> >> ['102\n', '231\n', '463\n', '487\n', '555\n', '961\n'] >> >> I was using 'print mylist.rstrip()' to strip off the '\n' >> >> but kept getting an error of : >> >> AttributeError: 'list' object has no attribute 'rstrip' >> > > You have to apply rstrip to each item in the list, not the list itself. > > Here are two ways to do it: > > #1: modify the list in a for-loop > for i, item in enumerate(mylist): > mylist[i] = item.rstrip() > > #2: make a new list with a list comprehension > mylist = [item.rstrip() for item in mylist] > > > Of the two, I prefer the second. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkid at insightbb.com Tue Feb 9 18:28:25 2010 From: beachkid at insightbb.com (Ken G.) Date: Tue, 09 Feb 2010 12:28:25 -0500 Subject: [Tutor] Embarrassed... Message-ID: <4B719B39.9060505@insightbb.com> I am a little embarrassed. I just happen to found a program I wrote in December that create random numbers into a file, copy the numbers into a list, print the numbers unsorted and sorted from the list without printing '\n'. Nevertheless, I do thanks you all for trying to help me out. Ken From sierra_mtnview at sbcglobal.net Tue Feb 9 21:05:33 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 09 Feb 2010 12:05:33 -0800 Subject: [Tutor] Closing a matplotlib window after show() In-Reply-To: <4B7195AA.50106@sbcglobal.net> References: <4B6F8EE4.3040003@sbcglobal.net> <4B706BF3.107@sbcglobal.net> <201002082323.10059.eike.welk@gmx.net> <4B70F863.1070407@sbcglobal.net> <4B7195AA.50106@sbcglobal.net> Message-ID: <4B71C00D.3020205@sbcglobal.net> Form me the solution is getting into interactive mode, which I had never heard of until this morning. On 2/9/2010 9:04 AM, Wayne Watson wrote: > Well, you are correct. Finally, my latest post to the MPL list caught > the eye of John Hunter. I think he wrote MPL. The way out is > interactive use. One problem I've had with Python packages they > "seem" to based on some other ... -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From zhuchunml at gmail.com Tue Feb 9 21:27:58 2010 From: zhuchunml at gmail.com (Joson) Date: Wed, 10 Feb 2010 04:27:58 +0800 Subject: [Tutor] apache2.2 - django deployment Message-ID: Hi all, I wanna deploy a django program on apache2.2. So I downloaded " mod_wsgi-win32-ap22py26-3.0.so" and copied it into apache2.2/modules/, renamed "mod_wsgi.so". in httpd.conf I appended sentence: LoadModule python_module modules/mod_wsgi.so Then It failed to start the server: httpd.exe: Syntax error on line 128 of C:/Program Files/Apache Software Foundati on/Apache2.2/conf/httpd.conf: Can't locate API module structure `python_module' in file C:/Program Files/Apache Software Foundation/Apache2.2/modules/mod_wsgi.s o: No error Note the errors or messages above, and press the key to exit. 21... Pls help me. thanks:) -------------- next part -------------- An HTML attachment was scrubbed... URL: From glenbot at gmail.com Tue Feb 9 22:48:46 2010 From: glenbot at gmail.com (Glen Zangirolami) Date: Tue, 9 Feb 2010 15:48:46 -0600 Subject: [Tutor] apache2.2 - django deployment In-Reply-To: References: Message-ID: <24a9d1f31002091348y31024d83h89dab58342675775@mail.gmail.com> Joson, Everything looks good but I think the *module name is incorrect.* Change: LoadModule *python_module *modules/mod_wsgi.so To: LoadModule *wsgi_module *modules/mod_wsgi.so Glen On Tue, Feb 9, 2010 at 2:27 PM, Joson wrote: > Hi all, > I wanna deploy a django program on apache2.2. So I downloaded " > mod_wsgi-win32-ap22py26-3.0.so" and copied it into apache2.2/modules/, > renamed "mod_wsgi.so". > > in httpd.conf I appended sentence: > LoadModule python_module modules/mod_wsgi.so > > Then It failed to start the server: > > httpd.exe: Syntax error on line 128 of C:/Program Files/Apache Software > Foundati > on/Apache2.2/conf/httpd.conf: Can't locate API module structure > `python_module' > in file C:/Program Files/Apache Software > Foundation/Apache2.2/modules/mod_wsgi.s > o: No error > Note the errors or messages above, and press the key to exit. 21... > > Pls help me. thanks:) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From glenbot at gmail.com Tue Feb 9 23:36:21 2010 From: glenbot at gmail.com (Glen Zangirolami) Date: Tue, 9 Feb 2010 16:36:21 -0600 Subject: [Tutor] apache2.2 - django deployment In-Reply-To: References: Message-ID: <24a9d1f31002091436k56e80c50x6be0541e1126dad5@mail.gmail.com> Joson, Everything looks good but I think the *module name is incorrect.* Change: LoadModule *python_module *modules/mod_wsgi.so To: LoadModule *wsgi_module *modules/mod_wsgi.so Glen On Tue, Feb 9, 2010 at 2:27 PM, Joson wrote: > Hi all, > I wanna deploy a django program on apache2.2. So I downloaded " > mod_wsgi-win32-ap22py26-3.0.so" and copied it into apache2.2/modules/, > renamed "mod_wsgi.so". > > in httpd.conf I appended sentence: > LoadModule python_module modules/mod_wsgi.so > > Then It failed to start the server: > > httpd.exe: Syntax error on line 128 of C:/Program Files/Apache Software > Foundati > on/Apache2.2/conf/httpd.conf: Can't locate API module structure > `python_module' > in file C:/Program Files/Apache Software > Foundation/Apache2.2/modules/mod_wsgi.s > o: No error > Note the errors or messages above, and press the key to exit. 21... > > Pls help me. thanks:) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Feb 10 03:00:08 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 09 Feb 2010 18:00:08 -0800 Subject: [Tutor] Exiting a Tkinter Program-- An Anomaly or two Message-ID: <4B721328.1090002@sbcglobal.net> I'm looking a 1800+ line someone else wrote. It uses one large dialog for menus, and has a large area for images. A few menus open small dialogs, for example, to enter a file name. The File menu has an exit choice. The only other exit is the x in the upper right corner of the large dialog. I'm pretty sure that menu is coded to quit via a shoft def in the program. def Quite(self) self.running = False self.master.quit() I see no other code to quit. If I use Exit, the program does not quite. If I then use the x, it quits and the shell script is left open for a command. Any ideas why Quit doesn't work? It's accessible via a self.mainMenu.add_command(.. command=self.Quit) I had not turned the program loose by using a menu or touching any controls. If I cause the program to print to the shell, and then use x to exit that it hangs the shell. Why? When I x the shell, it tells me the prog is running. Do I want to kill it. Yes,kills the shell window. The above seem abnormal to me. Comments? -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From ldl08 at gmx.net Wed Feb 10 04:00:05 2010 From: ldl08 at gmx.net (David) Date: Wed, 10 Feb 2010 11:00:05 +0800 Subject: [Tutor] NameError: global name 'celsius' is not defined (actually, solved) Message-ID: <4B722135.5030006@gmx.net> Hi guys, I just wrote this message, but after restarting ipython all worked fine. How is it to be explained that I first had a namespace error which, after a restart (and not merely a new "run Sande_celsius-main.py"), went away? I mean, surely the namespace should not be impacted by ipython at all!? Many thanks, David Dear List, this should be so basic that I feel bad asking this question here, but I don't get it. I am having a look at Sande's book "Hello World". The topic is 'Modules', and the code comes directly from the book. I have two files: Sande_celsius-main.py and Sande_my_module.py. I import the latter from within the former. # file: Sande_celsius-main.py from Sande_my_module import c_to_f celsius = float(raw_input("Enter a temperature in Celsius: ")) fahrenheit = c_to_f(celsius) print "That's ", fahrenheit, " degrees Fahrenheit" # this is the file Sande_my_module.py # we're going to use it in another program def c_to_f(celsius): fahrenheit = celsius * 9.0 / 5 + 32 return fahrenheit When I run Sande_celsius-main.py, I get the following error: NameError: global name 'celsius' is not defined WARNING: Failure executing file: First of all, this error message doesn't exactly tell me _where_ the problem is, does it? It could be a problem with(in) the imported function c_to_f... I wish he would tell me: "Problem in file x, line y". Secondly, the name celsius in the global namespace of ~-main.py is merely a variable, which later is then used as a parameter to c_to_f. I do not see a problem here. What is going on? From wescpy at gmail.com Wed Feb 10 04:13:20 2010 From: wescpy at gmail.com (wesley chun) Date: Tue, 9 Feb 2010 19:13:20 -0800 Subject: [Tutor] NameError: global name 'celsius' is not defined (actually, solved) In-Reply-To: <4B722135.5030006@gmx.net> References: <4B722135.5030006@gmx.net> Message-ID: <78b3a9581002091913u27dc639ft71a11af46dddb595@mail.gmail.com> > I just wrote this message, but after restarting ipython all worked fine. > How is it to be explained that I first had a namespace error which, after a > restart (and not merely a new "run Sande_celsius-main.py"), went away? I > mean, surely the namespace should not be impacted by ipython at all!? > : > # file: Sande_celsius-main.py > from Sande_my_module import c_to_f > celsius = float(raw_input("Enter a temperature in Celsius: ")) > fahrenheit = c_to_f(celsius) > print "That's ", fahrenheit, " degrees Fahrenheit" > > # this is the file Sande_my_module.py > # we're going to use it in another program > def c_to_f(celsius): > ? ?fahrenheit = celsius * 9.0 / 5 + 32 > ? ?return fahrenheit > > When I run Sande_celsius-main.py, I get the following error: > > NameError: global name 'celsius' is not defined > WARNING: Failure executing file: Python interpreters including the standard one or IPython should tell you a lot more than that. how are you executing this code? would it be possible to do so from the command-line? you should get a more verbose error message that you can post here. best regards, -- 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 ldl08 at gmx.net Wed Feb 10 06:06:43 2010 From: ldl08 at gmx.net (David) Date: Wed, 10 Feb 2010 13:06:43 +0800 Subject: [Tutor] NameError: global name 'celsius' is not defined (actually, solved) In-Reply-To: <78b3a9581002091913u27dc639ft71a11af46dddb595@mail.gmail.com> References: <4B722135.5030006@gmx.net> <78b3a9581002091913u27dc639ft71a11af46dddb595@mail.gmail.com> Message-ID: <4B723EE3.7060501@gmx.net> Hello Wesley, thanks for your reply. I was surprised about the limited information too. Sadly (?), I can't reproduce the error any more... David On 10/02/10 11:13, wesley chun wrote: >> I just wrote this message, but after restarting ipython all worked fine. >> How is it to be explained that I first had a namespace error which, after a >> restart (and not merely a new "run Sande_celsius-main.py"), went away? I >> mean, surely the namespace should not be impacted by ipython at all!? >> : >> # file: Sande_celsius-main.py >> from Sande_my_module import c_to_f >> celsius = float(raw_input("Enter a temperature in Celsius: ")) >> fahrenheit = c_to_f(celsius) >> print "That's ", fahrenheit, " degrees Fahrenheit" >> >> # this is the file Sande_my_module.py >> # we're going to use it in another program >> def c_to_f(celsius): >> fahrenheit = celsius * 9.0 / 5 + 32 >> return fahrenheit >> >> When I run Sande_celsius-main.py, I get the following error: >> >> NameError: global name 'celsius' is not defined >> WARNING: Failure executing file: > > > Python interpreters including the standard one or IPython should tell > you a lot more than that. how are you executing this code? would it be > possible to do so from the command-line? you should get a more verbose > error message that you can post here. > > best regards, > -- 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 sudheer.kay at gmail.com Wed Feb 10 06:49:10 2010 From: sudheer.kay at gmail.com (sudhir prasad) Date: Wed, 10 Feb 2010 11:19:10 +0530 Subject: [Tutor] how to clear contents of a file Message-ID: hi, how to clear contents of a file with out actually deleting it, basically wat im trying to do is copy a source file into a common file ,run the common file,after that i need to copy another source file into the common file,i ant to clear the contents of the common file before copying contents into it.how does f.truncate() helps here thanks, sudheer -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Wed Feb 10 07:43:08 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 10 Feb 2010 08:43:08 +0200 Subject: [Tutor] how to clear contents of a file In-Reply-To: References: Message-ID: <4B72557C.7050006@compuscan.co.za> sudhir prasad wrote: > hi, > how to clear contents of a file with out actually deleting it, > basically wat im trying to do is copy a source file into a common > file ,run the common file,after that i need to copy another source > file into the common file,i ant to clear the contents of the common > file before copying contents into it.how does f.truncate() helps here > > > thanks, > sudheer > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > You can just open the file again in write mode which will truncate it for you. So, f = open(filename, 'w') will clear the contents of your filename (don't forget to close the file when you're done if you do this though). -- Kind Regards, Christian Witts From alan.gauld at btinternet.com Wed Feb 10 09:50:26 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Feb 2010 08:50:26 -0000 Subject: [Tutor] how to clear contents of a file References: Message-ID: "sudhir prasad" wrote > how to clear contents of a file with out actually deleting it, reopening it for write will, clear the contents. However.... > basically wat im trying to do is copy a source file into a common file > ,run > the common file,after that i need to copy another source file into the > common file,i ant to clear the contents of the common file before > copying This is such a bizarre thing to do that I have to ask why you are doing it? There are so many ways to execute a piece of source code from within a python program why on earth are you creating a new file to do so? There may be a valid reason but I can't think of one. If you describe the wider problem we may be able to offer an alternative solution that does not require you to copy the code at all. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From nikunjbadjatya at gmail.com Wed Feb 10 12:47:42 2010 From: nikunjbadjatya at gmail.com (nikunj badjatya) Date: Wed, 10 Feb 2010 17:17:42 +0530 Subject: [Tutor] "Error :Attempt to overwrite cell" while using xlwt to create excel sheets Message-ID: Hi, I am using xlwt 0.7.2 and Python 2.6. I come across a situation wherein one of the "rows" of the excel sheet created was being overwritten. And it was flagging the following error. File "/usr/local/lib/python2.6/site-packages/xlwt/Row.py", line 150, in insert_cell raise Exception(msg) Exception: Attempt to overwrite cell *Action Taken:* I commented out the "raise Exception" statement in Row.py library module. Here's the (line no. 150 ) of Row.py which i have edited: def insert_cell(self, col_index, cell_obj): if col_index in self.__cells: if not self.__parent._cell_overwrite_ok: msg = "Attempt to overwrite cell: sheetname=%r rowx=%d colx=%d" \ % (self.__parent.name, self.__idx, col_index) *#raise Exception(msg) #########*commented to avoid error. * prev_cell_obj = self.__cells[col_index] sst_idx = getattr(prev_cell_obj, 'sst_idx', None) if sst_idx is not None: self.__parent_wb.del_str(sst_idx) self.__cells[col_index] = cell_obj The excel sheet creation code now works fine. *My question is, Instead of manually goin to /usr/lib/.../row.py and commenting out the line, Can this be done through few lines of code in my program itself. ??* As in if I use my program on different system, then again I have to comment out that line in row.py..!! Any suggestions?? Thanks, Nikunj Bangalore, India -------------- next part -------------- An HTML attachment was scrubbed... URL: From simbobo at cooptel.net Wed Feb 10 12:26:25 2010 From: simbobo at cooptel.net (Owain Clarke) Date: Wed, 10 Feb 2010 11:26:25 +0000 Subject: [Tutor] string to list In-Reply-To: References: Message-ID: <4B7297E1.9060207@cooptel.net> Please excuse the obviousness of my question (if it is), but I have searched the documentation for how to generate a list e.g. [(1,2), (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point me in the right direction. Many thanks Owain Clarke From denis.spir at free.fr Wed Feb 10 13:10:55 2010 From: denis.spir at free.fr (spir) Date: Wed, 10 Feb 2010 13:10:55 +0100 Subject: [Tutor] string to list In-Reply-To: <4B7297E1.9060207@cooptel.net> References: <4B7297E1.9060207@cooptel.net> Message-ID: <20100210131055.4080df19@o> On Wed, 10 Feb 2010 11:26:25 +0000 Owain Clarke wrote: > Please excuse the obviousness of my question (if it is), but I have > searched the documentation for how to generate a list e.g. [(1,2), > (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point > me in the right direction. Use eval. Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print eval("[(1,2), (3,4)]") [(1, 2), (3, 4)] But -1- This need problem shows a design issue, unless you try this only for exploring python. -2- One should avoid doing this and using eval() in other circumstances because of security issues: if the code-string comes from external source (data file, network...), there is no way to ensure what it actually does. In a general case, one should _parse_ the text (which probably would not be a python literal, anyway) to _construct_ resulting python data. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From cwitts at compuscan.co.za Wed Feb 10 13:19:00 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 10 Feb 2010 14:19:00 +0200 Subject: [Tutor] string to list In-Reply-To: <4B7297E1.9060207@cooptel.net> References: <4B7297E1.9060207@cooptel.net> Message-ID: <4B72A434.1080402@compuscan.co.za> Owain Clarke wrote: > Please excuse the obviousness of my question (if it is), but I have > searched the documentation for how to generate a list e.g. [(1,2), > (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point > me in the right direction. > > Many thanks > > Owain Clarke > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > new_list = eval("[(1,2), (3,4)]") But only ever do that if you know your incoming data is clean and secure, and even then I would be really careful with its usage. If I remember correctly there was a recipe for safe parsing on http://code.activestate.com/ but I don't seem to have the link at hand. -- Kind Regards, Christian Witts From ljmamoreira at gmail.com Wed Feb 10 13:12:58 2010 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Wed, 10 Feb 2010 12:12:58 +0000 Subject: [Tutor] string to list In-Reply-To: <4B7297E1.9060207@cooptel.net> References: <4B7297E1.9060207@cooptel.net> Message-ID: <201002101212.58913.ljmamoreira@gmail.com> On Wednesday 10 February 2010 11:26:25 am Owain Clarke wrote: > Please excuse the obviousness of my question (if it is), but I have > searched the documentation for how to generate a list e.g. [(1,2), > (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point > me in the right direction. > > Many thanks > > Owain Clarke > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi One possibility is to use the eval function. Look at this snippet from an idle session: >>> s="[(1,2),(3,4)]" >>> lst=eval(s) >>> lst [(1, 2), (3, 4)] >>> lst[0] (1, 2) >>> Hope this helped Jose Amoreira From stefan_ml at behnel.de Wed Feb 10 13:32:15 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 10 Feb 2010 13:32:15 +0100 Subject: [Tutor] string to list In-Reply-To: <4B7297E1.9060207@cooptel.net> References: <4B7297E1.9060207@cooptel.net> Message-ID: Owain Clarke, 10.02.2010 12:26: > Please excuse the obviousness of my question (if it is), but I have > searched the documentation for how to generate a list e.g. [(1,2), > (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point > me in the right direction. You may want to add a little bit about your use case. Is that really the input you have to deal with? Where does it come from? Can you control the format? What do you want to do with the list you extract from the string? All of that may have an impact on the right solution. Stefan From simbobo at cooptel.net Wed Feb 10 13:34:02 2010 From: simbobo at cooptel.net (Owain Clarke) Date: Wed, 10 Feb 2010 12:34:02 +0000 Subject: [Tutor] string to list In-Reply-To: <4B7297E1.9060207@cooptel.net> References: <4B7297E1.9060207@cooptel.net> Message-ID: <4B72A7BA.30306@cooptel.net> I have solved it myself - must search more before posting! If anyone at my kind of level is interested:- >>> mystring = "[(1,2), (3,4)]" >>> mylist = eval(mystring) >>> mylist [(1,2), (3,4)] >>> type(mylist) Thanks Owain Clarke wrote: > Please excuse the obviousness of my question (if it is), but I have > searched the documentation for how to generate a list e.g. [(1,2), > (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point > me in the right direction. > > Many thanks > > Owain Clarke > From kent37 at tds.net Wed Feb 10 13:34:26 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Feb 2010 07:34:26 -0500 Subject: [Tutor] NameError: global name 'celsius' is not defined (actually, solved) In-Reply-To: <4B722135.5030006@gmx.net> References: <4B722135.5030006@gmx.net> Message-ID: <1c2a2c591002100434r290c21ddva10964bef17adab8@mail.gmail.com> On Tue, Feb 9, 2010 at 10:00 PM, David wrote: > Hi guys, > > I just wrote this message, but after restarting ipython all worked fine. > How is it to be explained that I first had a namespace error which, after a > restart (and not merely a new "run Sande_celsius-main.py"), went away? I > mean, surely the namespace should not be impacted by ipython at all!? Python caches modules (in sys.modules). When you run inside of ipython, you are not restarting the interpreter so you don't get a clean module cache. This has implications for multi-module development. Suppose you have # module.py animls = ['cat', 'dog' ] # note the misspelling # main.py import module print module.animals If you "run main.py" you will get a NameError and the erroneous module.py will be cached in the module cache. If you correct module.py and again "run main.py" you will get the same error because module.py has not been reloaded. A couple of work-arounds- - run main.py from a command line or some other way that gives it a fresh interpreter - from ipython command line, or in main.py import module reload(module) Kent From kent37 at tds.net Wed Feb 10 13:43:25 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Feb 2010 07:43:25 -0500 Subject: [Tutor] "Error :Attempt to overwrite cell" while using xlwt to create excel sheets In-Reply-To: References: Message-ID: <1c2a2c591002100443i3fe03e45r2b57c69d83f5c037@mail.gmail.com> On Wed, Feb 10, 2010 at 6:47 AM, nikunj badjatya wrote: > I commented out the "raise Exception" statement in Row.py library > module. > Here's the (line no. 150 ) of Row.py which i have edited: > > ? def insert_cell(self, col_index, cell_obj): > ? ? ? ? if col_index in self.__cells: > ? ? ? ? ? ? if not self.__parent._cell_overwrite_ok: > ? ? ? ? ? ? ? ? msg = "Attempt to overwrite cell: sheetname=%r rowx=%d > colx=%d" \ > ? ? ? ? ? ? ? ? ? ? % (self.__parent.name, self.__idx, col_index) > ? ? ? ? ? ? ? ? #raise Exception(msg) > #########*commented to avoid error. > ? ? ? ? ? ? prev_cell_obj = self.__cells[col_index] > ? ? ? ? ? ? sst_idx = getattr(prev_cell_obj, 'sst_idx', None) > ? ? ? ? ? ? if sst_idx is not None: > ? ? ? ? ? ? ? ? self.__parent_wb.del_str(sst_idx) > ? ? ? ? self.__cells[col_index] = cell_obj > > The excel sheet creation code now works fine. > > My question is, Instead of manually goin to /usr/lib/.../row.py and > commenting out the line, Can this be done through few lines of code in > my program itself. ?? Looking at the code above, you can see that the exception is raised only if self.__parent._cell_overwrite_ok is False. So there is an option to allow overwriting. >From the error message it appears that self.__parent is a Worksheet. Looking at the source code for Worksheet.py, the __init__() method does have an optional cell_overwrite_ok= parameter. This parameter is also available in Workbook.add_sheet(). So if you pass cell_overwrite=True to add_sheet() you should be OK. Kent From stefan_ml at behnel.de Wed Feb 10 13:44:10 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 10 Feb 2010 13:44:10 +0100 Subject: [Tutor] string to list In-Reply-To: <4B72A7BA.30306@cooptel.net> References: <4B7297E1.9060207@cooptel.net> <4B72A7BA.30306@cooptel.net> Message-ID: Owain Clarke, 10.02.2010 13:34: > I have solved it myself - must search more before posting! > > If anyone at my kind of level is interested:- > >>>> mystring = "[(1,2), (3,4)]" >>>> mylist = eval(mystring) >>>> mylist > [(1,2), (3,4)] >>>> type(mylist) > As others have pointed out, this may or may not solve your problem, and it may introduce other problems, such as security vulnerabilities. Stefan From kent37 at tds.net Wed Feb 10 13:51:48 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Feb 2010 07:51:48 -0500 Subject: [Tutor] string to list In-Reply-To: <4B7297E1.9060207@cooptel.net> References: <4B7297E1.9060207@cooptel.net> Message-ID: <1c2a2c591002100451s6282bf83y36e1774a84d26e9@mail.gmail.com> On Wed, Feb 10, 2010 at 6:26 AM, Owain Clarke wrote: > Please excuse the obviousness of my question (if it is), but I have searched > the documentation for how to generate a list e.g. [(1,2), (3,4)] from a > string "[(1,2), (3,4)]". I wonder if someone could point me in the right > direction. Python 2.6 and later contain the function ast.literal_eval() which is the safe way to do this. http://docs.python.org/library/ast.html#ast.literal_eval In [15]: import ast In [16]: ast.literal_eval("[(1,2), (3,4)]") Out[16]: [(1, 2), (3, 4)] Kent From simbobo at cooptel.net Wed Feb 10 14:32:52 2010 From: simbobo at cooptel.net (Owain Clarke) Date: Wed, 10 Feb 2010 13:32:52 +0000 Subject: [Tutor] string to list In-Reply-To: References: Message-ID: <4B72B584.9020802@cooptel.net> > Owain Clarke wrote: > >> Please excuse the obviousness of my question (if it is), but I have >> searched the documentation for how to generate a list e.g. [(1,2), >> (3,4)] from a string "[(1,2), (3,4)]". I wonder if someone could point >> me in the right direction. >> >> Many thanks >> >> Owain Clarke >> >> Thanks to all who responded between my first and second post. > You may want to add a little bit about your use case. Is that really the input you > have to deal with? Where does it come from? Can you control the format? What do > you want to do with the list you extract from the string? > All of that may have an impact on the right solution. > Stefan My son was doing a statistics project in which he had to sort some data by either one of two sets of numbers, representing armspan and height of a group of children - a boring and painstaking job. I came across this piece of code:- li=[[2,6],[1,3],[5,4]] # would also work with li=[(2,6),(1,3),(5,4)] li.sort(key=lambda x:x[1] ) print li It occurred to me that I could adapt this so that he could input his data at the command line and then sort by x:x[0] or x:x[1]. And I have not discovered a way of inputting a list, only strings or various number types. I realise that I am a bit out of my depth here, but Python just seems like so much fun!! Owain From davea at ieee.org Wed Feb 10 15:00:29 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 10 Feb 2010 09:00:29 -0500 Subject: [Tutor] NameError: global name 'celsius' is not defined (actually, solved) In-Reply-To: <4B723EE3.7060501@gmx.net> References: <4B722135.5030006@gmx.net> <78b3a9581002091913u27dc639ft71a11af46dddb595@mail.gmail.com> <4B723EE3.7060501@gmx.net> Message-ID: <4B72BBFD.9080800@ieee.org> David wrote: >
Hello > Wesley, > > thanks for your reply. I was surprised about the limited information > too. Sadly (?), I can't reproduce the error any more... > > David > > > > On 10/02/10 11:13, wesley chun wrote: >>> I just wrote this message, but after restarting ipython all worked >>> fine. >>> How is it to be explained that I first had a namespace error which, >>> after a >>> restart (and not merely a new "run Sande_celsius-main.py"), went >>> away? I >>> mean, surely the namespace should not be impacted by ipython at all!? >>> : >>> # file: Sande_celsius-main.py >>> from Sande_my_module import c_to_f >>> celsius = float(raw_input("Enter a temperature in Celsius: ")) >>> fahrenheit = c_to_f(celsius) >>> print "That's ", fahrenheit, " degrees Fahrenheit" >>> >>> # this is the file Sande_my_module.py >>> # we're going to use it in another program >>> def c_to_f(celsius): >>> fahrenheit = celsius * 9.0 / 5 + 32 >>> return fahrenheit >>> >>> When I run Sande_celsius-main.py, I get the following error: >>> >>> NameError: global name 'celsius' is not defined >>> WARNING: Failure executing file: >> >> >> Python interpreters including the standard one or IPython should tell >> you a lot more than that. how are you executing this code? would it be >> possible to do so from the command-line? you should get a more verbose >> error message that you can post here. >> >> best regards, >> -- wesley > Your response to Wesley should have been here, instead of at the top. Please don't top-post on this forum. I don't use iPython, so this is just a guess. But perhaps the problem is that once you've imported the code, then change it, it's trying to run the old code instead of the changed code. Try an experiment in your environment. Deliberately add an error to Sande_celsius-main.py, and run it. Then correct it, and run it again, to see if it notices the fix. The changes I'd try in this experiment are to first change the name on the celsius= line to celsius2= and after running and getting the error, change the following line to call celsius2(). If it gets an error, notice what symbol it complains about. HTH DaveA From steve at pearwood.info Wed Feb 10 15:13:39 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 11 Feb 2010 01:13:39 +1100 Subject: [Tutor] string to list In-Reply-To: <4B72B584.9020802@cooptel.net> References: <4B72B584.9020802@cooptel.net> Message-ID: <201002110113.40241.steve@pearwood.info> On Thu, 11 Feb 2010 12:32:52 am Owain Clarke wrote: > My son was doing a statistics project in which he had to sort some > data by either one of two sets of numbers, representing armspan and > height of a group of children - a boring and painstaking job. I came > across this piece of code:- > > li=[[2,6],[1,3],[5,4]] # would also work with li=[(2,6),(1,3),(5,4)] > li.sort(key=lambda x:x[1] ) > print li > > It occurred to me that I could adapt this so that he could input his > data at the command line and then sort by x:x[0] or x:x[1]. And I > have not discovered a way of inputting a list, only strings or > various number types. Which command line do you mean? If you are talking about the Python interactive interpreter, then you can input either lists or strings: >>> li = [1, 2, 3] # a list >>> li = "[1, 2, 3]" # a string If you mean the external shell (say, "bash" under Linux or the DOS command line in Windows, or similar) then you can only input strings -- everything is a string in such shells. There are two ways to convert such strings to lists: the easy, unsafe way; or the slightly more difficult but safer way. Think of it like The Force, where the Dark Side is simpler and more attractive but ultimately more dangerous :) First, the easy way. If you absolutely trust the source of the data, then you can use the eval function: >>> s = "[1, 2, 3]" # quote marks make it a string >>> li = eval(s) The interpreter will read the string s as a Python expression, and do whatever it says. In this example, it says "make a list with the numbers 1, 2 and 3 in it". But it could say *anything*, like "erase the hard disk", and Python would dutifully do what it is told. This is why eval is easy and fast but dangerous, and you must absolutely trust the source of the string. Alternatively, you could do this: >>> s = "1 2 3 4" # numbers separated by spaces >>> li = s.split() # li now contains the strings "1", "2" etc. >>> li = map(int, li) # convert the strings to actual ints >>> print li [1, 2, 3, 4] Naturally the string s would come from the shell, otherwise there is no point! If you are typing the data directly into the Python interpreter, you would enter it directly as a list and not a string. Hope this helps, -- Steven D'Aprano From kent37 at tds.net Wed Feb 10 15:19:06 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Feb 2010 09:19:06 -0500 Subject: [Tutor] string to list In-Reply-To: <4B72B584.9020802@cooptel.net> References: <4B72B584.9020802@cooptel.net> Message-ID: <1c2a2c591002100619p5beef182wa429421c7742bc55@mail.gmail.com> On Wed, Feb 10, 2010 at 8:32 AM, Owain Clarke wrote: > My son was doing a statistics project in which he had to sort some data by > either one of two sets of numbers, representing armspan and height of a > group of children - a boring and painstaking job. ?I came across this piece > of code:- > > li=[[2,6],[1,3],[5,4]] ?# would also work with li=[(2,6),(1,3),(5,4)] > li.sort(key=lambda x:x[1] ) > print li > > It occurred to me that I could adapt this so that he could input his data at > the command line and then sort by x:x[0] or x:x[1]. ?And I have not > discovered a way of inputting a list, only strings or various number types. I would do this by reading the data from a file, that way the data entry is simpler, easier to check and correct, easy to reuse, etc.. Create a file that looks like this: 2 6 1 3 5 4 Read it with code like f = open('data.txt') data = [] for line in f: line_data = [ int(x) for x in line.split() ] data.append(line_data) or if you like map() and one-line list comprehensions: data = [ map(int, line.split()) for line in open('data.txt') ] Then you can sort & process data to your hearts content. You could also just hard-code the data into your program as a literal list. Kent From eike.welk at gmx.net Wed Feb 10 15:24:46 2010 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 10 Feb 2010 15:24:46 +0100 Subject: [Tutor] string to list In-Reply-To: <4B72B584.9020802@cooptel.net> References: <4B72B584.9020802@cooptel.net> Message-ID: <201002101524.46949.eike.welk@gmx.net> On Wednesday February 10 2010 14:32:52 Owain Clarke wrote: > My son was doing a statistics project in which he had to sort some data by > either one of two sets of numbers, representing armspan and height of a > group of children - a boring and painstaking job. I came across this > piece of code:- > > li=[[2,6],[1,3],[5,4]] # would also work with li=[(2,6),(1,3),(5,4)] > li.sort(key=lambda x:x[1] ) > print li > > It occurred to me that I could adapt this so that he could input his data > at the command line and then sort by x:x[0] or x:x[1]. And I have not > discovered a way of inputting a list, only strings or various number > types. I would let him enter the data into the program text directly, or parse a text file with a simple format. Something like: in_data = [ #arm span, height [2 , 6 ], [1 , 3 ], [5 , 4 ], [ , ], [ , ], [ , ], ] This way the computation can be repeated when there were errors int the data. Otherwise one error might spoil all the work he did while typing in the data. Designing a simple text representation of the data and interpreting it with a computer program, is much more easy that writing good user interfaces. For the same reason Unix, a concept from the late 1960s, is still doing relatively well. Eike. From stefan_ml at behnel.de Wed Feb 10 15:28:28 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 10 Feb 2010 15:28:28 +0100 Subject: [Tutor] string to list In-Reply-To: <4B72B584.9020802@cooptel.net> References: <4B72B584.9020802@cooptel.net> Message-ID: Owain Clarke, 10.02.2010 14:32: >> You may want to add a little bit about your use case. Is that really >> the input you >> have to deal with? Where does it come from? Can you control the >> format? What do >> you want to do with the list you extract from the string? >> >> All of that may have an impact on the right solution. > > My son was doing a statistics project in which he had to sort some data > by either one of two sets of numbers, representing armspan and height of > a group of children - a boring and painstaking job. Thanks for the explanation, that certainly clears it up. > I came across this piece of code:- > > li=[[2,6],[1,3],[5,4]] # would also work with li=[(2,6),(1,3),(5,4)] > li.sort(key=lambda x:x[1] ) > print li > > It occurred to me that I could adapt this so that he could input his > data at the command line and then sort by x:x[0] or x:x[1]. And I have > not discovered a way of inputting a list, only strings or various number > types. I would rather put them into a file one-per-line, e.g. 2,6 1,3 5,4 and then read that in as input. That way, you can reuse the input multiple times, even if you discover that your program has a bug or needs a new feature, or whatever. Having to retype the data will quickly get really cumbersome. Something like this should do the job: children_properties = [] with file("thefile.txt") as f: for line in f: if line.count(',') != 1: # broken line? print("Ignoring malformed line '%s'" % line) continue armspan, height = map(int, line.split(',')) children_properties.append( (armspan, height) ) Then sort and print as you see fit. > I realise that I am a bit out of my depth here, but Python just seems > like so much fun!! The beauty of Python for people who are just starting programming is that so many things are so surprisingly simply to do that you really quickly get to think about rather tricky problems, instead of being blocked by syntax. Keep up the pace! :) Stefan From simbobo at cooptel.net Wed Feb 10 15:51:34 2010 From: simbobo at cooptel.net (Owain Clarke) Date: Wed, 10 Feb 2010 14:51:34 +0000 Subject: [Tutor] string to list In-Reply-To: References: Message-ID: <4B72C7F6.1010604@cooptel.net> An HTML attachment was scrubbed... URL: From grigor.kolev at gmail.com Wed Feb 10 20:30:52 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Wed, 10 Feb 2010 21:30:52 +0200 Subject: [Tutor] html and python Message-ID: <1265830252.8722.1.camel@dedal-laptop> Hi. I want to make a list of E-mail, photos and some additional data. But I want this list to be displayed in one site. How can I send data from a list of site page. Which module should I use -- Grigor Kolev From vinces1979 at gmail.com Wed Feb 10 20:33:07 2010 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 10 Feb 2010 13:33:07 -0600 Subject: [Tutor] html and python In-Reply-To: <1265830252.8722.1.camel@dedal-laptop> References: <1265830252.8722.1.camel@dedal-laptop> Message-ID: <1e53c511002101133ne417527x4ee6e590a7a451de@mail.gmail.com> On Wed, Feb 10, 2010 at 1:30 PM, Grigor Kolev wrote: > Hi. > I want to make a list of E-mail, photos and some additional data. > But I want this list to be displayed in one site. > How can I send data from a list of site page. Which module should I use > -- > Grigor Kolev > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > do you have any code currently? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Feb 10 20:39:50 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Feb 2010 14:39:50 -0500 Subject: [Tutor] html and python In-Reply-To: <1265830252.8722.1.camel@dedal-laptop> References: <1265830252.8722.1.camel@dedal-laptop> Message-ID: <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> On Wed, Feb 10, 2010 at 2:30 PM, Grigor Kolev wrote: > Hi. > I want to make a list of E-mail, photos and some additional data. > But I want this list to be displayed in one site. > How can I send data from a list of site page. Which module should I use I don't understand "send data from a list of site page". Are you making a web site? Dynamic or static? Are you asking how to build an HTML page in Python? Kent From dananzoff at gmail.com Wed Feb 10 20:40:40 2010 From: dananzoff at gmail.com (Harya Dananjaya) Date: Thu, 11 Feb 2010 04:40:40 +0900 Subject: [Tutor] Compile py to exe in ubuntu Message-ID: <4B730BB8.1030004@gmail.com> Can I compile my python source to exe in ubuntu? if I can do it, which compiler can do it? Thanks you, Harya Dananjaya From vinces1979 at gmail.com Wed Feb 10 20:41:43 2010 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 10 Feb 2010 13:41:43 -0600 Subject: [Tutor] html and python In-Reply-To: <1265830252.8722.1.camel@dedal-laptop> References: <1265830252.8722.1.camel@dedal-laptop> Message-ID: <1e53c511002101141ocab158dn6e6e1a52372382d7@mail.gmail.com> On Wed, Feb 10, 2010 at 1:30 PM, Grigor Kolev wrote: > Hi. > I want to make a list of E-mail, photos and some additional data. > But I want this list to be displayed in one site. > How can I send data from a list of site page. Which module should I use > -- > Grigor Kolev > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Your best bet is show us some code .. then we can help. Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From grigor.kolev at gmail.com Wed Feb 10 20:49:25 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Wed, 10 Feb 2010 21:49:25 +0200 Subject: [Tutor] html and python In-Reply-To: <1e53c511002101133ne417527x4ee6e590a7a451de@mail.gmail.com> References: <1265830252.8722.1.camel@dedal-laptop> <1e53c511002101133ne417527x4ee6e590a7a451de@mail.gmail.com> Message-ID: <1265831365.8722.13.camel@dedal-laptop> ? 13:33 -0600 ?? 10.02.2010 (??), vince spicer ??????: > On Wed, Feb 10, 2010 at 1:30 PM, Grigor Kolev > wrote: > Hi. > I want to make a list of E-mail, photos and some additional > data. > But I want this list to be displayed in one site. > How can I send data from a list of site page. Which module > should I use > -- > Grigor Kolev > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > do you have any code currently? No have. Data is something like this. [{'grigor.kolev at gmail.com' : {name: 'Grigor', age: 26, photo: r'/home/user/photoname'}, {Next mail}] But I do not know how to send data in html. I want to make loop who pars the list and show data in the site. -- Grigor Kolev From vinces1979 at gmail.com Wed Feb 10 20:49:53 2010 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 10 Feb 2010 13:49:53 -0600 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <4B730BB8.1030004@gmail.com> References: <4B730BB8.1030004@gmail.com> Message-ID: <1e53c511002101149y4197a86apf3a41c305bccd1be@mail.gmail.com> On Wed, Feb 10, 2010 at 1:40 PM, Harya Dananjaya wrote: > Can I compile my python source to exe in ubuntu? > if I can do it, which compiler can do it? > > Thanks you, > > Harya Dananjaya > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > 1. Ubuntu and linux in general don't use exe per say 2. Python can be compiled but not usually in the way you are thinking 3. you might check out http://pypi.python.org/pypi/bbfreeze/ Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Feb 10 20:47:50 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 10 Feb 2010 13:47:50 -0600 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <4B730BB8.1030004@gmail.com> References: <4B730BB8.1030004@gmail.com> Message-ID: <333efb451002101147t648f1fcfk2c62501014a00dba@mail.gmail.com> On Wed, Feb 10, 2010 at 1:40 PM, Harya Dananjaya wrote: > Can I compile my python source to exe in ubuntu? > if I can do it, which compiler can do it? > > Thanks you, > > Harya Dananjaya > Do you mean a windows executable? Not really. Why do you want an .exe anyway? Python code is (usually) cross-platform. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From grigor.kolev at gmail.com Wed Feb 10 20:56:59 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Wed, 10 Feb 2010 21:56:59 +0200 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <4B730BB8.1030004@gmail.com> References: <4B730BB8.1030004@gmail.com> Message-ID: <1265831819.8722.22.camel@dedal-laptop> ? 04:40 +0900 ?? 11.02.2010 (??), Harya Dananjaya ??????: > Can I compile my python source to exe in ubuntu? > if I can do it, which compiler can do it? > > Thanks you, > > Harya Dananjaya > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Use cx_freeze but you cannot make exe in ubuntu must use Windows -- Grigor Kolev From kent37 at tds.net Wed Feb 10 21:02:41 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Feb 2010 15:02:41 -0500 Subject: [Tutor] html and python In-Reply-To: <1265831670.8722.18.camel@dedal-laptop> References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> <1265831670.8722.18.camel@dedal-laptop> Message-ID: <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> On Wed, Feb 10, 2010 at 2:54 PM, Grigor Kolev wrote: > ? 14:39 -0500 ?? 10.02.2010 (??), Kent Johnson ??????: >> On Wed, Feb 10, 2010 at 2:30 PM, Grigor Kolev wrote: >> > Hi. >> > I want to make a list of E-mail, photos and some additional data. >> > But I want this list to be displayed in one site. >> > How can I send data from a list of site page. Which module should I use >> >> I don't understand "send data from a list of site page". Are you >> making a web site? Dynamic or static? Are you asking how to build an >> HTML page in Python? >> >> Kent > Yes how can I build html file with Python. > And how can i make a script who start every day and refresh the html pages HTML is just text. Do you know what you want your HTML to look like? In the simplest case, you can write the HTML directly from Python to a file. For more complicated files you may want to use some kind of templating or HTML-generation library. You can schedule a script to run every day using cron (*nix) or Scheduled Tasks (Windows). What is your level of experience? You will get better answers if you give us more information in your questions. Don't make us work for every bit of your problem. Kent From grigor.kolev at gmail.com Wed Feb 10 21:26:47 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Wed, 10 Feb 2010 22:26:47 +0200 Subject: [Tutor] html and python In-Reply-To: <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> <1265831670.8722.18.camel@dedal-laptop> <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> Message-ID: <1265833607.8722.24.camel@dedal-laptop> ? 15:02 -0500 ?? 10.02.2010 (??), Kent Johnson ??????: > On Wed, Feb 10, 2010 at 2:54 PM, Grigor Kolev wrote: > > ? 14:39 -0500 ?? 10.02.2010 (??), Kent Johnson ??????: > >> On Wed, Feb 10, 2010 at 2:30 PM, Grigor Kolev wrote: > >> > Hi. > >> > I want to make a list of E-mail, photos and some additional data. > >> > But I want this list to be displayed in one site. > >> > How can I send data from a list of site page. Which module should I use > >> > >> I don't understand "send data from a list of site page". Are you > >> making a web site? Dynamic or static? Are you asking how to build an > >> HTML page in Python? > >> > >> Kent > > Yes how can I build html file with Python. > > And how can i make a script who start every day and refresh the html pages > > HTML is just text. Do you know what you want your HTML to look like? > In the simplest case, you can write the HTML directly from Python to a > file. For more complicated files you may want to use some kind of > templating or HTML-generation library. > > You can schedule a script to run every day using cron (*nix) or > Scheduled Tasks (Windows). > > What is your level of experience? > > You will get better answers if you give us more information in your > questions. Don't make us work for every bit of your problem. > > Kent I apologize to my question is incorrectly set. We have a mail list and we want to do in site a list of all participants with their photos and names. List with people is saved in the txt file. I want to open this file. Take all mail address and to do formating the data. Then with loop to do parsing all data and to do send in the html. I can open and save as plain text document. File = file(r'/home/user/test.html', 'w') But if I refresh the data every day it by a slowly. -- Grigor Kolev From invincible_patriot at hotmail.com Wed Feb 10 22:27:32 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Wed, 10 Feb 2010 21:27:32 +0000 Subject: [Tutor] need idea In-Reply-To: <1265833607.8722.24.camel@dedal-laptop> References: <1265830252.8722.1.camel@dedal-laptop>, <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com>, <1265831670.8722.18.camel@dedal-laptop>, <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com>, <1265833607.8722.24.camel@dedal-laptop> Message-ID: hi i want to compare a string with a dictionary or u can say that i want to take user input A STRING, and want to compare each character of that string with the KEYS in the dictionary, and then i wana print the values for the characters that are present in that strinng that we got as the input and were present in the dictionary as well can you please give me some idea how to do that what i hav done is that 1) I have made a dictionary with the keys and the values 2) I have taken the input from the user and hav saved it into a variable not i wana compare string that was given to us and replace them with the values given in the dictionary please let me know _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. http://clk.atdmt.com/GBL/go/201469226/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From invincible_patriot at hotmail.com Wed Feb 10 22:29:26 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Wed, 10 Feb 2010 21:29:26 +0000 Subject: [Tutor] Needleman-Wunsch algorithm In-Reply-To: <1265833607.8722.24.camel@dedal-laptop> References: <1265830252.8722.1.camel@dedal-laptop>, <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com>, <1265831670.8722.18.camel@dedal-laptop>, <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com>, <1265833607.8722.24.camel@dedal-laptop> Message-ID: hi i hope every one knows about the needleman wunsch algo i am trying to do the same task, can some one give me an outline as to how should i start after taking 2 input strings from the user.. _________________________________________________________________ Hotmail: Powerful Free email with security by Microsoft. http://clk.atdmt.com/GBL/go/201469230/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Feb 10 22:51:16 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 10 Feb 2010 15:51:16 -0600 Subject: [Tutor] Needleman-Wunsch algorithm In-Reply-To: References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> <1265831670.8722.18.camel@dedal-laptop> <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> <1265833607.8722.24.camel@dedal-laptop> Message-ID: <333efb451002101351x56326595p811e4ee13e7d6346@mail.gmail.com> On Wed, Feb 10, 2010 at 3:29 PM, invincible patriot < invincible_patriot at hotmail.com> wrote: > hi > i hope every one knows about the needleman wunsch algo > Never heard of it > i am trying to do the same task, > can some one give me an outline as to how should i start after taking 2 > input strings from the user. > Where do you think you should start? Perhaps if you explain the algorithm you'll get some ideas about where to start... 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 Wed Feb 10 23:09:52 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Feb 2010 17:09:52 -0500 Subject: [Tutor] need idea In-Reply-To: References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> <1265831670.8722.18.camel@dedal-laptop> <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> <1265833607.8722.24.camel@dedal-laptop> Message-ID: <1c2a2c591002101409v447e2e7gc6394c3caf357d36@mail.gmail.com> On Wed, Feb 10, 2010 at 4:27 PM, invincible patriot wrote: > hi > i want to compare a string with a dictionary > or u can say that i want to take user input A STRING, and want to compare > each character of that string with the KEYS? in the dictionary, and then i > wana print the values for the characters that are present in that strinng > that we got as the input and were present in the dictionary as well Please give an example input, dictionary and desired output. > can you please give me some idea how to do that > > what i hav done is that > 1) I have made a dictionary with the keys and the values > 2) I have taken the input from the user and hav saved it into a variable > > not i wana compare string that was given to us and replace them with the > values given in the dictionary You probably want some combination of iteration over the input string and dict.get(). Kent From andreengels at gmail.com Wed Feb 10 23:10:38 2010 From: andreengels at gmail.com (Andre Engels) Date: Wed, 10 Feb 2010 23:10:38 +0100 Subject: [Tutor] need idea In-Reply-To: References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> <1265831670.8722.18.camel@dedal-laptop> <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> <1265833607.8722.24.camel@dedal-laptop> Message-ID: <6faf39c91002101410w4ff0169cof846d70fc801fff5@mail.gmail.com> On Wed, Feb 10, 2010 at 10:27 PM, invincible patriot wrote: > hi > i want to compare a string with a dictionary > or u can say that i want to take user input A STRING, and want to compare > each character of that string with the KEYS? in the dictionary, and then i > wana print the values for the characters that are present in that strinng > that we got as the input and were present in the dictionary as well > > can you please give me some idea how to do that > > what i hav done is that > 1) I have made a dictionary with the keys and the values > 2) I have taken the input from the user and hav saved it into a variable > > not i wana compare string that was given to us and replace them with the > values given in the dictionary It's not yet completely clear to me what you want, but the following should help you: Let str be the string, and dict the dictionary, then: [c for c in str if c in dict] will give you the characters in the string that are keys in the dictionary. -- Andr? Engels, andreengels at gmail.com From invincible_patriot at hotmail.com Thu Feb 11 00:12:05 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Wed, 10 Feb 2010 23:12:05 +0000 Subject: [Tutor] need idea In-Reply-To: <6faf39c91002101410w4ff0169cof846d70fc801fff5@mail.gmail.com> References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com>, <1265831670.8722.18.camel@dedal-laptop> <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com>, <1265833607.8722.24.camel@dedal-laptop> , <6faf39c91002101410w4ff0169cof846d70fc801fff5@mail.gmail.com> Message-ID: thanks let me clear you that what i am trying to do suppose we hav a input string and a dict our_dict={'a':'u', 't':'a', 'c':'g', 'g':'c'} input_string='atcg' now what i wana do is that where ever we are having 'a' i wana replace it with 'u', 't' with 'a' and so on i tried using input_string.replace('a', 'u') but it is replacing only one character i wana replace these 4 characters according to the dictionary i hope it is now clear kindly let me know how to proceed now > From: andreengels at gmail.com > Date: Wed, 10 Feb 2010 23:10:38 +0100 > Subject: Re: [Tutor] need idea > To: invincible_patriot at hotmail.com > CC: tutor at python.org > > On Wed, Feb 10, 2010 at 10:27 PM, invincible patriot > wrote: > > hi > > i want to compare a string with a dictionary > > or u can say that i want to take user input A STRING, and want to compare > > each character of that string with the KEYS in the dictionary, and then i > > wana print the values for the characters that are present in that strinng > > that we got as the input and were present in the dictionary as well > > > > can you please give me some idea how to do that > > > > what i hav done is that > > 1) I have made a dictionary with the keys and the values > > 2) I have taken the input from the user and hav saved it into a variable > > > > not i wana compare string that was given to us and replace them with the > > values given in the dictionary > > It's not yet completely clear to me what you want, but the following > should help you: > > Let str be the string, and dict the dictionary, then: > > [c for c in str if c in dict] > > will give you the characters in the string that are keys in the dictionary. > > > > > -- > Andr? Engels, andreengels at gmail.com _________________________________________________________________ Hotmail: Powerful Free email with security by Microsoft. http://clk.atdmt.com/GBL/go/201469230/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Feb 11 00:24:10 2010 From: andreengels at gmail.com (Andre Engels) Date: Thu, 11 Feb 2010 00:24:10 +0100 Subject: [Tutor] need idea In-Reply-To: References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> <1265831670.8722.18.camel@dedal-laptop> <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> <1265833607.8722.24.camel@dedal-laptop> <6faf39c91002101410w4ff0169cof846d70fc801fff5@mail.gmail.com> Message-ID: <6faf39c91002101524vf088331if8f5be3a3cd87304@mail.gmail.com> On Thu, Feb 11, 2010 at 12:12 AM, invincible patriot wrote: > thanks > let me clear you that what i am trying to do > suppose we hav a input string and a dict > our_dict={'a':'u', 't':'a', 'c':'g', 'g':'c'} > input_string='atcg' > > > now what i wana do is that where ever we are having 'a' i wana replace it > with 'u', 't' with 'a' and so on > i tried using input_string.replace('a', 'u') > but it is replacing only one character > i wana replace these 4 characters according to the dictionary > > i hope it is now clear > > kindly let me know how to proceed now See http://www.tutorialspoint.com/python/string_translate.htm -- Andr? Engels, andreengels at gmail.com From fubarninja at hotmail.com Thu Feb 11 00:43:31 2010 From: fubarninja at hotmail.com (jim serson) Date: Wed, 10 Feb 2010 18:43:31 -0500 Subject: [Tutor] running split and count + looping to check for numbers in same line Message-ID: I am getting an error when I try and run split and count I seem to get it to work with one or the other but not together. python wants a character buffer but I am not sure how to use it. I would also like to use readline to check and see if several numbers are in the same line but I think I will need to use it in a loop maybe for? So it would check for the first then check for the second if both are true add to count but if ether are false continue to next line and repeat. If anyone can help me that would be grate. Thanks look_in = "keno_back_up.txt"#raw_input ("Enter the search file to look in ") search = raw_input ("Enter your search item ").split file = open(look_in, "r").read().count(search) print "Your search came",file ,"times" Traceback (most recent call last): File "C:\Python26\keno program\get rid of 4", line 4, in file = open(look_in, "r").read().count(search) TypeError: expected a character buffer object _________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From transmogribenno at gmail.com Thu Feb 11 01:28:48 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Thu, 11 Feb 2010 09:28:48 +0900 Subject: [Tutor] html and python In-Reply-To: <1265833607.8722.24.camel@dedal-laptop> References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> <1265831670.8722.18.camel@dedal-laptop> <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> <1265833607.8722.24.camel@dedal-laptop> Message-ID: <9b00d1a91002101628v11ba3349y288dde8593be42ed@mail.gmail.com> On Thu, Feb 11, 2010 at 5:26 AM, Grigor Kolev wrote: > I apologize to my question is incorrectly set. > We have a mail list and we want to do in site a list of all participants > with their photos and names. > List with people is saved in the txt file. > I want to open this file. Take all mail address and to do formating the > data. > Then with loop to do parsing all data and to do send in the html. > I can open and save as plain text document. > File = file(r'/home/user/test.html', 'w') > But if I refresh the data every day it by a ?slowly. If you can call scripts when actions occur on the mailing list (e.g. new subscriber added, user unsubscribes, user details updated, etc), then you could write a Python script to generate static HTML at that point. It would probably be less hassle than creating a dynamic web page. So then all you have to do is loop through your records and write the resultant HTML to a file that the web server can read. HTH, benno From dwbarne at earthlink.net Thu Feb 11 01:48:31 2010 From: dwbarne at earthlink.net (dwbarne at earthlink.net) Date: Wed, 10 Feb 2010 19:48:31 -0500 (EST) Subject: [Tutor] packing up python code to transfer to another machine Message-ID: <7228665.1265849311452.JavaMail.root@elwamui-norfolk.atl.sa.earthlink.net> I have become a true Pythonaholic. My newest problem is.... I have a rather large Python code (1.5yrs + developing!) currently running on Windows machines that imports several modules, some from external libraries. It allows the user to easily access MySQL databases and plot selected columns and such. I would like to bundle my (code + libraries + modules) and transfer all to a *nix environment, rather than just transferring my code over and then having to download and install all the relevant libraries again. Is this possible? I would think so with Python but am not sure. Is there a Python package that does this? If so, what? Thanks in advance. From kent37 at tds.net Thu Feb 11 03:50:53 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 10 Feb 2010 21:50:53 -0500 Subject: [Tutor] running split and count + looping to check for numbers in same line In-Reply-To: References: Message-ID: <1c2a2c591002101850n3adebd2chf2bae4639584c6f3@mail.gmail.com> On Wed, Feb 10, 2010 at 6:43 PM, jim serson wrote: > I?am getting an error when I try and run split and count I seem to get it to > work with one or the other but not together. python wants a character buffer > but I am not sure how to use it. > > I would also like to use readline to check and see if several numbers are in > the same line but I think I will need to use it in a loop maybe for? So it > would check for the first then check for the second if both are true add to > count but if ether are false continue to next line and repeat. > > If anyone can help me that would be grate. > Thanks > > look_in = "keno_back_up.txt"#raw_input ("Enter the search file to look in ") > search = raw_input ("Enter your search item ").split Here search is actually a function because you left out the parentheses after split(). But with them, search would be a list. The argument to count() must be a string. > file = open(look_in, "r").read().count(search) > print "Your search came",file ,"times" Do you want a count per line or for the whole file? For the whole file you could do something like search_terms = raw_input ("Enter your search item ").split() # Note the final () data = open(look_in).read() count = 0 for term in search_terms: count += data.count(term) The last three lines could also be written as count = sum(data.count(term) for term in search_terms) Kent From fubarninja at hotmail.com Thu Feb 11 04:10:03 2010 From: fubarninja at hotmail.com (jim serson) Date: Wed, 10 Feb 2010 22:10:03 -0500 Subject: [Tutor] running split and count + looping to check for numbers in same line In-Reply-To: <1c2a2c591002101850n3adebd2chf2bae4639584c6f3@mail.gmail.com> References: , <1c2a2c591002101850n3adebd2chf2bae4639584c6f3@mail.gmail.com> Message-ID: Thanks for the information > Date: Wed, 10 Feb 2010 21:50:53 -0500 > Subject: Re: [Tutor] running split and count + looping to check for numbers in same line > From: kent37 at tds.net > To: fubarninja at hotmail.com > CC: tutor at python.org > > On Wed, Feb 10, 2010 at 6:43 PM, jim serson wrote: > > I am getting an error when I try and run split and count I seem to get it to > > work with one or the other but not together. python wants a character buffer > > but I am not sure how to use it. > > > > I would also like to use readline to check and see if several numbers are in > > the same line but I think I will need to use it in a loop maybe for? So it > > would check for the first then check for the second if both are true add to > > count but if ether are false continue to next line and repeat. > > > > If anyone can help me that would be grate. > > Thanks > > > > look_in = "keno_back_up.txt"#raw_input ("Enter the search file to look in ") > > search = raw_input ("Enter your search item ").split > > Here search is actually a function because you left out the > parentheses after split(). But with them, search would be a list. The > argument to count() must be a string. > > file = open(look_in, "r").read().count(search) > > print "Your search came",file ,"times" > > Do you want a count per line or for the whole file? For the whole file > you could do something like > > search_terms = raw_input ("Enter your search item ").split() # Note > the final () > data = open(look_in).read() > count = 0 > for term in search_terms: > count += data.count(term) > > The last three lines could also be written as > count = sum(data.count(term) for term in search_terms) > > Kent _________________________________________________________________ Check your Hotmail from your phone. http://go.microsoft.com/?linkid=9708121 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dananzoff at gmail.com Thu Feb 11 04:39:13 2010 From: dananzoff at gmail.com (Harya Dananjaya) Date: Thu, 11 Feb 2010 12:39:13 +0900 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <333efb451002101147t648f1fcfk2c62501014a00dba@mail.gmail.com> References: <4B730BB8.1030004@gmail.com> <333efb451002101147t648f1fcfk2c62501014a00dba@mail.gmail.com> Message-ID: <4B737BE1.6040407@gmail.com> On 11/02/10 04:47, Wayne Werner wrote: > Do you mean a windows executable? Not really. Why do you want an .exe > anyway? Python code is (usually) cross-platform. > > -Wayne Yupe, Yupe, python is cross platform, but we need install python in every computer we want to using the pyththon *.py . Harya Dananjaya From dananzoff at gmail.com Thu Feb 11 04:53:13 2010 From: dananzoff at gmail.com (Harya Dananjaya) Date: Thu, 11 Feb 2010 12:53:13 +0900 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <1e53c511002101149y4197a86apf3a41c305bccd1be@mail.gmail.com> References: <4B730BB8.1030004@gmail.com> <1e53c511002101149y4197a86apf3a41c305bccd1be@mail.gmail.com> Message-ID: <4B737F29.9090303@gmail.com> On 11/02/10 04:49, vince spicer wrote: > > 1. Ubuntu and linux in general don't use exe per say > 2. Python can be compiled but not usually in the way you are thinking > 3. you might check out http://pypi.python.org/pypi/bbfreeze/ > Vince 1.Yupe, I know ubuntu don't use exe file. I have windows too, but windows is slower than ubuntu, so that's waste my time. 2. what do you mean about 'not usually in the way you thingking'? 3. OK, I have downloaded bbfreeze on my windows, but I can't install it on windows, I use 'easy_install bbfreeze' command, but generate some error Then I use c_freeze, but when I compile with cx_freeze, it generate error : ---------------------------------------Begin error-------------------------------------------------------------------------------------------------------------- Missing modules: ? Image imported from matplotlib.image ? PyQt4.QtGui imported from matplotlib.pyplot ? _scproxy imported from urllib ? _transforms imported from matplotlib.dates ? _wxagg imported from matplotlib.backends.backend_wxagg ? config imported from matplotlib ? gobject imported from matplotlib.pyplot ? mpl_toolkits.natgrid imported from matplotlib.mlab ? nose imported from numpy.testing.nosetester ? numpy.core.integer imported from numpy.fft.helper ? numpy.core.signbit imported from numpy.testing.utils ? pkg_resources imported from pytz ? pyemf imported from matplotlib.backends.backend_emf ? pytz.zoneinfo imported from matplotlib.dates ? qt imported from matplotlib.pyplot ? scipy imported from numpy.testing.nosetester ? win32pdh imported from numpy.testing.utils ------------------------------END of Error------------------------------------------------------------------------------------------------------------------- Harya Dananjaya From dananzoff at gmail.com Thu Feb 11 04:54:51 2010 From: dananzoff at gmail.com (Harya Dananjaya) Date: Thu, 11 Feb 2010 12:54:51 +0900 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <1265831819.8722.22.camel@dedal-laptop> References: <4B730BB8.1030004@gmail.com> <1265831819.8722.22.camel@dedal-laptop> Message-ID: <4B737F8B.3040008@gmail.com> On 11/02/10 04:56, Grigor Kolev wrote: > Use cx_freeze but you cannot make exe in ubuntu must use Windows OK, I have installed cx_freeze on my windows, but when I compile with cx_freeze, it generate error : ---------------------------------------Begin error-------------------------------------------------------------------------------------------------------------- Missing modules: ? Image imported from matplotlib.image ? PyQt4.QtGui imported from matplotlib.pyplot ? _scproxy imported from urllib ? _transforms imported from matplotlib.dates ? _wxagg imported from matplotlib.backends.backend_wxagg ? config imported from matplotlib ? gobject imported from matplotlib.pyplot ? mpl_toolkits.natgrid imported from matplotlib.mlab ? nose imported from numpy.testing.nosetester ? numpy.core.integer imported from numpy.fft.helper ? numpy.core.signbit imported from numpy.testing.utils ? pkg_resources imported from pytz ? pyemf imported from matplotlib.backends.backend_emf ? pytz.zoneinfo imported from matplotlib.dates ? qt imported from matplotlib.pyplot ? scipy imported from numpy.testing.nosetester ? win32pdh imported from numpy.testing.utils ------------------------------END of Error------------------------------------------------------------------------------------------------------------------- Harya Dananjaya From cfuller084 at thinkingplanet.net Thu Feb 11 04:53:23 2010 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 10 Feb 2010 21:53:23 -0600 Subject: [Tutor] packing up python code to transfer to another machine In-Reply-To: <7228665.1265849311452.JavaMail.root@elwamui-norfolk.atl.sa.earthlink.net> References: <7228665.1265849311452.JavaMail.root@elwamui-norfolk.atl.sa.earthlink.net> Message-ID: <201002102153.23382.cfuller084@thinkingplanet.net> There are two obvious "gotchas". One is binary extensions. If you are using modules that are not "pure Python", you will have to find *nux versions for your target. The other problem is impossible to solve in general, but most of the time, it's less trouble than the first problem. Python is a dynamic language. Dependencies can be created at runtime (using __import__, exec, or execfile, at least), and it's certainly possible to write code that has unpredictable dependencies. Usually, however, the unknown dependency is drawn from a finite pool that is predictable. If you include all the bits that each third party modules comes with (and the same for your code, if it does any of these tricks), you should be Ok, but you can't prove it without analyzing the code. If you know the package dependencies (usually documented), you can work with that. matplotlib requires numpy, for instance. If this isn't enough, there's the modulefinder module. Note that it won't detect dynamic dependencies, so you have to know what third party stuff is included, and make sure you include all of it (or less, but only if you know what you're doing). Modulefinder also makes a lot of noise, and will include stuff you don't want or need. Another problem is platform compatibility. If you rely on the windows API, or filesystem idiosyncrasies, like drive letters, you'll have to fix those; but these are less surprising and easy to catch. Cheers On Wednesday 10 February 2010, dwbarne at earthlink.net wrote: > I have become a true Pythonaholic. My newest problem is.... > > I have a rather large Python code (1.5yrs + developing!) currently running > on Windows machines that imports several modules, some from external > libraries. It allows the user to easily access MySQL databases and plot > selected columns and such. > > I would like to bundle my (code + libraries + modules) and transfer all to > a *nix environment, rather than just transferring my code over and then > having to download and install all the relevant libraries again. > > Is this possible? I would think so with Python but am not sure. > > Is there a Python package that does this? If so, what? > > Thanks in advance. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From cfuller084 at thinkingplanet.net Thu Feb 11 05:18:50 2010 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 10 Feb 2010 22:18:50 -0600 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <4B737F8B.3040008@gmail.com> References: <4B730BB8.1030004@gmail.com> <1265831819.8722.22.camel@dedal-laptop> <4B737F8B.3040008@gmail.com> Message-ID: <201002102218.50893.cfuller084@thinkingplanet.net> Using freeze or another tool of its ilk is only going to make you an executable for that platform. If you want an executable for a different platform, you need to set up a native Python environment with all the dependencies installed where Python can find them, and then use that platform's tools for making a standalone version. Cheers From simbobo at cooptel.net Wed Feb 10 17:57:01 2010 From: simbobo at cooptel.net (Owain Clarke) Date: Wed, 10 Feb 2010 16:57:01 +0000 Subject: [Tutor] string to list In-Reply-To: References: Message-ID: <4B72E55D.4080700@cooptel.net> With thanks to all who made suggestions, this was what I settled on f = open('testfile') #(testfile consisting of 2 columns of data, as per Kent's suggestion) data = [] for line in f: line_data = [int(x) for x in line.split()] data.append(line_data) data.sort(key=lambda x:x[0]) print "sort by first key:", data data.sort(key=lambda x:x[1]) print "sort by second key:", data I would love a really clear explanation of lambda! Owain From grigor.kolev at gmail.com Thu Feb 11 08:58:52 2010 From: grigor.kolev at gmail.com (=?windows-1251?B?w/Do4+7w?=) Date: Thu, 11 Feb 2010 09:58:52 +0200 Subject: [Tutor] html and python In-Reply-To: <9b00d1a91002101628v11ba3349y288dde8593be42ed@mail.gmail.com> References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> <1265831670.8722.18.camel@dedal-laptop> <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> <1265833607.8722.24.camel@dedal-laptop> <9b00d1a91002101628v11ba3349y288dde8593be42ed@mail.gmail.com> Message-ID: I found this. http://karrigell.sourceforge.net/en/pythoninsidehtml.htm 2010/2/11 Benno Lang : > On Thu, Feb 11, 2010 at 5:26 AM, Grigor Kolev wrote: >> I apologize to my question is incorrectly set. >> We have a mail list and we want to do in site a list of all participants >> with their photos and names. >> List with people is saved in the txt file. >> I want to open this file. Take all mail address and to do formating the >> data. >> Then with loop to do parsing all data and to do send in the html. >> I can open and save as plain text document. >> File = file(r'/home/user/test.html', 'w') >> But if I refresh the data every day it by a ?slowly. > > If you can call scripts when actions occur on the mailing list (e.g. > new subscriber added, user unsubscribes, user details updated, etc), > then you could write a Python script to generate static HTML at that > point. It would probably be less hassle than creating a dynamic web > page. > > So then all you have to do is loop through your records and write the > resultant HTML to a file that the web server can read. > > HTH, > benno > -- ????? ???? ???? ???, ???? ???? ??????? ?? ???? ?? ???? ! From alan.gauld at btinternet.com Thu Feb 11 09:29:43 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Feb 2010 08:29:43 -0000 Subject: [Tutor] string to list References: <4B72E55D.4080700@cooptel.net> Message-ID: "Owain Clarke" wrote > I would love a really clear explanation of lambda! lambda returns an anonymous function - a function without a name. When we define a function normally we use something like: def square(x): return x*x That creates a function that has the name square We can do the same with lambda: square = lambda x : x*x which is equivalent to the def form. This is useful where we only need the function temporarily, such as to return a sort key or in building GUI controls. The general shape of lambda is: lambda : So in your case lambda x: x[0] could be replaced with def first(x): return x[0] lst.sort(key=first) But since you don't use first() for anything else you don't really need a named function so you can use a lambda. lambda is best used for short single line functions. In fact you can only use it where the body of the function can be expressed as a single expression. You will find more explanation and examples in the Functional Programming topic in my tutorial. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Feb 11 09:34:19 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Feb 2010 08:34:19 -0000 Subject: [Tutor] Compile py to exe in ubuntu References: <4B730BB8.1030004@gmail.com><333efb451002101147t648f1fcfk2c62501014a00dba@mail.gmail.com> <4B737BE1.6040407@gmail.com> Message-ID: "Harya Dananjaya" wrote >> Do you mean a windows executable? Not really. Why do you want an .exe >> anyway? Python code is (usually) cross-platform. > > Yupe, python is cross platform, but we need install python in every > computer we want to using the pyththon *.py . What would you do with Java? It too is cross platform but requires a JVM to be installed on every platform. Python is similar. The "compilers" actually bundle up the python interpreter with the script to create a large executable single file. But if you already have Python, or if you load several of these "exe"s it becomes very inefficient way to storing programs - multiple versions of Python. There can be cases where it makes sense but there are more cases where it malkes more sense to just install Python. IMHO -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From nikunjbadjatya at gmail.com Thu Feb 11 09:37:44 2010 From: nikunjbadjatya at gmail.com (nikunj badjatya) Date: Thu, 11 Feb 2010 14:07:44 +0530 Subject: [Tutor] "Error :Attempt to overwrite cell" while using xlwt to create excel sheets In-Reply-To: <1c2a2c591002100443i3fe03e45r2b57c69d83f5c037@mail.gmail.com> References: <1c2a2c591002100443i3fe03e45r2b57c69d83f5c037@mail.gmail.com> Message-ID: Hi, Many thanks to all.. I tried cell_overwrite=True and its working fine..!! On Wed, Feb 10, 2010 at 6:13 PM, Kent Johnson wrote: > On Wed, Feb 10, 2010 at 6:47 AM, nikunj badjatya > wrote: > > > I commented out the "raise Exception" statement in Row.py library > > module. > > Here's the (line no. 150 ) of Row.py which i have edited: > > > > def insert_cell(self, col_index, cell_obj): > > if col_index in self.__cells: > > if not self.__parent._cell_overwrite_ok: > > msg = "Attempt to overwrite cell: sheetname=%r rowx=%d > > colx=%d" \ > > % (self.__parent.name, self.__idx, col_index) > > #raise Exception(msg) > > #########*commented to avoid error. > > prev_cell_obj = self.__cells[col_index] > > sst_idx = getattr(prev_cell_obj, 'sst_idx', None) > > if sst_idx is not None: > > self.__parent_wb.del_str(sst_idx) > > self.__cells[col_index] = cell_obj > > > > The excel sheet creation code now works fine. > > > > My question is, Instead of manually goin to /usr/lib/.../row.py and > > commenting out the line, Can this be done through few lines of code in > > my program itself. ?? > > Looking at the code above, you can see that the exception is raised > only if self.__parent._cell_overwrite_ok is False. So there is an > option to allow overwriting. > > From the error message it appears that self.__parent is a Worksheet. > Looking at the source code for Worksheet.py, the __init__() method > does have an optional cell_overwrite_ok= parameter. This parameter is > also available in Workbook.add_sheet(). So if you pass > cell_overwrite=True to add_sheet() you should be OK. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.plum at uni-koeln.de Thu Feb 11 09:41:40 2010 From: alan.plum at uni-koeln.de (Alan Plum) Date: Thu, 11 Feb 2010 09:41:40 +0100 Subject: [Tutor] string to list In-Reply-To: <4B72E55D.4080700@cooptel.net> References: <4B72E55D.4080700@cooptel.net> Message-ID: <1265877700.2935.17.camel@kallisti> On Mi, 2010-02-10 at 16:57 +0000, Owain Clarke wrote: > I would love a really clear explanation of lambda! Generally, lambdas are anonymous functions. In Python specifically, however, they are limited to simple expressions (i.e. only what you can put on the right-hand side of an assignment). myfunction = lambda : is roughly equivalent to: def myfunction(): return (note that the function definition becomes invalid if you leave out the function name, lambdas OTOH don't need to be assigned to a named variable and don't contain a name in their definition) The point here is that the expression is evaluated and the result returned by the lambda, much like the expression following a return statement in a normal function: the equivalent function's body consists of a single return statement with the lambda's body as return value. There's not much to understanding how lambdas work. They just make one-offs easier when all you really want to do is pass a value where a callable is required or if you want to do something like accessing an index or sub-index or member variable of each object in a list (which is what the sorting function's key argument is usually used for). In the case of your code, your lambda was: lambda x: x[0] and lambda x: x[1] If applied to a tuple or list, this works like this: >>> mytuple = ('a','b') >>> l1 = lambda x: x[0] >>> l2 = lambda x: x[1] >>> l1(mytuple) 'a' >>> l2(mytuple) 'b' Hope that helps. Alan Plum From timomlists at gmail.com Thu Feb 11 09:47:41 2010 From: timomlists at gmail.com (Timo) Date: Thu, 11 Feb 2010 09:47:41 +0100 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <4B730BB8.1030004@gmail.com> References: <4B730BB8.1030004@gmail.com> Message-ID: <4B73C42D.7090405@gmail.com> On 10-02-10 20:40, Harya Dananjaya wrote: > Can I compile my python source to exe in ubuntu? Like said before, you need Windows for this. > if I can do it, which compiler can do it? I use py2exe to compile my Python/PyGTK application. I build it on my Windows XP machine and it works on Windows 2000 to Windows 7 without installing anything else (like Python). Try GUI2exe for a nice graphical interface. Cheers, Timo > > Thanks you, > > Harya Dananjaya > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From stefan_ml at behnel.de Thu Feb 11 10:44:08 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 11 Feb 2010 10:44:08 +0100 Subject: [Tutor] string to list In-Reply-To: <4B72E55D.4080700@cooptel.net> References: <4B72E55D.4080700@cooptel.net> Message-ID: Owain Clarke, 10.02.2010 17:57: > data.sort(key=lambda x:x[0]) > data.sort(key=lambda x:x[1]) Two things to note: 1) you can use the operator module, specifically operator.itemgetter 2) given that you have lists as items in the 'data' list, it's enough to call sort() once, as the comparison of lists is defined as the comparison of each item to the corresponding item of the other list. If you want to sort based on the second item before the first item, it's best to exchange both items before sorting and swap them back afterwards. Stefan From laomao1975 at googlemail.com Thu Feb 11 10:56:51 2010 From: laomao1975 at googlemail.com (Lao Mao) Date: Thu, 11 Feb 2010 09:56:51 +0000 Subject: [Tutor] Simple Stats on Apache Logs Message-ID: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> Hi, I have 3 servers which generate about 2G of webserver logfiles in a day. These are available on my machine over NFS. I would like to draw up some stats which shows, for a given keyword, how many times it appears in the logs, per hour, over the previous week. So the behavior might be: $ ./webstats --keyword downloader Which would read from the logs (which it has access to) and produce something like: Monday: 0000: 12 0100: 17 etc I'm not sure how best to get started. My initial idea would be to filter the logs first, pulling out the lines with matching keywords, then check the timestamp - maybe incrementing a dictionary if the logfile was within a certain time? I'm not looking for people to write it for me, but I'd appreciate some guidance as the the approach and algorithm. Also what the simplest presentation model would be. Or even if it would make sense to stick it in a database! I'll post back my progress. Thanks, Laomao -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Feb 11 11:35:20 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 11 Feb 2010 12:35:20 +0200 Subject: [Tutor] Simple Stats on Apache Logs In-Reply-To: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> References: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> Message-ID: <4B73DD68.1090405@compuscan.co.za> Lao Mao wrote: > Hi, > > I have 3 servers which generate about 2G of webserver logfiles in a > day. These are available on my machine over NFS. > > I would like to draw up some stats which shows, for a given keyword, > how many times it appears in the logs, per hour, over the previous week. > > So the behavior might be: > > $ ./webstats --keyword downloader > > Which would read from the logs (which it has access to) and produce > something like: > > Monday: > 0000: 12 > 0100: 17 > > etc > > I'm not sure how best to get started. My initial idea would be to > filter the logs first, pulling out the lines with matching keywords, > then check the timestamp - maybe incrementing a dictionary if the > logfile was within a certain time? > > I'm not looking for people to write it for me, but I'd appreciate some > guidance as the the approach and algorithm. Also what the simplest > presentation model would be. Or even if it would make sense to stick > it in a database! I'll post back my progress. > > Thanks, > > Laomao > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > grep -c or if you are looking for only stuff for today for eg then grep | grep -c That would be the simplest implementation. For a python implementation think about dictionaries with multiple layers like {Date: {Keyword1: Count, Keyword2: Count}. Essentially you would just iterate over the file, check if the line contains your keyword(s) that you are looking for and then incrementing the counter for it. -- Kind Regards, Christian Witts Business Intelligence C o m p u s c a n | Confidence in Credit Telephone: +27 21 888 6000 National Cell Centre: 0861 51 41 31 Fax: +27 21 413 2424 E-mail: cwitts at compuscan.co.za NOTE: This e-mail (including attachments )is subject to the disclaimer published at: http://www.compuscan.co.za/live/content.php?Item_ID=494. If you cannot access the disclaimer, request it from email.disclaimer at compuscan.co.za or 0861 514131. National Credit Regulator Credit Bureau Registration No. NCRCB6 From laomao1975 at googlemail.com Thu Feb 11 11:50:41 2010 From: laomao1975 at googlemail.com (Lao Mao) Date: Thu, 11 Feb 2010 10:50:41 +0000 Subject: [Tutor] Simple Stats on Apache Logs In-Reply-To: <4B73DD68.1090405@compuscan.co.za> References: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> <4B73DD68.1090405@compuscan.co.za> Message-ID: <9f92935c1002110250g7828748dk3dcbf72cdf3b4bee@mail.gmail.com> Hi Christian, grep -c > or if you are looking for only stuff for today for eg then > grep | grep -c > I don't see how that will produce figures per hour! That would be the simplest implementation. For a python implementation > think about dictionaries with multiple layers like {Date: {Keyword1: Count, > Keyword2: Count}. Essentially you would just iterate over the file, check > if the line contains your keyword(s) that you are looking for and then > incrementing the counter for it. > OK. Laomao -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Thu Feb 11 12:18:03 2010 From: denis.spir at free.fr (spir) Date: Thu, 11 Feb 2010 12:18:03 +0100 Subject: [Tutor] Simple Stats on Apache Logs In-Reply-To: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> References: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> Message-ID: <20100211121803.3532653b@o> On Thu, 11 Feb 2010 09:56:51 +0000 Lao Mao wrote: > Hi, > > I have 3 servers which generate about 2G of webserver logfiles in a day. > These are available on my machine over NFS. > > I would like to draw up some stats which shows, for a given keyword, how > many times it appears in the logs, per hour, over the previous week. > > So the behavior might be: > > $ ./webstats --keyword downloader > > Which would read from the logs (which it has access to) and produce > something like: > > Monday: > 0000: 12 > 0100: 17 > > etc > > I'm not sure how best to get started. My initial idea would be to filter > the logs first, pulling out the lines with matching keywords, then check the > timestamp - maybe incrementing a dictionary if the logfile was within a > certain time? > > I'm not looking for people to write it for me, but I'd appreciate some > guidance as the the approach and algorithm. Also what the simplest > presentation model would be. Or even if it would make sense to stick it in > a database! I'll post back my progress. As your logfile in rather big, I would iterate line per line using "for line in file". Check each line to determine whether (1) it has changed hour (2) it holds the given keyword. For the presentation, it depends on your expectation! Also, are keywords constants (= predefined at coding time)? You may think at a python (nested) dict: keywordStats = {} ... keywordStats[one_keyword] = { Monday: [12, 17, ...] , ... } (hours in 24 format (actually 0..23) are implicit keys of the lists) This lets open the opportunity to read the info back into the machine... Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From sierra_mtnview at sbcglobal.net Thu Feb 11 12:38:51 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 11 Feb 2010 03:38:51 -0800 Subject: [Tutor] Exiting a Tkinter Program-- An Anomaly or two In-Reply-To: <4B721328.1090002@sbcglobal.net> References: <4B721328.1090002@sbcglobal.net> Message-ID: <4B73EC4B.9070902@sbcglobal.net> Well, I found where I had tucked away my inbox mail folder for tkinter. Somehow it got to be a subfolder of another list. It hadn't been used by me for months. The short of this is that I posted to tkinter, and have a better understanding of this now. In fact, fixed it by using sys.exit() in the def. On 2/9/2010 6:00 PM, Wayne Watson wrote: > I'm looking a 1800+ line someone else wrote. It uses one large dialog > for menus, and has a large area for images. A few menus open small > dialogs, for example, to enter a file name. The File menu has an exit > choice. The only other exit is the x in the upper right corner of the > large dialog. I'm pretty sure that menu is coded to quit via a shoft > def in the program. > > def Quit(self) > self.running = False > self.master.quit() > > I see no other code to quit. If I use Exit, the program does not > quite. If I then use the x, it quits and the shell script is left open > for a command. Any ideas why Quit doesn't work? It's accessible via a > self.mainMenu.add_command(.. command=self.Quit) > I had not turned the program loose by using a menu or touching any > controls. > > If I cause the program to print to the shell, and then use x to exit > that it hangs the shell. Why? When I x the shell, it tells me the > prog is running. Do I want to kill it. Yes,kills the shell window. > > The above seem abnormal to me. Comments? > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From dananzoff at gmail.com Thu Feb 11 12:44:48 2010 From: dananzoff at gmail.com (Harya Dananjaya) Date: Thu, 11 Feb 2010 20:44:48 +0900 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: References: <4B730BB8.1030004@gmail.com><333efb451002101147t648f1fcfk2c62501014a00dba@mail.gmail.com> <4B737BE1.6040407@gmail.com> Message-ID: <4B73EDB0.6060602@gmail.com> On 11/02/10 17:34, Alan Gauld wrote: > > What would you do with Java? It too is cross platform but requires a > JVM to be installed on every platform. Python is similar. > OK, but python need 3rd praties library, and may be the the user don't know about the 3rd party libraries, and don't know how to install it on his computer. And not all person is programmer, so he don't want to know about programming, he just want to use the program. Harya Dananjaya From andreas at kostyrka.org Thu Feb 11 13:02:07 2010 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 11 Feb 2010 13:02:07 +0100 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <4B73EDB0.6060602@gmail.com> References: <4B730BB8.1030004@gmail.com> <4B73EDB0.6060602@gmail.com> Message-ID: <201002111302.07899.andreas@kostyrka.org> Am Donnerstag, 11. Februar 2010 12:44:48 schrieb Harya Dananjaya: > On 11/02/10 17:34, Alan Gauld wrote: > > What would you do with Java? It too is cross platform but requires a > > JVM to be installed on every platform. Python is similar. > > OK, but python need 3rd praties library, and may be the the user don't > know about the 3rd party libraries, and don't know how to install it on > his computer. And not all person is programmer, so he don't want to know > about programming, he just want to use the program. Well, compiling it to a binary would not solve the problem. 1.) either you dynamically link the libraries. Then the user needs to have these installed. 2.) or you statically link the libraries. Then you get the same problem, slightly different: While the libraries are in the binary (which is a bad thing for many reasons, e.g. security fixes do not get applied this way), you can still have an environment mismatch, e.g. if your library expects services, file paths, and so on. The correct way to package a Linux program is to create a package for the distributions you want to support, and provide the source code and a README for all others. This way you can support users that are computer illiterate by making the package system ensure that all dependencies are available (and you can customize your app for the distribution if needed), and computer literate people can just read your README. If installing a package is to complicated for your target users, your only plausible strategy would be to make it a webapp, sorry. Andreas > > Harya Dananjaya > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Feb 11 14:13:53 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Feb 2010 08:13:53 -0500 Subject: [Tutor] html and python In-Reply-To: References: <1265830252.8722.1.camel@dedal-laptop> <1c2a2c591002101139q7106c729hc20d7731f783df29@mail.gmail.com> <1265831670.8722.18.camel@dedal-laptop> <1c2a2c591002101202h767b082fg8bdbfbd8dbd4d2ac@mail.gmail.com> <1265833607.8722.24.camel@dedal-laptop> <9b00d1a91002101628v11ba3349y288dde8593be42ed@mail.gmail.com> Message-ID: <1c2a2c591002110513l43195f8ct1017e2fbc8f89bfd@mail.gmail.com> 2010/2/11 ?????? : > I found this. > http://karrigell.sourceforge.net/en/pythoninsidehtml.htm Many options here: http://wiki.python.org/moin/Templating Kent From kent37 at tds.net Thu Feb 11 14:16:42 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Feb 2010 08:16:42 -0500 Subject: [Tutor] string to list In-Reply-To: References: <4B72E55D.4080700@cooptel.net> Message-ID: <1c2a2c591002110516v591093c6g65fda694ed3f21d@mail.gmail.com> On Thu, Feb 11, 2010 at 4:44 AM, Stefan Behnel wrote: > 2) given that you have lists as items in the 'data' list, it's enough to > call sort() once, as the comparison of lists is defined as the comparison > of each item to the corresponding item of the other list. If you want to > sort based on the second item before the first item, it's best to exchange > both items before sorting and swap them back afterwards. No, that is the old decorate-sort-undecorate idiom which has been replaced by the key= parameter to sort. data.sort(key=operator.itemgetter(1)) is the best way to sort on the second item. Kent From kent37 at tds.net Thu Feb 11 14:21:52 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Feb 2010 08:21:52 -0500 Subject: [Tutor] Simple Stats on Apache Logs In-Reply-To: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> References: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> Message-ID: <1c2a2c591002110521s35316e2fs4920558b5609f36b@mail.gmail.com> On Thu, Feb 11, 2010 at 4:56 AM, Lao Mao wrote: > Hi, > > I have 3 servers which generate about 2G of webserver logfiles in a day. > These are available on my machine over NFS. > > I would like to draw up some stats which shows, for a given keyword, how > many times it appears in the logs, per hour, over the previous week. > > So the behavior might be: > > $ ./webstats --keyword downloader > > Which would read from the logs (which it has access to) and produce > something like: > > Monday: > 0000: 12 > 0100: 17 > > etc > > I'm not sure how best to get started.? My initial idea would be to filter > the logs first, pulling out the lines with matching keywords, then check the > timestamp - maybe incrementing a dictionary if the logfile was within a > certain time? I would use itertools.groupby() to group lines by hour, then look for the keywords and increment a count. The technique of stacking generators as a processing pipeline might be useful. See David Beazley's "Generator Tricks for System Programmers" http://www.dabeaz.com/generators-uk/index.html Loghetti might also be useful as a starting point or code reference: http://code.google.com/p/loghetti/ Kent From stefan_ml at behnel.de Thu Feb 11 14:37:34 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 11 Feb 2010 14:37:34 +0100 Subject: [Tutor] string to list In-Reply-To: <1c2a2c591002110516v591093c6g65fda694ed3f21d@mail.gmail.com> References: <4B72E55D.4080700@cooptel.net> <1c2a2c591002110516v591093c6g65fda694ed3f21d@mail.gmail.com> Message-ID: Kent Johnson, 11.02.2010 14:16: > On Thu, Feb 11, 2010 at 4:44 AM, Stefan Behnel wrote: > >> 2) given that you have lists as items in the 'data' list, it's enough to >> call sort() once, as the comparison of lists is defined as the comparison >> of each item to the corresponding item of the other list. If you want to >> sort based on the second item before the first item, it's best to exchange >> both items before sorting and swap them back afterwards. > > No, that is the old decorate-sort-undecorate idiom which has been > replaced by the key= parameter to sort. Nothing keeps you from writing data.sort(key=lambda x:x[::-1]) or data.sort(key=operator.itemgetter(slice(None,None,-1)) (which is equivalent) Stefan From kent37 at tds.net Thu Feb 11 15:11:30 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Feb 2010 09:11:30 -0500 Subject: [Tutor] string to list In-Reply-To: References: <4B72E55D.4080700@cooptel.net> <1c2a2c591002110516v591093c6g65fda694ed3f21d@mail.gmail.com> Message-ID: <1c2a2c591002110611r1dd2178eq643d99c9abda0e42@mail.gmail.com> On Thu, Feb 11, 2010 at 8:37 AM, Stefan Behnel wrote: > Kent Johnson, 11.02.2010 14:16: >> On Thu, Feb 11, 2010 at 4:44 AM, Stefan Behnel wrote: >> >>> 2) given that you have lists as items in the 'data' list, it's enough to >>> call sort() once, as the comparison of lists is defined as the comparison >>> of each item to the corresponding item of the other list. If you want to >>> sort based on the second item before the first item, it's best to exchange >>> both items before sorting and swap them back afterwards. >> >> No, that is the old decorate-sort-undecorate idiom which has been >> replaced by the key= parameter to sort. > > Nothing keeps you from writing > > ? ?data.sort(key=lambda x:x[::-1]) > > or > > ? ?data.sort(key=operator.itemgetter(slice(None,None,-1)) Ok, I thought you meant make a new list. These examples don't swap anything back... You can also use data.sort(key=operator.itemgetter(1, 0)) Kent From dananzoff at gmail.com Thu Feb 11 15:42:31 2010 From: dananzoff at gmail.com (Harya Dananjaya) Date: Thu, 11 Feb 2010 23:42:31 +0900 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <4B73C42D.7090405@gmail.com> References: <4B730BB8.1030004@gmail.com> <4B73C42D.7090405@gmail.com> Message-ID: <4B741757.4000008@gmail.com> On 11/02/10 17:47, Timo wrote: > I use py2exe to compile my Python/PyGTK application. > I build it on my Windows XP machine and it works on Windows 2000 to > Windows 7 without installing anything else (like Python). > > Try GUI2exe for a nice graphical interface. > > Cheers, > Timo > Yupe, I have a windows, after I using py2exe, the compilation is success, but when I run the *.exe, some error generated : Traceback (most recent call last): File "fondasi-4.py", line 16, in File "draw.pyc", line 5, in File "matplotlib\__init__.pyc", line 709, in File "matplotlib\__init__.pyc", line 627, in rc_params File "matplotlib\__init__.pyc", line 569, in matplotlib_fname File "matplotlib\__init__.pyc", line 240, in wrapper File "matplotlib\__init__.pyc", line 483, in _get_data_path_cached File "matplotlib\__init__.pyc", line 479, in _get_data_path RuntimeError: Could not find the matplotlib data files From andreas at kostyrka.org Thu Feb 11 15:57:32 2010 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 11 Feb 2010 15:57:32 +0100 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <4B741757.4000008@gmail.com> References: <4B730BB8.1030004@gmail.com> <4B73C42D.7090405@gmail.com> <4B741757.4000008@gmail.com> Message-ID: <201002111557.33018.andreas@kostyrka.org> Am Donnerstag, 11. Februar 2010 15:42:31 schrieb Harya Dananjaya: > On 11/02/10 17:47, Timo wrote: > > I use py2exe to compile my Python/PyGTK application. > > I build it on my Windows XP machine and it works on Windows 2000 to > > Windows 7 without installing anything else (like Python). > > > > Try GUI2exe for a nice graphical interface. > > > > Cheers, > > Timo > > Yupe, I have a windows, > after I using py2exe, the compilation is success, > but when I run the *.exe, > some error generated : > RuntimeError: Could not find the matplotlib data files What's so hard? It's a plain text error message. So obviously (for people with at least two working brain cells, sorry could not resist), you need to include these too (or matplotlib will not work with py2exe, depending how it accesses these files I guess). So google searches that I'd consider: matplotlib py2exe py2exe including datafiles Andreas From dananzoff at gmail.com Thu Feb 11 16:21:43 2010 From: dananzoff at gmail.com (Harya Dananjaya) Date: Fri, 12 Feb 2010 00:21:43 +0900 Subject: [Tutor] Compile py to exe in ubuntu In-Reply-To: <201002111557.33018.andreas@kostyrka.org> References: <4B730BB8.1030004@gmail.com> <4B73C42D.7090405@gmail.com> <4B741757.4000008@gmail.com> <201002111557.33018.andreas@kostyrka.org> Message-ID: <4B742087.4080200@gmail.com> On 11/02/10 23:57, Andreas Kostyrka wrote: > What's so hard? It's a plain text error message. thank you,,, Now it's solved, I have include the needed library,,, It's solved, Thank you for all help me, Harya Dananjaya From randyeraymond at mchsi.com Thu Feb 11 17:09:38 2010 From: randyeraymond at mchsi.com (Randy Raymond) Date: Thu, 11 Feb 2010 10:09:38 -0600 Subject: [Tutor] Shelve Message-ID: I am running Python 2.6.4 under Windows Vista 32-bit Home Edition. When I run: import shelve test=shelve.open("myTest.fil") I get a DCPermissionerror exception. I am an administrator on this machine (it is my home PC). Python and Pythonw are both allowed exceptions to the Windows firewall. I tried turning the Windows Firewall completely off, but that does not help. Any ideas? Randy Raymond -------------- next part -------------- An HTML attachment was scrubbed... URL: From laomao1975 at googlemail.com Thu Feb 11 17:23:20 2010 From: laomao1975 at googlemail.com (Lao Mao) Date: Thu, 11 Feb 2010 16:23:20 +0000 Subject: [Tutor] Downloading S3 Logs Message-ID: <9f92935c1002110823g24033bf1qe742d63d6ff4062e@mail.gmail.com> Hello, I've written the below to get the previous day's logs from an Amazon S3 bucket. #!/usr/bin/python import time from datetime import datetime import boto daily_s3_log = open("/tmp/s3logs", "w+") now = datetime.now() connection = boto.connect_s3() bucket = connection.get_bucket("downloads.sekrit.co.uk") todays_keys = [] for key in bucket: time_difference = (now - datetime(*time.strptime(key.last_modified.split(".")[0], "%Y-%m-%dT%H: %M:%S")[0:6])).days if time_difference < 1 and key.name.startswith("log/access_log"): todays_keys.append(key) for key in todays_keys: key.get_file(daily_s3_log) daily_s3_log.close() This takes about 2 mins to download a day's logs (about 25M). I'd appreciate any improvements or feedback on the above. For example, would it make sense to make the first loop into a generator function that yields the interesting keys? Also is there a cleaner way to do the date comparison in Python 2.4? Thanks, Laomao -------------- next part -------------- An HTML attachment was scrubbed... URL: From randyeraymond at mchsi.com Thu Feb 11 17:54:14 2010 From: randyeraymond at mchsi.com (Randy Raymond) Date: Thu, 11 Feb 2010 10:54:14 -0600 Subject: [Tutor] Downloading S3 Logs In-Reply-To: <9f92935c1002110823g24033bf1qe742d63d6ff4062e@mail.gmail.com> References: <9f92935c1002110823g24033bf1qe742d63d6ff4062e@mail.gmail.com> Message-ID: <8F9AAEA0538346C2B328910CD4C7C27E@RandyPC> Mr. Mao, I am not a professional programmer. However, I do think that you want to reduce the number of "things" that you have to do in loops that go through the transaction (log entries in your case). Since you are converting to a datetime, perhaps rather than doing a calculation, you should remove the calculation and compare the datetime to yesterday (yesterday=now-1, whatever the datetime needs to make it yesterday) in the "if" statement (I.e. change "time_differnce < 1" to recordDate (<-make this instead of time_difference). You can try changing things a bit to see if it speeds up. For example, if a lot of messages are failing the "key.name.startswith("log/access_log")" test, then maybe make a nested if, testing "key.name.startswith("log/access_log")" before you actually test the date difference. Or, switch it around and test the date first, the the "key.name.startswith("log/access_log")". Sincerely, Randy Raymond From: Lao Mao Sent: Thursday, February 11, 2010 10:23 AM To: tutor at python.org Subject: [Tutor] Downloading S3 Logs Hello, I've written the below to get the previous day's logs from an Amazon S3 bucket. #!/usr/bin/python import time from datetime import datetime import boto daily_s3_log = open("/tmp/s3logs", "w+") now = datetime.now() connection = boto.connect_s3() bucket = connection.get_bucket("downloads.sekrit.co.uk") todays_keys = [] for key in bucket: time_difference = (now - datetime(*time.strptime(key.last_modified.split(".")[0], "%Y-%m-%dT%H: %M:%S")[0:6])).days if time_difference < 1 and key.name.startswith("log/access_log"): todays_keys.append(key) for key in todays_keys: key.get_file(daily_s3_log) daily_s3_log.close() This takes about 2 mins to download a day's logs (about 25M). I'd appreciate any improvements or feedback on the above. For example, would it make sense to make the first loop into a generator function that yields the interesting keys? Also is there a cleaner way to do the date comparison in Python 2.4? Thanks, Laomao -------------------------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From oberoc at gmail.com Thu Feb 11 18:09:20 2010 From: oberoc at gmail.com (Tino Dai) Date: Thu, 11 Feb 2010 12:09:20 -0500 Subject: [Tutor] Downloading S3 Logs In-Reply-To: <9f92935c1002110823g24033bf1qe742d63d6ff4062e@mail.gmail.com> References: <9f92935c1002110823g24033bf1qe742d63d6ff4062e@mail.gmail.com> Message-ID: <2ac5d4851002110909l1c45ba89s2b33ff513ba46a5b@mail.gmail.com> On Thu, Feb 11, 2010 at 11:23 AM, Lao Mao wrote: > Hello, > > I've written the below to get the previous day's logs from an Amazon S3 > bucket. > > #!/usr/bin/python > import time > from datetime import datetime > import boto > > daily_s3_log = open("/tmp/s3logs", "w+") > now = datetime.now() > connection = boto.connect_s3() > bucket = connection.get_bucket("downloads.sekrit.co.uk") > todays_keys = [] > > for key in bucket: > time_difference = (now - > datetime(*time.strptime(key.last_modified.split(".")[0], "%Y-%m-%dT%H: > %M:%S")[0:6])).days > if time_difference < 1 and key.name.startswith("log/access_log"): > todays_keys.append(key) > > for key in todays_keys: > key.get_file(daily_s3_log) > > daily_s3_log.close() > > This takes about 2 mins to download a day's logs (about 25M). > > What I would do would be to profile your code: You can find more profiling info @ http://docs.python.org/library/profile.html -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Thu Feb 11 18:15:40 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 11 Feb 2010 18:15:40 +0100 Subject: [Tutor] Shelve In-Reply-To: References: Message-ID: <1265908540.17394.11.camel@infirit> On do, 2010-02-11 at 10:09 -0600, Randy Raymond wrote: > I am running Python 2.6.4 under Windows Vista 32-bit Home Edition. > When I run: > > import shelve > test=shelve.open("myTest.fil") And to shich directory does this file get written? I suspect you are writing to a protected directory. When no path is given it will be written to the current directory, check with the os module where this is. import os, shelve print os.path.realpath(os.path.curdir) test=shelve.open("myTest.fil") Better is to always pass a full path like, 'C:\\Users\\ I get a DCPermissionerror exception. I am an administrator on this > machine (it is my home PC). Python and Pythonw are both allowed > exceptions to the Windows firewall. I tried turning the Windows > Firewall completely off, but that does not help. Any ideas? It is *always* helpful to provide the full error message. Greets Sander From randyeraymond at mchsi.com Thu Feb 11 17:22:17 2010 From: randyeraymond at mchsi.com (Randy Raymond) Date: Thu, 11 Feb 2010 10:22:17 -0600 Subject: [Tutor] Shelve In-Reply-To: References: Message-ID: <1A9DBDDEDBA945B6BBBDA8D467B0A825@RandyPC> Ok, I see that is was the directory restriction that was the problem. Sorry for the simple question. Randy Raymond From: Randy Raymond Sent: Thursday, February 11, 2010 10:09 AM To: Tutor Python Subject: [Tutor] Shelve I am running Python 2.6.4 under Windows Vista 32-bit Home Edition. When I run: import shelve test=shelve.open("myTest.fil") I get a DCPermissionerror exception. I am an administrator on this machine (it is my home PC). Python and Pythonw are both allowed exceptions to the Windows firewall. I tried turning the Windows Firewall completely off, but that does not help. Any ideas? Randy Raymond -------------------------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From gtxy37 at hotmail.com Thu Feb 11 19:59:54 2010 From: gtxy37 at hotmail.com (Matthew Matson) Date: Thu, 11 Feb 2010 13:59:54 -0500 Subject: [Tutor] Algorithm for combination analysis suggestion. Message-ID: Hi Tutors, I am looking for the proper approach regarding the analysis of a dictionary of combinations I have. What I need to do is read from a supplied text file that has a unique ID and that unique ID's associated combination of elements. So let's say I have the following lines in a text file (real file could be millions of lines): "ID" "Elements" 1 'A, B, C, D' 2 'A, D' 3 'D, E' 4 'A, D' 5 'A, B' 6 'A, C, D' and I do something like... combinationDict = {} for line in file: data = line.split('\t') comb = tuple(data[1].split(',')) if comb not in combinationDict: combinationDict[comb] = 1 else: combination[comb] +=1 Now after I read all of the data I end up with a dictionary with the combination as the key and the associated total qty as its value. print combinationDict {('A','B','C','D'):1, ('A','D'):2, ('D','E'):1, ('A','B'):1, ('A', 'C', 'D'):1} What I am looking for is a starting point for a solution in python to analyze the combination list so that I can determine for example that ('A', 'D') is the most popular combination and then determining how many other combinations in the dictionary contain this combination. I would like to incorporate some parameters so for example the combination ('A','B','C','D') and ('A', 'C', 'D') contain ('A','D') so they are valid but I could also say that as long as one element is contained in a combination it is valid as well provided I add no more than one additional item to the combination. If I apply this logic then ('D','E') can ('A','B') can contain ('A', 'D') and if I apply this to the combination dictionary I have: {('B','C', ('A', 'D')):1, ('A','D'):2, ('E', ('A', 'D')):1, ('B', ('A', 'D')):1, ('C', ('A', 'D')):1} which I could then query the keys for ('A', 'D') inclusion to get a total of 4 for ('A', 'D'). I hope this isn't too long and confusing but I am looking for an approach where I can analyze for the highest quantity of combinations and then iterate through the dictionary substituting those combinations that were determined a "highest qty" combination into other low qty combinations when valid. I was hoping to have parameters to qualify a high qty combination (e.g. every combination with qty above 10,000) with the highest quantity of that determined set taking precedence for substitution for the first pass then moving on to the next highest combination for the second pass of substitution etc.. The other parameter would be for the combination that would receive a substitution whereby I might say that I can only substitute if a substitution results in only one additional (superfluous) value being added to the combination existing low qty combination. I have looked around and this sounds like it might be similar to a packing problem and in particular the knapsack problem but I can't seem to wrap my head around an approach for this in python. I am not looking for a solution just some guidance on a starting point or perhaps libraries that may be helpful. Thank you. _________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From grigor.kolev at gmail.com Thu Feb 11 21:13:36 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Thu, 11 Feb 2010 22:13:36 +0200 Subject: [Tutor] SMTP Message-ID: <1265919216.8909.13.camel@dedal-laptop> Hi. I try send a mail with smtplib Server work with postfix. I try it ------------------------------------------------ import smtplib s=smtplib.SMTP("localhost") tolist=['grigor.kolev at gmail.com'] msg = '''\ From: grigor.kolev at gmail.com Subject: testin' This is a test ''' s.sendmail("test at local", tolist, msg) ------------------------------------------------- How can i send the file? And I am not sure that work. Mail is not sending but perhaps problem i in my postfix. -- Grigor Kolev From kent37 at tds.net Thu Feb 11 21:21:51 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Feb 2010 15:21:51 -0500 Subject: [Tutor] Algorithm for combination analysis suggestion. In-Reply-To: References: Message-ID: <1c2a2c591002111221g65f17639wa798118b5a71b6ff@mail.gmail.com> On Thu, Feb 11, 2010 at 1:59 PM, Matthew Matson wrote: > > Hi Tutors, > > I am looking for the proper approach regarding the analysis of a dictionary > of combinations I have. > > What I need to do is read from a supplied text file that has a unique ID and > that unique ID's associated combination of elements. So let's say I have the > following lines in a text file (real file could be millions of lines): > > "ID"??? "Elements" > 1??? 'A, B, C, D' > 2??? 'A, D' > 3??? 'D, E' > 4??? 'A, D' > 5??? 'A, B' > 6??? 'A, C, D' > > and I do something like... > > combinationDict = {} > for line in file: > ??? data = line.split('\t') > ??? comb = tuple(data[1].split(',')) > ??? if comb not in combinationDict: > ??? ??? combinationDict[comb] = 1 > ??? else: > ??? ??? combination[comb] +=1 Use combinationDict = collections.defaultdict(int) Then you can just write combination[comb] += 1 without the test for comb in combinattionDict. > Now after I read all of the data I end up with a dictionary with the > combination as the key and the associated total qty as its value. > > print combinationDict > {('A','B','C','D'):1, ('A','D'):2, ('D','E'):1, ('A','B'):1, ('A', 'C', > 'D'):1} > > What I am looking for is a starting point for a solution in python to > analyze the combination list so that I can determine for example that ('A', > 'D') is the most popular combination and then determining how many other > combinations in the dictionary contain this combination. maxComb = max(combinationDict, key=combinationDict.__getitem__) will give you the single key with the largest count. maxCombSet = set(maxComb) [ comb for comb in combinationDict if maxCombSet <= set(comb) ] will give you a list of all the combinations that contain the max though it could be slow if you have lots of unique combinations (because of all the set conversions). > I would like to incorporate some parameters so for example the combination > ('A','B','C','D') and ('A', 'C', 'D') contain ('A','D') so they are valid > but I could also say that as long as one element is contained in a > combination it is valid as well provided I add no more than one additional > item to the combination. Now you are starting to lose me but you can modify the conditional in the above list comprehension to make whatever kind of test you want. > If I apply this logic then ('D','E') can ('A','B') > can contain ('A', 'D') and if I apply this to the combination dictionary I > have: > > {('B','C', ('A', 'D')):1, ('A','D'):2, ('E', ('A', 'D')):1, ('B', ('A', > 'D')):1, ('C', ('A', 'D')):1} > > which I could then query the keys for ('A', 'D') inclusion to get a total of > 4 for ('A', 'D'). Now you have lost me completely. What are the keys in this new dict? How do you get a total of 4 fro ('A', 'D')? Kent > I hope this isn't too long and confusing but I am looking for an approach > where I can analyze for the highest quantity of combinations and then > iterate through the dictionary substituting those combinations that were > determined a "highest qty" combination into other low qty combinations when > valid. > > I was hoping to have parameters to qualify a high qty combination (e.g. > every combination with qty above 10,000) with the highest quantity of that > determined set taking precedence for substitution for the first pass then > moving on to the next highest combination for the second pass of > substitution etc.. The other parameter would be for the combination that > would receive a substitution whereby I might say that I can only substitute > if a substitution results in only one additional (superfluous) value being > added to the combination existing low qty combination. > > I have looked around and this sounds like it might be similar to a packing > problem and in particular the knapsack problem but I can't seem to wrap my > head around an approach for this in python. I am not looking for a solution > just some guidance on a starting point or perhaps libraries that may be > helpful. > > Thank you. > > > ________________________________ > Windows? phone-your Windows stuff, on the go. See more. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Feb 11 22:04:31 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 11 Feb 2010 16:04:31 -0500 Subject: [Tutor] SMTP In-Reply-To: <1265919216.8909.13.camel@dedal-laptop> References: <1265919216.8909.13.camel@dedal-laptop> Message-ID: <1c2a2c591002111304y13730a1ahe13ccd8c011e5268@mail.gmail.com> On Thu, Feb 11, 2010 at 3:13 PM, Grigor Kolev wrote: > Hi. > I try send a mail with smtplib > Server work with postfix. > I try it > ------------------------------------------------ > ?import smtplib > ?s=smtplib.SMTP("localhost") > tolist=['grigor.kolev at gmail.com'] > msg = '''\ > ?From: grigor.kolev at gmail.com > Subject: testin' > This is a test ''' > s.sendmail("test at local", tolist, msg) > ------------------------------------------------- > How can i send the file? I think you need the To: header in the msg, and possibly a blank line after the headers. See the example here: http://docs.python.org/library/smtplib.html#smtp-example Kent From alan.gauld at btinternet.com Thu Feb 11 23:00:58 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Feb 2010 22:00:58 -0000 Subject: [Tutor] Compile py to exe in ubuntu References: <4B730BB8.1030004@gmail.com><333efb451002101147t648f1fcfk2c62501014a00dba@mail.gmail.com> <4B737BE1.6040407@gmail.com> <4B73EDB0.6060602@gmail.com> Message-ID: "Harya Dananjaya" wrote >> What would you do with Java? It too is cross platform but requires a >> JVM to be installed on every platform. Python is similar. >> > OK, but python need 3rd praties library, No, you can write very sophisticated Python apps using just the standard library. Equally many Java apps require 3rd party libraries. There really is no difference between the two. > and may be the the user don't know about the 3rd party libraries, > and don't know how to install it on his computer. But you can wrte an installer that installs the 3rd party libraries without compiling the script to an 'exe'. And may 'exe's require third party libraries - especially on Windows where installing an exe along with a bunch of DLLs is normal. > And not all person is programmer, so he don't want to know > about programming, he just want to use the program. They shouldn't need to know about prrogramming to run an installer. I think you are confusing an install program with a compiler. A good installer will check that Python is installed (and that it is the minimum version), install the scripts needed (including modules), install any third party libraries as needed (in other words check to see if you can find them first) and add things like help files and readme documents. Finally it should offer to place an icon/entry in the start menu or desktop or where-ever is normal for the OS. But none of that requires the application to be an executable. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Feb 11 23:09:35 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Feb 2010 22:09:35 -0000 Subject: [Tutor] SMTP References: <1265919216.8909.13.camel@dedal-laptop> Message-ID: "Grigor Kolev" wrote > I try send a mail with smtplib > Server work with postfix. > I try it > ------------------------------------------------ > import smtplib > s=smtplib.SMTP("localhost") This requires you to have an SMTP server running on localhost. Do you? I notice you say the server works with postfix but is it running when you exercise the script? Its one possibility. > tolist=['grigor.kolev at gmail.com'] > msg = '''\ > From: grigor.kolev at gmail.com > Subject: testin' > This is a test ''' > s.sendmail("test at local", tolist, msg) > ------------------------------------------------- > How can i send the file? > And I am not sure that work. > Mail is not sending but perhaps problem i in my postfix. HTH, Alan G From gtxy37 at hotmail.com Thu Feb 11 23:34:31 2010 From: gtxy37 at hotmail.com (Matthew Matson) Date: Thu, 11 Feb 2010 17:34:31 -0500 Subject: [Tutor] Algorithm for combination analysis suggestion. In-Reply-To: <1c2a2c591002111221g65f17639wa798118b5a71b6ff@mail.gmail.com> References: , <1c2a2c591002111221g65f17639wa798118b5a71b6ff@mail.gmail.com> Message-ID: Thanks Kent. I know this is confusing, perhaps if we look at it this way. Let's say A,B,C,D,E are widgets that I manufacture, now the easiest way for me to distribute them to the the unique IDs would be to gather all the widget quantities from the complete list of combinations. In this case I would need to 5 A's, 2 B's, 2 C's, 5 D's, and 1 E and assemble all of the unique IDs distributions in assembly. Putting the widgets together in assembly is expensive so I have the oppotunity in manufacturing to produce combined widgets (e.g. ('A', 'D')). The more combined widgets that I can produce in manufacturing equates to less gathering of individual widgets in assembly reducing time and cost. Because of manufacturing setup I need a significant volume of a combined widget in order to produce cost effectively hence the minimum qty threshold for that combined widget. If I have a combined widget in the combination list with a large volume we are manufacturing anyway I can just add additional qty to this at minimal cost so what I want to do is analyze all my combinations and add as many combined widgets to them as possible. If I have a combination that requires only one item from a combined widget I can add this to the combination provided that by adding this combined widget to the combination I do not add any more than one not required additonal widget to the original combination. I think this still sounds confusing - I will see if I can code up a sample of what I am trying to do. Thanks again. > Date: Thu, 11 Feb 2010 15:21:51 -0500 > Subject: Re: [Tutor] Algorithm for combination analysis suggestion. > From: kent37 at tds.net > To: gtxy37 at hotmail.com > CC: tutor at python.org > > On Thu, Feb 11, 2010 at 1:59 PM, Matthew Matson wrote: > > > > Hi Tutors, > > > > I am looking for the proper approach regarding the analysis of a dictionary > > of combinations I have. > > > > What I need to do is read from a supplied text file that has a unique ID and > > that unique ID's associated combination of elements. So let's say I have the > > following lines in a text file (real file could be millions of lines): > > > > "ID" "Elements" > > 1 'A, B, C, D' > > 2 'A, D' > > 3 'D, E' > > 4 'A, D' > > 5 'A, B' > > 6 'A, C, D' > > > > and I do something like... > > > > combinationDict = {} > > for line in file: > > data = line.split('\t') > > comb = tuple(data[1].split(',')) > > if comb not in combinationDict: > > combinationDict[comb] = 1 > > else: > > combination[comb] +=1 > > Use > combinationDict = collections.defaultdict(int) > > Then you can just write > combination[comb] += 1 > without the test for comb in combinattionDict. > > > Now after I read all of the data I end up with a dictionary with the > > combination as the key and the associated total qty as its value. > > > > print combinationDict > > {('A','B','C','D'):1, ('A','D'):2, ('D','E'):1, ('A','B'):1, ('A', 'C', > > 'D'):1} > > > > What I am looking for is a starting point for a solution in python to > > analyze the combination list so that I can determine for example that ('A', > > 'D') is the most popular combination and then determining how many other > > combinations in the dictionary contain this combination. > > maxComb = max(combinationDict, key=combinationDict.__getitem__) will > give you the single key with the largest count. > > maxCombSet = set(maxComb) > [ comb for comb in combinationDict if maxCombSet <= set(comb) ] > > will give you a list of all the combinations that contain the max > though it could be slow if you have lots of unique combinations > (because of all the set conversions). > > > I would like to incorporate some parameters so for example the combination > > ('A','B','C','D') and ('A', 'C', 'D') contain ('A','D') so they are valid > > but I could also say that as long as one element is contained in a > > combination it is valid as well provided I add no more than one additional > > item to the combination. > > Now you are starting to lose me but you can modify the conditional in > the above list comprehension to make whatever kind of test you want. > > > If I apply this logic then ('D','E') can ('A','B') > > can contain ('A', 'D') and if I apply this to the combination dictionary I > > have: > > > > {('B','C', ('A', 'D')):1, ('A','D'):2, ('E', ('A', 'D')):1, ('B', ('A', > > 'D')):1, ('C', ('A', 'D')):1} > > > > which I could then query the keys for ('A', 'D') inclusion to get a total of > > 4 for ('A', 'D'). > > Now you have lost me completely. What are the keys in this new dict? > How do you get a total of 4 fro ('A', 'D')? > > Kent > > > I hope this isn't too long and confusing but I am looking for an approach > > where I can analyze for the highest quantity of combinations and then > > iterate through the dictionary substituting those combinations that were > > determined a "highest qty" combination into other low qty combinations when > > valid. > > > > I was hoping to have parameters to qualify a high qty combination (e.g. > > every combination with qty above 10,000) with the highest quantity of that > > determined set taking precedence for substitution for the first pass then > > moving on to the next highest combination for the second pass of > > substitution etc.. The other parameter would be for the combination that > > would receive a substitution whereby I might say that I can only substitute > > if a substitution results in only one additional (superfluous) value being > > added to the combination existing low qty combination. > > > > I have looked around and this sounds like it might be similar to a packing > > problem and in particular the knapsack problem but I can't seem to wrap my > > head around an approach for this in python. I am not looking for a solution > > just some guidance on a starting point or perhaps libraries that may be > > helpful. > > > > Thank you. > > > > > > ________________________________ > > Windows? phone-your Windows stuff, on the go. See more. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > _________________________________________________________________ Introducing Windows? phone. http://go.microsoft.com/?linkid=9708122 -------------- next part -------------- An HTML attachment was scrubbed... URL: From lawrence.jones at imperial.ac.uk Thu Feb 11 23:15:14 2010 From: lawrence.jones at imperial.ac.uk (Jones, Lawrence D) Date: Thu, 11 Feb 2010 22:15:14 +0000 Subject: [Tutor] Coin flip game Message-ID: <544ED9D63633B348ADA92AC334EC98081ED3A0BACA@ICEXM4.ic.ac.uk> Hi, I'm new to the list and to Python. I'm reading through Michael Dawson's 'Python programming: for absolute beginners' and at the end of chapter 3 he's set a challenge where the reader has to create a coin flip game. My code now works, but only after I randomly switched pieces of the code around and, basically, pulled my hair out because it wouldn't work. My code is below. But can someone please explain to me why the following variable has to be placed where it is for the code to work? I thought it would need to go nearer the start of the code i.e. just before heads = 0, tails = 0 etc: coin = random.randrange(2) Also, why does the randrange integer have to be '2'? I only discovered this worked by complete accident. I tried '1' and '0,1' as my integers but they just didn't work. Thanks, Lawrence import random print "The Coin Flip Game\n" heads = 0 tails = 0 count = 0 while count < 100: coin = random.randrange(2) if coin == 0: heads = heads + 1 else: tails = tails + 1 count += 1 print "Heads: ", heads print "Tails: ", tails raw_input("\nPress enter to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From transmogribenno at gmail.com Fri Feb 12 00:16:04 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Fri, 12 Feb 2010 08:16:04 +0900 Subject: [Tutor] Coin flip game In-Reply-To: <544ED9D63633B348ADA92AC334EC98081ED3A0BACA@ICEXM4.ic.ac.uk> References: <544ED9D63633B348ADA92AC334EC98081ED3A0BACA@ICEXM4.ic.ac.uk> Message-ID: <9b00d1a91002111516hf8bfd43m766176d47ba5b93f@mail.gmail.com> On Fri, Feb 12, 2010 at 7:15 AM, Jones, Lawrence D wrote: > My code is below. But can someone please explain to me why the following > variable has to be placed where it is for the code to work? I thought it > would need to go nearer the start of the code i.e. just before heads = 0, > tails = 0 etc: > ??????????????? coin = random.randrange(2) If you put this at the start of the code (before the loop), then you only flip the coin once, and then count that single flip 100 times. That would work, but wouldn't be a very useful program. > Also, why does the randrange integer have to be ?2?? I only discovered this > worked by complete accident. I tried ?1? and ?0,1? as my integers but they > just didn?t work. See: http://docs.python.org/library/random.html#random.randrange random.randrange parameters are the same as for range, which you can learn more about here: http://docs.python.org/tutorial/controlflow.html#the-range-function HTH, benno From ldl08 at gmx.net Fri Feb 12 01:49:47 2010 From: ldl08 at gmx.net (David) Date: Fri, 12 Feb 2010 08:49:47 +0800 Subject: [Tutor] Coin flip game In-Reply-To: <544ED9D63633B348ADA92AC334EC98081ED3A0BACA@ICEXM4.ic.ac.uk> References: <544ED9D63633B348ADA92AC334EC98081ED3A0BACA@ICEXM4.ic.ac.uk> Message-ID: <4B74A5AB.8050406@gmx.net> Hello Lawrence, let me try to clarify this (warning: am a beginner myself). On 12/02/10 06:15, Jones, Lawrence D wrote: > Hi, > > I'm new to the list and to Python. I'm reading through Michael Dawson's 'Python programming: for absolute beginners' and at the end of chapter 3 he's set a challenge where the reader has to create a coin flip game. My code now works, but only after I randomly switched pieces of the code around and, basically, pulled my hair out because it wouldn't work. > > My code is below. But can someone please explain to me why the following variable has to be placed where it is for the code to work? I thought it would need to go nearer the start of the code i.e. just before heads = 0, tails = 0 etc: > > coin = random.randrange(2) Python runs through your code, step by step. I believe it starts at the top and goes down, following the logic of your code. When you make Python refer to a variable in your while loop that Python has not encountered yet, then it will not know what to do -- and complain about it. Solution: let Python know of the variable _before_ you then start to work with it. > > Also, why does the randrange integer have to be '2'? I only discovered this worked by complete accident. I tried '1' and '0,1' as my integers but they just didn't work. That is because your coin has _two_ sides, and you therefore want a random choice out of _two_ possibilities. With the random.randrange(2) function the choices will be 0 and 1, satisfying your demands. This means that the randrange() function goes up to, but not including, the integer you supply. It amounts to two choices in the end all the same because the counting starts with 0 instead of 1. That is, if you chose randrange(1) you will get only one answer, namely 0. If you type randrange(0) then you will get an error message (ValueError: empty range for randrange). Which makes sense. Remember, randrange() goes up to, but not including the integer supplied. HTH, David > > Thanks, > > Lawrence > > > import random > print "The Coin Flip Game\n" > > heads = 0 > tails = 0 > count = 0 > > while count< 100: > coin = random.randrange(2) > if coin == 0: > heads = heads + 1 > else: > tails = tails + 1 > count += 1 > > print "Heads: ", heads > print "Tails: ", tails > > raw_input("\nPress enter to exit.") > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Feb 12 02:04:26 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Feb 2010 01:04:26 -0000 Subject: [Tutor] Coin flip game References: <544ED9D63633B348ADA92AC334EC98081ED3A0BACA@ICEXM4.ic.ac.uk> Message-ID: "Jones, Lawrence D" wrote > My code is below. But can someone please explain to me > why the following variable has to be placed where it is Others have explained about variable creation and the fact you need to be inside the loop to get different results for each iteration. coin = random.randrange(2) I just want to pick up on something you said. You asked about the "variable". The variable is "coin". It can go anywhere before the point of use, even the first line of your code. You could have done coin = None or coin = 0 and it would work just fine. What needs to be inside the loop is the call to the randrange() function. That is what is simulating the coin flip. So you need to distinguish the difference between variable creation (which in Python happens by means of the first assignment of a value) and function application (where you call a function and assign its return value to a variable.) In your code you create the variable coin at the same time as you apply the function, but you could have done those two things separately and the code would still work. It might seem like I'm splitting hairs but it starts to make a difference in some other cases, like this: while True: coin = coin + someFunction() This will raise an error because you are using the value of coin (on the right hand side) before it has been created. You need to write it like this: coin = 0 while True coin = coin + someFunction() It is very important in programming to be clear in your mind about these different concepts, especially when deciphering error messages. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jlintz at gmail.com Fri Feb 12 06:15:33 2010 From: jlintz at gmail.com (Justin Lintz) Date: Fri, 12 Feb 2010 00:15:33 -0500 Subject: [Tutor] Simple Stats on Apache Logs In-Reply-To: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> References: <9f92935c1002110156u5692bc48s4760413abd6f061b@mail.gmail.com> Message-ID: <99edfc5e1002112115t4f887756vd0b4fbc0e718d947@mail.gmail.com> On Thu, Feb 11, 2010 at 4:56 AM, Lao Mao wrote: > Hi, > > I have 3 servers which generate about 2G of webserver logfiles in a day. > These are available on my machine over NFS. > > I would like to draw up some stats which shows, for a given keyword, how > many times it appears in the logs, per hour, over the previous week. > > So the behavior might be: > > $ ./webstats --keyword downloader > > Which would read from the logs (which it has access to) and produce > something like: > > Monday: > 0000: 12 > 0100: 17 > > etc > > I'm not sure how best to get started.? My initial idea would be to filter > the logs first, pulling out the lines with matching keywords, then check the > timestamp - maybe incrementing a dictionary if the logfile was within a > certain time? > > I'm not looking for people to write it for me, but I'd appreciate some > guidance as the the approach and algorithm.? Also what the simplest > presentation model would be.? Or even if it would make sense to stick it in > a database!? I'll post back my progress. > > Thanks, > > Laomao > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You may also find this link useful http://effbot.org/zone/wide-finder.htm on parsing logs efficiently using Python. From alan.gauld at btinternet.com Fri Feb 12 10:34:41 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Feb 2010 09:34:41 -0000 Subject: [Tutor] New Python testing book Message-ID: Amazon have just brought to my attention the following title: Python Testing: Beginner's Guide Has anyone seen this? Is it any good? What test frameworks does it cover? Amazon are remarkably reticent about the actual contents. Its very new, only published on 22nd January. Alan G. From ldl08 at gmx.net Fri Feb 12 11:26:36 2010 From: ldl08 at gmx.net (David) Date: Fri, 12 Feb 2010 18:26:36 +0800 Subject: [Tutor] New Python testing book In-Reply-To: References: Message-ID: <4B752CDC.1060707@gmx.net> Hi Alan, On 12/02/10 17:34, Alan Gauld wrote: > Amazon are remarkably reticent about the actual contents. See here: http://tinyurl.com/y9dy62p I am, btw, always happy to see 'book announcements' on this list -- keep them coming! David From onyxtic at gmail.com Fri Feb 12 11:35:16 2010 From: onyxtic at gmail.com (Evans Anyokwu) Date: Fri, 12 Feb 2010 10:35:16 +0000 Subject: [Tutor] New Python testing book In-Reply-To: <4B752CDC.1060707@gmx.net> References: <4B752CDC.1060707@gmx.net> Message-ID: On Fri, Feb 12, 2010 at 10:26 AM, David wrote: > Hi Alan, > > > On 12/02/10 17:34, Alan Gauld wrote: > > Amazon are remarkably reticent about the actual contents. >> > See here: http://tinyurl.com/y9dy62p > > I am, btw, always happy to see 'book announcements' on this list -- keep > them coming! > > David For those who don't like shortened URL, here's the actual link http://www.packtpub.com/view_popup/page/python-testing-beginners-guide-table-of-contents It's just the Table of Content and nothing else. -- Evans > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Fri Feb 12 12:12:52 2010 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 12 Feb 2010 03:12:52 -0800 (PST) Subject: [Tutor] Coin flip game In-Reply-To: <4B74A5AB.8050406@gmx.net> Message-ID: <913294.57511.qm@web110716.mail.gq1.yahoo.com> Hi, random.choice offers an intuitive way to write the code: import random for i in range(10): ??? print random.choice(["head", "tail"]) Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the face of ambiguity, refuse the temptation to guess. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- On Fri, 2/12/10, David wrote: From: David Subject: Re: [Tutor] Coin flip game To: tutor at python.org Date: Friday, February 12, 2010, 1:49 AM Hello Lawrence, let me try to clarify this (warning: am a beginner myself). On 12/02/10 06:15, Jones, Lawrence D wrote: > Hi, > > I'm new to the list and to Python. I'm reading through Michael Dawson's 'Python programming: for absolute beginners' and at the end of chapter 3 he's set a challenge where the reader has to create a coin flip game. My code now works, but only after I randomly switched pieces of the code around and, basically, pulled my hair out because it wouldn't work. > > My code is below. But can someone please explain to me why the following variable has to be placed where it is for the code to work? I thought it would need to go nearer the start of the code i.e. just before heads = 0, tails = 0 etc: > >? ? ? ? ? ? ? ? ? coin = random.randrange(2) Python runs through your code, step by step. I believe it starts at the top and goes down, following the logic of your code. When you make Python refer to a variable in your while loop that Python has not encountered yet, then it will not know what to do -- and complain about it. Solution: let Python know of the variable _before_ you then start to work with it. > > Also, why does the randrange integer have to be '2'? I only discovered this worked by complete accident. I tried '1' and '0,1' as my integers but they just didn't work. That is because your coin has _two_ sides, and you therefore want a random choice out of _two_ possibilities. With the random.randrange(2) function the choices will be 0 and 1, satisfying your demands. This means that the randrange() function goes up to, but not including, the integer you supply. It amounts to two choices in the end all the same because the counting starts with 0 instead of 1. That is, if you chose randrange(1) you will get only one answer, namely 0. If you type randrange(0) then you will get an error message (ValueError: empty range for randrange). Which makes sense. Remember, randrange() goes up to, but not including the integer supplied. HTH, David > > Thanks, > > Lawrence > > > import random > print "The Coin Flip Game\n" > > heads = 0 > tails = 0 > count = 0 > > while count? ? ? coin = random.randrange(2) >? ? ? if coin == 0: >? ? ? ? ? heads = heads + 1 >? ? ? else: >? ? ? ? ? tails = tails + 1 >? ? ? count += 1 > > print "Heads: ", heads > print "Tails: ", tails > > raw_input("\nPress enter to exit.") > > > > > > > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Fri Feb 12 16:33:04 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 12 Feb 2010 16:33:04 +0100 Subject: [Tutor] Tutor list as pair progamming plush toy Message-ID: <1265988784.21902.10.camel@jabbar> Have you ever got that piece of advice about - when you have stuck on a bug you seem unable to track - getting a plush toy to whom you explain your code? (This is of course a workaround if you do not have a fellow developer to help you out). Well... I found out this advice kind of works for me, with the notable difference that my plush toy is this mailing list. It works so wonderfully that indeed is several months I do not post any message: whenever I get stuck, I begin to write a message to the list, and in the process of explaining what is the intended behaviour and outcome of my code, I systematically find the bug by myself. I know - this is slightly OT for the list - but I thought to share as maybe this is a "hidden benefit" the list is bringing to a few people without the tutors even knowing it. Does anybody else experience the same? Cheers, :) Mac. From zstumgoren at gmail.com Fri Feb 12 17:05:30 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 12 Feb 2010 11:05:30 -0500 Subject: [Tutor] Tutor list as pair progamming plush toy In-Reply-To: <1265988784.21902.10.camel@jabbar> References: <1265988784.21902.10.camel@jabbar> Message-ID: In similar vein, I find that a concept suddenly makes more sense to me when I try to explain it to someone else (or I realize that I don't fully understand and need to do some more research). But with regard to the plush toy you mention, I just ran into that anecdote in Coders at Work. Can't recall off the top of my head which developer mentioned it, but it's an interesting concept. Btw, I'd recommend that book to anyone interested in expanding their horizons on coding philosophies and methodologies. Some of it's pretty high-brow comp sci discussion, but there's a lot about basic testing and debugging approaches, and how one should go about reading someone else's code. I'm only half-way through the book, but the variety of responses and approaches is fascinating. Serdar -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mike.Hansen at atmel.com Fri Feb 12 17:55:59 2010 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Fri, 12 Feb 2010 09:55:59 -0700 Subject: [Tutor] Tutor list as pair progamming plush toy In-Reply-To: <1265988784.21902.10.camel@jabbar> References: <1265988784.21902.10.camel@jabbar> Message-ID: <7941B2693F32294AAF16C26B679A258D0ECC3CF5@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces+mike.hansen=atmel.com at python.org > [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On > Behalf Of Mac Ryan > Sent: Friday, February 12, 2010 8:33 AM > To: tutor at python.org > Subject: [Tutor] Tutor list as pair progamming plush toy > > Have you ever got that piece of advice about - when you have > stuck on a > bug you seem unable to track - getting a plush toy to whom you explain > your code? (This is of course a workaround if you do not have a fellow > developer to help you out). > > Well... I found out this advice kind of works for me, with the notable > difference that my plush toy is this mailing list. It works so > wonderfully that indeed is several months I do not post any message: > whenever I get stuck, I begin to write a message to the list, > and in the > process of explaining what is the intended behaviour and outcome of my > code, I systematically find the bug by myself. > > I know - this is slightly OT for the list - but I thought to share as > maybe this is a "hidden benefit" the list is bringing to a few people > without the tutors even knowing it. > > Does anybody else experience the same? > > Cheers, :) > Mac. > This kind of sounds like the rubber duck method of debugging. http://lists.ethernal.org/oldarchives/cantlug-0211/msg00174.html Mike From waynejwerner at gmail.com Fri Feb 12 17:58:15 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 12 Feb 2010 10:58:15 -0600 Subject: [Tutor] Tutor list as pair progamming plush toy In-Reply-To: References: <1265988784.21902.10.camel@jabbar> Message-ID: <333efb451002120858u1d5c6603j2edc4249ae01026a@mail.gmail.com> I've discovered that same thing. Usually I end out not sending my message because in the process of composing my email I end out I, too, find the errors. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kp8 at mac.com Fri Feb 12 17:22:42 2010 From: kp8 at mac.com (kevin parks) Date: Sat, 13 Feb 2010 01:22:42 +0900 Subject: [Tutor] batch file processing w/ python using cmd line executable? Message-ID: hi I am new territory here and not even sure where to start poking around other than the os module some. Essentially i need to do something like a shell script for batch processing gobs of files. I am trying to use a command line tool (sox, an open source sound file converter that runs from the unix command line) and I don't want to edit the command line, run the job, edit the command line, etc over and over again for hundreds of small files. I wonder if it is possible to use python to call sox and have it do os.mkdir, process all the input files in a particular directory and put the converted files into the directory it made with mkdir... so if i had kp/flute/ST kp8/flute/ST/foo01.aif kp8/flute/ST/foo02.aif kp8/flute/ST/foo03.aif kp8/flute/ST/foo04.aif kp8/flute/ST/foo05.aif The script would call sox repeatedly and create a new dir with a converted file for each found in the original folder. like so: kp/flute/STout/ kp/flute/STout/foo01.wav kp/flute/STout/foo02.wav kp/flute/STout/foo03.wav kp/flute/STout/foo04.wav kp/flute/STout/foo05.wav what makes this especially hairy is that sox is a monster an typically needs a crazy number of arguments, though these would be the same for the whole batch. A typical command line call i need to make to, say, batch convert files from one sample rate and bit depth to another would look like so: % sox -V3 -D -S St.01.aif -b16 kp/flute/STout/St.01.wav rate -s -v 44100 Is there away to do this in python, by just pointing it to a whole dir of files and say "do it" to all of these? cheers, kevin From grflanagan at gmail.com Fri Feb 12 19:35:10 2010 From: grflanagan at gmail.com (Gerard Flanagan) Date: Fri, 12 Feb 2010 18:35:10 +0000 Subject: [Tutor] Algorithm for combination analysis suggestion. In-Reply-To: References: Message-ID: Matthew Matson wrote: > > Hi Tutors, > > I am looking for the proper approach regarding the analysis of a > dictionary of combinations I have. > > What I need to do is read from a supplied text file that has a unique ID > and that unique ID's associated combination of elements. So let's say I > have the following lines in a text file (real file could be millions of > lines): > > "ID" "Elements" > 1 'A, B, C, D' > 2 'A, D' > 3 'D, E' > 4 'A, D' > 5 'A, B' > 6 'A, C, D' > > and I do something like... > > combinationDict = {} > for line in file: > data = line.split('\t') > comb = tuple(data[1].split(',')) > if comb not in combinationDict: > combinationDict[comb] = 1 > else: > combination[comb] +=1 > > Now after I read all of the data I end up with a dictionary with the > combination as the key and the associated total qty as its value. > > print combinationDict > {('A','B','C','D'):1, ('A','D'):2, ('D','E'):1, ('A','B'):1, ('A', 'C', > 'D'):1} > > What I am looking for is a starting point for a solution in python to > analyze the combination list so that I can determine for example that > ('A', 'D') is the most popular combination and then determining how many > other combinations in the dictionary contain this combination. > > I would like to incorporate some parameters so for example the > combination ('A','B','C','D') and ('A', 'C', 'D') contain ('A','D') so > they are valid but I could also say that as long as one element is > contained in a combination it is valid as well provided I add no more > than one additional item to the combination. If I apply this logic then > ('D','E') can ('A','B') can contain ('A', 'D') and if I apply this to > the combination dictionary I have: > > {('B','C', ('A', 'D')):1, ('A','D'):2, ('E', ('A', 'D')):1, ('B', ('A', > 'D')):1, ('C', ('A', 'D')):1} > > which I could then query the keys for ('A', 'D') inclusion to get a > total of 4 for ('A', 'D'). > > I hope this isn't too long and confusing but I am looking for an > approach where I can analyze for the highest quantity of combinations > and then iterate through the dictionary substituting those combinations > that were determined a "highest qty" combination into other low qty > combinations when valid. > > I was hoping to have parameters to qualify a high qty combination (e.g. > every combination with qty above 10,000) with the highest quantity of > that determined set taking precedence for substitution for the first > pass then moving on to the next highest combination for the second pass > of substitution etc.. The other parameter would be for the combination > that would receive a substitution whereby I might say that I can only > substitute if a substitution results in only one additional > (superfluous) value being added to the combination existing low qty > combination. > > I have looked around and this sounds like it might be similar to a > packing problem and in particular the knapsack problem but I can't seem > to wrap my head around an approach for this in python. I am not looking > for a solution just some guidance on a starting point or perhaps > libraries that may be helpful. > > Thank you. > > Hey, never heard of commas! I'm out of breath after that ;-) It sounds something like Linear Programming - not that I know much about it, but maybe asking on other lists, eg. scipy, might turn up some kind of standard approach to this kind of problem. One idea for the 'is a combination contained in another combination' issue is using bitmasks. Create a bitmask for each combination, then C1 is a component of C2 if C1 & C2 == C1. (Hope i've got that right!) Some code doodling below shows the idea. Regards G.F. ----------------------------------------------------- from collections import defaultdict data = """ 1 A, B, C, D 2 A, D 3 D, E 4 A, D 5 A, B 6 A, C, D 7 E """.splitlines() atoms = {} key2mask = {} mask2key = {} combos = defaultdict(int) for line in data: if line: key = '' mask = 0 for atom in line[5:].split(','): atom = atom.strip() key += atom mask |= atoms.setdefault(atom, 1 << len(atoms)) key2mask[key] = mask mask2key[mask] = key combos[mask] += 1 for combo in ['AB', 'AD', 'DE', 'E']: mask = key2mask[combo] print for c in combos.iterkeys(): if mask & c == mask: print '%s is a component of %s' % (combo, mask2key[c]) print 'there are %s %ss' % (combos[mask], combo) ------------------------------------------------------ def xuniqueCombinations(items, n): if n==0: yield [] else: for i in xrange(len(items)): for cc in xuniqueCombinations(items[i+1:],n-1): yield [items[i]]+cc def allcombos(): for k in range(1,6): for c in xuniqueCombinations('ABCDE', k): yield c ------------------------------------------------------- From dwightdhutto at yahoo.com Fri Feb 12 19:40:20 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Fri, 12 Feb 2010 10:40:20 -0800 (PST) Subject: [Tutor] Tutor list as pair progamming plush toy In-Reply-To: <7941B2693F32294AAF16C26B679A258D0ECC3CF5@csomb01.corp.atmel.com> Message-ID: <253553.41844.qm@web45303.mail.sp1.yahoo.com> --- On Fri, 2/12/10, Hansen, Mike wrote: From: Hansen, Mike Subject: Re: [Tutor] Tutor list as pair progamming plush toy To: tutor at python.org Date: Friday, February 12, 2010, 11:55 AM > -----Original Message----- > From: tutor-bounces+mike.hansen=atmel.com at python.org > [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On > Behalf Of Mac Ryan > Sent: Friday, February 12, 2010 8:33 AM > To: tutor at python.org > Subject: [Tutor] Tutor list as pair progamming plush toy > > Have you ever got that piece of advice about - when you have > stuck on a > bug you seem unable to track - getting a plush toy to whom you explain > your code? (This is of course a workaround if you do not have a fellow > developer to help you out). > > Well... I found out this advice kind of works for me, with the notable > difference that my plush toy is this mailing list. It works so > wonderfully that indeed is several months I do not post any message: > whenever I get stuck, I begin to write a message to the list, > and in the > process of explaining what is the intended behaviour and outcome of my > code, I systematically find the bug by myself. > > I know - this is slightly OT for the list - but I thought to share as > maybe this is a "hidden benefit" the list is bringing to a few people > without the tutors even knowing it. > > Does anybody else experience the same? > > Cheers, :) > Mac. > +1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 12 20:54:27 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Feb 2010 19:54:27 -0000 Subject: [Tutor] Tutor list as pair progamming plush toy References: <1265988784.21902.10.camel@jabbar> Message-ID: "Mac Ryan" wrote > I know - this is slightly OT for the list - but I thought to share as > maybe this is a "hidden benefit" the list is bringing to a few people > without the tutors even knowing it. Actually I think it is bang on topic. One of the most common benefits of any online community is the way we are foced to think about propblems to write them down. Doing so ioften brings new solutions to mind. In fact I often find solutioons to my own problems while replying to others! - even on seemingly unrelated issues :-) And of course if the solution doesn't come you have the 2nd level support option of actually posting and getting replies! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Feb 12 21:00:42 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Feb 2010 20:00:42 -0000 Subject: [Tutor] batch file processing w/ python using cmd line executable? References: Message-ID: "kevin parks" wrote > I wonder if it is possible to use python to call sox and have it do > os.mkdir, process all the input files in a particular directory and > put the converted files into the directory it made with mkdir... Of course. What do you perceive to be the problem? This would just be a standard loop or os.walk call. > The script would call sox repeatedly and create a new dir with a > converted file for each found in the original folder. like so: Presumably a new dir for each dir found? Thus mirroring the source structure? Thats easily done with os.walk and would be a good place to start writing the script. Calling sox can be done using the subprocess module. > what makes this especially hairy is that sox is a monster an typically > needs a crazy number of arguments, though these would be the same for > the whole batch. So store them in a list and apply them to each call. subprocess makes this easy. > % sox -V3 -D -S St.01.aif -b16 kp/flute/STout/St.01.wav rate -s -v > 44100 > > Is there away to do this in python, by just pointing it to a whole dir > of files and say "do it" to all of these? I'd check out os.walk and subprocess. Both are discussed in the Using the OS topic in my tutorial. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From marky1991 at gmail.com Sat Feb 13 00:41:09 2010 From: marky1991 at gmail.com (Mark Young) Date: Fri, 12 Feb 2010 18:41:09 -0500 Subject: [Tutor] Defining operators for custom types Message-ID: I created a custom vector type, inheriting from object, and defined __mul__, __add__, etc. Unfortunately, the operators only work if I type "vector * (int/float/number)", in that exact order. My program produces an error if I instead type "number * vector". This makes sense to me, because I haven't told the number (int, float, whatever) how to deal with an object of type vector, (At least, I think that's why it doesn't work.). Is there any way to allow "number (operator) vector", short of modifying the standard types' behavior? Here's an example of the error. vec1 = vector(5,6,7) >>> vec1 * 2 (10, 12, 14) >>> 2 * vec1 Traceback (most recent call last): File "", line 1, in 2 * vec1 TypeError: unsupported operand type(s) for *: 'int' and 'vector' I'm using python 3.1. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Feb 13 01:11:13 2010 From: bgailer at gmail.com (bob gailer) Date: Fri, 12 Feb 2010 19:11:13 -0500 Subject: [Tutor] Defining operators for custom types In-Reply-To: References: Message-ID: <4B75EE21.8010208@gmail.com> Mark Young wrote: > I created a custom vector type, inheriting from object, and defined > __mul__, __add__, etc. Unfortunately, the operators only work if I > type "vector * (int/float/number)", in that exact order. My program > produces an error if I instead type "number * vector". Use __rmul__, __radd__, etc. > This makes sense to me, because I haven't told the number (int, float, > whatever) how to deal with an object of type vector, (At least, I > think that's why it doesn't work.). Is there any way to allow > "number (operator) vector", short of modifying the standard types' > behavior? > > Here's an example of the error. > vec1 = vector(5,6,7) > >>> vec1 * 2 > (10, 12, 14) > >>> 2 * vec1 > Traceback (most recent call last): > File "", line 1, in > 2 * vec1 > TypeError: unsupported operand type(s) for *: 'int' and 'vector' > > I'm using python 3.1. > Thanks. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 919-636-4239 Chapel Hill NC From marky1991 at gmail.com Sat Feb 13 01:19:36 2010 From: marky1991 at gmail.com (Mark Young) Date: Fri, 12 Feb 2010 19:19:36 -0500 Subject: [Tutor] Defining operators for custom types In-Reply-To: <4B75EE21.8010208@gmail.com> References: <4B75EE21.8010208@gmail.com> Message-ID: Thanks for the help. That's exactly the kind of solution I wanted. I've been to that page several times already, but just ignored that section apparently. Thanks alot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From garry.willgoose at newcastle.edu.au Sat Feb 13 00:51:38 2010 From: garry.willgoose at newcastle.edu.au (Garry Willgoose) Date: Sat, 13 Feb 2010 10:51:38 +1100 Subject: [Tutor] aliasing an imported module Message-ID: <0A04999D-5173-4355-A1E6-1BAD757DC2BD@newcastle.edu.au> I want to be able to import multiple instances of a module and call each by a unique name and it doesn't appear at first glance that either import or __import__ have what I need. I need this because of computing platform I have developed where users write python scripts to do some analysis of science problems where they call modules that have code for monipulating data and where the imported module does some specific scientfic manipulation of data. The key problem is that the module might locally store some partial results ready for the next time its called to save CPU time (typically the results for one timestep ready for the next timestep). But if the module is called for two different purposes in two different parts of the script then the second call will actually see the partial results from the 1st call and vice versa. The simple solution is if it were possible to import the same module file twice but for them to act like they were different modules. It was also make it easy to parallelise code without the called module needing to be thread safe (each instance would be one thread) but that is a lesser priority for the moment. If I have module in a file called stuff.py has in it a global variable somevariable I want to be able to import multiple instance (with seperate name spaces etc) of stuff so that I could have for example a=instance1ofstuff.somevariable b=instance2ofstuff.somevariable and a and b are referring to different variables in entirely different modules. IS there any way to do this? ==================================================================== Prof Garry Willgoose, Australian Professorial Fellow in Environmental Engineering, Director, Centre for Climate Impact Management (C2IM), School of Engineering, The University of Newcastle, Callaghan, 2308 Australia. Centre webpage: www.c2im.org.au Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574 (Fri PM-Mon) FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal and Telluric) Env. Engg. Secretary: (International) +61 2 4921 6042 email: garry.willgoose at newcastle.edu.au; g.willgoose at telluricresearch.com email-for-life: garry.willgoose at alum.mit.edu personal webpage: www.telluricresearch.com/garry ==================================================================== "Do not go where the path may lead, go instead where there is no path and leave a trail" Ralph Waldo Emerson ==================================================================== From alan.gauld at btinternet.com Sat Feb 13 02:57:30 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Feb 2010 01:57:30 -0000 Subject: [Tutor] aliasing an imported module References: <0A04999D-5173-4355-A1E6-1BAD757DC2BD@newcastle.edu.au> Message-ID: "Garry Willgoose" wrote >I want to be able to import multiple instances of a module and call each >by a unique name and it doesn't appear at first glance that either import >or __import__ have what I need. No because it would be bad practice. Stateful modules lead to hard to debug prolems. > computing platform I have developed where users write python scripts to > do some analysis of science problems where they call modules that have > code for monipulating data and where the imported module does some > specific scientfic manipulation of data. The key problem is that the > module might locally store some partial results ready for the next time > its called to save CPU time This is where classes come in. You can define a class in your module with the analysis done in a method and have it store the results in instance variables. Then you can either call another method which can access those variables or you can create another instance of the class with its own independant copies of its values. > But if the module is called for two different purposes in two different > parts of the script then the second call will actually see the partial > results from the 1st call and vice versa. Technically you don't call a module you import it which has the side-effect of executing the code in the module. In a well structured module the code should really be inside function definitions so that nothing haoppens until you call the modules functions. importing modules as a way of executing the code within them is not good practice. > The simple solution is if it were possible to import the same module > file twice but for them to act like they were different modules. It was > also make it easy to parallelise code without the called module needing > to be thread safe (each instance would be one thread) but that is a > lesser priority for the moment. Again classes can do that for you. Either by having two instances of the class in a single thread and multiplexing the calls to their methods (round-robin style) or, if necessary, by having two instances each in their own thread executing independantly. > If I have module in a file called stuff.py has in it a global variable > somevariable I want to be able to import multiple instance (with > seperate name spaces etc) of stuff so that I could have for example > > a=instance1ofstuff.somevariable > b=instance2ofstuff.somevariable With a class that becomes: import stuff a = stuff.myClass() b = stuff.myClass() a.myFunction(x,y,z) b.myFunction(a,b,c) print a.myvar, b.myvar etc. > and a and b are referring to different variables in entirely different > modules. IS there any way to do this? a and b refer to independant instances of the same class each with its own myvar variable inside. See the OOP topic of my tutorial for more on Object Oriented Programming HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From randyeraymond at mchsi.com Sat Feb 13 03:30:15 2010 From: randyeraymond at mchsi.com (Randy Raymond) Date: Fri, 12 Feb 2010 20:30:15 -0600 Subject: [Tutor] Just a Note Message-ID: <5323715525EA4925A05B0EF6E0A94AF3@RandyPC> By the way, Alan Gauld's emails generate an error in my system. His is the only emails I have a problem with so far. At first it tried to open a News service. Randy Raymond -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sat Feb 13 03:40:12 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 12 Feb 2010 20:40:12 -0600 Subject: [Tutor] Just a Note In-Reply-To: <5323715525EA4925A05B0EF6E0A94AF3@RandyPC> References: <5323715525EA4925A05B0EF6E0A94AF3@RandyPC> Message-ID: This doesn't make any sense. What do you mean "tries to open up a news service"? When you read the e-mail? What system are you using? On Fri, Feb 12, 2010 at 8:30 PM, Randy Raymond wrote: > By the way, Alan Gauld's emails generate an error in my system. His is > the only emails I have a problem with so far. At first it tried to open a > News service. > > Randy Raymond > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Feb 13 04:55:43 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 12 Feb 2010 19:55:43 -0800 Subject: [Tutor] The Order of Imports and install order of modules and other matters (XP vs W7, ...) Message-ID: <4B7622BF.9000408@sbcglobal.net> There seems to be something of a general consensus in ordering import statements. Something like standard library imports first. When using tools like matlablib or tkinter (maybe), must one keep an order among the relevant imports? Related to this is the order in which modules are installed. Does it make a difference? Finally, I'm in the process of moving Python code from XP to Win7. I just grabbed all the install files I have from XP, and executed them on W7. Everything seems to be working as expected, but one strange thing happened with scipy. It produced a warning about something like "unable to provide key". I continued anyway. All seems well. Was I supposed to use some W7 version of the "XP" files? This is anomaly 1. OK, this the last one. In both XP and W7, I've found executing a program by use of the py file (not IDLE. Is there a name for this method?) using numpy that see early on in the DOS-like window (is there name for it too?) it's complaining (alerting me) about deprecations and some use of a numpy test. What's that about? This is anomaly 2. -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From eduardo.susan at gmail.com Sat Feb 13 05:49:15 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 12 Feb 2010 21:49:15 -0700 Subject: [Tutor] Not understanding this code example. Help, please. Message-ID: <9356b9f31002122049w5cde73cbqb8c1f231367bd15a@mail.gmail.com> Hello! I was reading the latest version of Mark Pilgrim's "Dive into Python" and am confused with these example about the pluralization rules. See http://diveintopython3.org/examples/plural3.py and http://diveintopython3.org/generators.html#a-list-of-patterns Here is part of the code: import re def build_match_and_apply_functions(pattern, search, replace): def matches_rule(word): return re.search(pattern, word) def apply_rule(word): return re.sub(search, replace, word) return (matches_rule, apply_rule) patterns = \ ( ('[sxz]$', '$', 'es'), ('[^aeioudgkprt]h$', '$', 'es'), ('(qu|[^aeiou])y$', 'y$', 'ies'), ('$', '$', 's') ) rules = [build_match_and_apply_functions(pattern, search, replace) for (pattern, search, replace) in patterns] def plural(noun): for matches_rule, apply_rule in rules: if matches_rule(noun): return apply_rule(noun) this example works on IDLE: print plural("baby") My question is "baby" assigned to "word" in the inner function? It's a little mind bending for me... Thanks, Eduardo From alan.gauld at btinternet.com Sat Feb 13 10:18:57 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Feb 2010 09:18:57 -0000 Subject: [Tutor] Just a Note References: <5323715525EA4925A05B0EF6E0A94AF3@RandyPC> Message-ID: "Randy Raymond" wrote > By the way, Alan Gauld's emails generate an error in my system. > His is the only emails I have a problem with so far. > At first it tried to open a News service. Interesting. I am using the gmane news server but I've not heard of anyone else having problems. Is there anyone else? Alan G. From alan.gauld at btinternet.com Sat Feb 13 10:27:42 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Feb 2010 09:27:42 -0000 Subject: [Tutor] Not understanding this code example. Help, please. References: <9356b9f31002122049w5cde73cbqb8c1f231367bd15a@mail.gmail.com> Message-ID: "Eduardo Vieira" wrote > def build_match_and_apply_functions(pattern, search, replace): > def matches_rule(word): > return re.search(pattern, word) > def apply_rule(word): > return re.sub(search, replace, word) > return (matches_rule, apply_rule) > > patterns = \ > ( > ('[sxz]$', '$', 'es'), > ('[^aeioudgkprt]h$', '$', 'es'), > ('(qu|[^aeiou])y$', 'y$', 'ies'), > ('$', '$', 's') > ) > rules = [build_match_and_apply_functions(pattern, search, replace) > for (pattern, search, replace) in patterns] > > def plural(noun): > for matches_rule, apply_rule in rules: > if matches_rule(noun): > return apply_rule(noun) > > My question is "baby" assigned to "word" in the inner function? It's a > little mind bending for me... Yes. rules is a list comprehension that builds a list of 3 pairs of functions. These functions are returned from the first function above. Those functions both take a word as an argument. in plural it iterates over these pairs of functions and applies noun as the argument to both functtions, so noun gets applied as the word parameter to both functions. And yes it is a little mind bending and there are more straighforward ways to code it, but they require more code and don't show off the use of higher order functions. It depends on what the book is actually trying to explain here whether this approach is sensible or not. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Feb 13 10:33:01 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Feb 2010 09:33:01 -0000 Subject: [Tutor] The Order of Imports and install order of modules and other matters (XP vs W7, ...) References: <4B7622BF.9000408@sbcglobal.net> Message-ID: "Wayne Watson" wrote > There seems to be something of a general consensus in ordering import > statements. Something like standard library imports first. I've never seen anything written down but its true I tend to do that. But its not been a conscious thing... > tools like matlablib or tkinter (maybe), must one keep an order among > the relevant imports? The order can be significant, especially if the module code has executable statements in it or there are dependencies between them. But with well written modules it should not matter provided you use the straightforward import m style. It will matter if you use the from m import * method though, because of likely name collisions. > Related to this is the order in which modules are installed. Does it > make a difference? Again it shouldn't but if the installer for one relies on another (eg a GUI library) then it will. > Finally, I'm in the process of moving Python code from XP to Win7. I Sorry, I know nothing of W7... :-) Alan G From pythonnewbie6 at gmail.com Sat Feb 13 13:21:43 2010 From: pythonnewbie6 at gmail.com (Chris Patillo) Date: Sat, 13 Feb 2010 06:21:43 -0600 Subject: [Tutor] json file Message-ID: <5f3def2d1002130421q4115c300ic2e38f9726a2c1f@mail.gmail.com> I need to read in a .json file and write out a file with some of the information from this file. I can't figure out how to read the .json file in. I know there is a module for this, but I don't understand how it works. The file I am needing to read is like below (except much much larger) { "table":"contacts", "records":[ { "name":"John", "phone":"555-555-4444" }, { "name":"Jane", "phone":"555-555-3333" }, ] } I have no clue how to do this. I was thinking something like; import json json.dumps([name,phone], seperators(":")) Would something like this even remotely stand a chance of working? If not can someone explain the json module to me in a way that is easy to understand? All my past experience has been in reading ism files in a different language - I've never read a java file before and haven't done much python coding either. If this statement would work, then how do I get it to give me the data for one record at a time so I can then move it to another file? I would really appreciate any help I could get with this. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 13 15:59:00 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Feb 2010 09:59:00 -0500 Subject: [Tutor] Not understanding this code example. Help, please. In-Reply-To: <9356b9f31002122049w5cde73cbqb8c1f231367bd15a@mail.gmail.com> References: <9356b9f31002122049w5cde73cbqb8c1f231367bd15a@mail.gmail.com> Message-ID: <1c2a2c591002130659h4e3f40cfh5cc304f5c53397e4@mail.gmail.com> On Fri, Feb 12, 2010 at 11:49 PM, Eduardo Vieira wrote: > Hello! I was reading the latest version of Mark Pilgrim's "Dive into > Python" and am confused with these example about the pluralization > rules. See http://diveintopython3.org/examples/plural3.py and > http://diveintopython3.org/generators.html#a-list-of-patterns > Here is part of the code: > import re > > def build_match_and_apply_functions(pattern, search, replace): > ? ?def matches_rule(word): > ? ? ? ?return re.search(pattern, word) > ? ?def apply_rule(word): > ? ? ? ?return re.sub(search, replace, word) > ? ?return (matches_rule, apply_rule) > > patterns = \ > ?( > ? ?('[sxz]$', ? ? ? ? ? '$', ?'es'), > ? ?('[^aeioudgkprt]h$', '$', ?'es'), > ? ?('(qu|[^aeiou])y$', ?'y$', 'ies'), > ? ?('$', ? ? ? ? ? ? ? ?'$', ?'s') > ?) > rules = [build_match_and_apply_functions(pattern, search, replace) > ? ? ? ? for (pattern, search, replace) in patterns] > > def plural(noun): > ? ?for matches_rule, apply_rule in rules: > ? ? ? ?if matches_rule(noun): > ? ? ? ? ? ?return apply_rule(noun) > > this example works on IDLE: print plural("baby") > My question is "baby" assigned to "word" in the inner function? It's a > little mind bending for me... It is a little mind bending when you first start seeing functions used as first-class objects. In Python functions are values that can be passed as arguments, returned, and assigned just like any other value. This can simplify a lot of problems. In this case I think the use of functions makes the code needlessly complicated. Without build_match_and_apply_functions() and the rules list it would look like this: def plural(noun): for (pattern, search, replace) in patterns: if re.search(pattern, noun): return re.replace(search, replace, noun) which is not much longer that the original plural(), doesn't require all the helper machinery and IMO is easier to understand. Kent From kent37 at tds.net Sat Feb 13 16:06:02 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Feb 2010 10:06:02 -0500 Subject: [Tutor] The Order of Imports and install order of modules and other matters (XP vs W7, ...) In-Reply-To: <4B7622BF.9000408@sbcglobal.net> References: <4B7622BF.9000408@sbcglobal.net> Message-ID: <1c2a2c591002130706i6aa1b99boc019f7f37d2c8804@mail.gmail.com> On Fri, Feb 12, 2010 at 10:55 PM, Wayne Watson wrote: > There seems to be something of a general consensus in ordering import > statements. Something like standard library imports first. When using tools > like matlablib or tkinter (maybe), must one keep an order among the relevant > imports? I don't know if there is a general consensus but what I like to do is standard library imports third-party library imports application-specific imports Within each group I tend to group "import x" imports before "from x import y" imports and alphabetize by module name. I'm not strict about that though. > Related to this is the order in which modules are installed. Does it make a > difference? It shouldn't matter. > Finally, I'm in the process of moving Python code from XP to Win7. I just > grabbed all the install files I have from XP, and executed them on W7. > Everything seems to be working as expected, but one strange thing happened > with scipy. It produced a warning about something like "unable to provide > key". ?I continued anyway. All seems well. Was I supposed to use some W7 > version of the "XP" files? This is anomaly 1. There doesn't seem to be a separate installer for W7 but there may be issues, W7 is still pretty new. Also check that you are using the most recent scipy. > OK, this the last one. In both XP and W7, I've found executing a program by > use of the py file (not IDLE. Is there a name for this method?) using numpy > that ?see early on in the DOS-like window (is there name for it too?) it's > complaining (alerting me) about deprecations and some use of a numpy test. > What's that about? This is anomaly 2. Deprecation warnings mean the code is using some outdated functionality that is slated to be removed. You should at least look at them and see if it is in your code or in scipy. Kent > -- > "Crime is way down. War is declining. And that's far from the good news." -- > Steven Pinker (and other sources) Why is this true, but yet the media says > otherwise? The media knows very well how to manipulate us (see limbic, > emotion, $$). -- WTW > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Feb 13 16:11:18 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Feb 2010 10:11:18 -0500 Subject: [Tutor] json file In-Reply-To: <5f3def2d1002130421q4115c300ic2e38f9726a2c1f@mail.gmail.com> References: <5f3def2d1002130421q4115c300ic2e38f9726a2c1f@mail.gmail.com> Message-ID: <1c2a2c591002130711t247e2538vce591036a0bf733a@mail.gmail.com> On Sat, Feb 13, 2010 at 7:21 AM, Chris Patillo wrote: > I need to read in a .json file and write out a file with some of the > information from this file.? I can't figure out how to read the .json file > in.? I know there is a module for this, but I don't understand how it works. > > The file I am needing to read is like below (except much much larger) > > { > > ?? "table":"contacts", > > ?? "records":[ > > ?? ? ?{ > > ?? ? ? ? "name":"John", > > ?? ? ? ? "phone":"555-555-4444" > > ?? ? ?}, > > ?? ? ?{ > > ?? ? ? ? "name":"Jane", > > ?? ? ? ? "phone":"555-555-3333" > > ?? ? ?}, > > ?? ] > > } > > > > I have no clue how to do this.? I was thinking something like; > > import json > > json.dumps([name,phone], seperators(":")) json.dumps() converts a structure to a json string. json.load() is what you want. If your file is called data.json, try import json data = json.load(open('data.json')) print data If your data is not Ascii or UTF-8 you have to specify the encoding to json.load(). Kent From waynejwerner at gmail.com Sat Feb 13 16:37:07 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 13 Feb 2010 09:37:07 -0600 Subject: [Tutor] Just a Note In-Reply-To: References: <5323715525EA4925A05B0EF6E0A94AF3@RandyPC> Message-ID: <333efb451002130737md7b2bf6u6d07b91de33a6888@mail.gmail.com> On Sat, Feb 13, 2010 at 3:18 AM, Alan Gauld wrote: > > "Randy Raymond" wrote > > By the way, Alan Gauld's emails generate an error in my system. His is >> the only emails I have a problem with so far. At first it tried to open a >> News service. >> > > Interesting. I am using the gmane news server but I've not heard of anyone > else having problems. Is there anyone else? Not I - gmail hasn't had any problems... at least that I know of. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Feb 13 17:14:31 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 13 Feb 2010 08:14:31 -0800 Subject: [Tutor] The Order of Imports and install order of modules and other matters (XP vs W7, ...) In-Reply-To: References: <4B7622BF.9000408@sbcglobal.net> Message-ID: <4B76CFE7.3090600@sbcglobal.net> Thanks, Alan. Some of what I've derived elsewhere almost sounds like hearsay or is anecdotal. I'm thinking here about forums and the like. However, I just grabbed my Core Python book, and noted than Chun mentions a preferred sequence. Std Lib, Third Party, App specific modules. He cites scoping rules. Another question on similar matters. If I write a program and "compile" it for distribution, and a user has 2.6 going to be able to execute it. I would like to the the compiled program is free of such restrictions. That is, it's an independent program. I would like to think that if I've been testing it successfully in IDLE, that the compiled version will produce everything I see in IDLE. For example, when I run it in IDLE, and make a connection to the (camera) h/w, a dos-like window appears that I otherwise never see. The program purposefully either sends warning and error messages there through some built-in facility or creates that window somehow. I'm dealing with tkinter in the app code. I didn't write the (1600 line) program, but certainly am modifying it. On 2/13/2010 1:33 AM, Alan Gauld wrote: > > "Wayne Watson" wrote > >> There seems to be something of a general consensus in ordering import >> statements. Something like standard library imports first. > > I've never seen anything written down but its true I tend to do that. > But its not been a conscious thing... ... -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From alan.gauld at btinternet.com Sat Feb 13 17:19:06 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 13 Feb 2010 16:19:06 +0000 (GMT) Subject: [Tutor] The Order of Imports and install order of modules and other matters (XP vs W7, ...) In-Reply-To: <4B76CFE7.3090600@sbcglobal.net> References: <4B7622BF.9000408@sbcglobal.net> <4B76CFE7.3090600@sbcglobal.net> Message-ID: <808178.25267.qm@web86704.mail.ird.yahoo.com> > Another question on similar matters. If I write a program and "compile" it for > distribution, and a user has 2.6 going to be able to execute it. I would like to > the the compiled program is free of such restrictions. That is, it's an > independent program. I would like to think that if I've been testing it > successfully in IDLE, that the compiled version will produce everything I see in > IDLE. Never ever, ever, test anything for distribution inside an IDE! Always test it as it will be run - from the OS prompt or filemanager. IDEs can introduce subtle differences of behaviour that conceal bugs. Similarly never ever do a final test with debuggng code switched on or the debugger active, again the debugger can cause subtle changes in behaviour. > For example, when I run it in IDLE, and make a connection to the (camera) > h/w, a dos-like window appears that I otherwise never see. The program > purposefully either sends warning and error messages there through some built-in > facility or creates that window somehow. I'm dealing with tkinter in the app > code. I didn't write the (1600 line) program, but certainly am modifying it. Do you run it with python or pythonw, that might also make a difference. HTH, Alan G. From sierra_mtnview at sbcglobal.net Sat Feb 13 17:20:02 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 13 Feb 2010 08:20:02 -0800 Subject: [Tutor] The Order of Imports and install order of modules and other matters (XP vs W7, ...) In-Reply-To: <1c2a2c591002130706i6aa1b99boc019f7f37d2c8804@mail.gmail.com> References: <4B7622BF.9000408@sbcglobal.net> <1c2a2c591002130706i6aa1b99boc019f7f37d2c8804@mail.gmail.com> Message-ID: <4B76D132.9010604@sbcglobal.net> Thanks, Kent. As of a day ago, I've moved my Python work to W7. For about the last 4 weeks, I've been using XP. Four weeks ago, I moved my mail and browser to W7, so trying to copy out from one PC to the other is a tale of juggling. Next time I have the deprecation and test msgs appear, I'll print them out, so that I can read the detail. I'm planning on making the code I'm writing available in a "compiled" form, exe. I hope those messages don't appear when users try to execute the program. On 2/13/2010 7:06 AM, Kent Johnson wrote: > On Fri, Feb 12, 2010 at 10:55 PM, Wayne Watson > wrote: > >> There seems to be something of a general consensus in ordering import >> statements. Something like standard library imports first. When using tools >> like matlablib or tkinter (maybe), must one keep an order among the relevant >> imports? >> > I don't know if there is a general consensus but what I like to do is > standard library imports > ... >> s that about? This is anomaly 2. >> > Deprecation warnings mean the code is using some outdated > functionality that is slated to be removed. You should at least look > at them and see if it is in your code or in scipy. > > Kent > > >> -- >> "Crime is way down. War is declining. And that's far from the good news." -- >> Steven Pinker (and other sources) Why is this true, but yet the media says >> otherwise? The media knows very well how to manipulate us (see limbic, >> emotion, $$). -- WTW >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From zepangolin at gmail.com Sat Feb 13 16:56:08 2010 From: zepangolin at gmail.com (patrice laporte) Date: Sat, 13 Feb 2010 16:56:08 +0100 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? Message-ID: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> Hi, Being in an exeption of my own, I want to print the name of the caller, and I'm looking for a way to have it. I've found a lot of recipe all of them using what seems to be, according to me, a not so good trick : all those recipe make use of sys._getframe(1).f_code.co_name, such as in this exemple : import sys def whoami(): print "Who call me ? : ", sys._getframe(1).f_code.co_name print "Who am I ? : ", sys._getframe(0).f_code.co_name def print_caller_name(): whoami() if __name__ == "__main__": print_caller_name() With the following result, as expected : Who call me ? : print_caller_name Who am I ? : whoami A closer look at the documentation about sys._getframe at http://docs.python.org/library/sys.html make me think it's not a good idea, because of the note : "*CPython implementation detail:* This function should be used for internal and specialized purposes only. *It is not guaranteed to exist in all implementations of Python*." So, this trick works today, but what about tomorow ? Is anybody have an idea how to get the the same result without _getframe ? Thanks Patrice. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Feb 13 19:44:28 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 13 Feb 2010 10:44:28 -0800 Subject: [Tutor] The Order of Imports and install order of modules and other matters (XP vs W7, ...) In-Reply-To: <808178.25267.qm@web86704.mail.ird.yahoo.com> References: <4B7622BF.9000408@sbcglobal.net> <4B76CFE7.3090600@sbcglobal.net> <808178.25267.qm@web86704.mail.ird.yahoo.com> Message-ID: <4B76F30C.3060309@sbcglobal.net> Thanks. Sounds like good advice. BTW, I just did some advertising on the AstroPy NG a moment ago for your books. A query for good Py books. On 2/13/2010 8:19 AM, ALAN GAULD wrote: > > >> Another question on similar matters. If I write a program and "compile" it for >> distribution, and a user has 2.6 going to be able to execute it. I would like to >> the the compiled program is free of such restrictions. That is, it's an >> independent program. I would like to think that if I've been testing it >> successfully in IDLE, that the compiled version will produce everything I see in >> IDLE. >> > Never ever, ever, test anything for distribution inside an IDE! > Always test it as it will be run - from the OS prompt or filemanager. > > IDEs can introduce subtle differences of behaviour that conceal bugs. > > Similarly never ever do a final test with debuggng code switched > on or the debugger active, again the debugger can cause subtle > changes in behaviour. > > >> For example, when I run it in IDLE, and make a connection to the (camera) >> h/w, a dos-like window appears that I otherwise never see. The program >> purposefully either sends warning and error messages there through some built-in >> facility or creates that window somehow. I'm dealing with tkinter in the app >> code. I didn't write the (1600 line) program, but certainly am modifying it. >> > Do you run it with python or pythonw, that might also make a difference. > > HTH, > > Alan G. > > > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From kent37 at tds.net Sat Feb 13 19:57:21 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Feb 2010 13:57:21 -0500 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> Message-ID: <1c2a2c591002131057g316ebf5dtb824e9c4504cdae5@mail.gmail.com> On Sat, Feb 13, 2010 at 10:56 AM, patrice laporte wrote: > Being in an exeption of my own, I want to print the name of the caller, and > I'm looking for a way to have it. > > I've found a lot of recipe all of them using what seems to be, according to > me, a not so good trick : all those recipe make use of > sys._getframe(1).f_code.co_name > > A closer look at the documentation about sys._getframe at > http://docs.python.org/library/sys.html make me think it's not a good idea, > because of the note : > "CPython implementation detail: This function should be used for internal > and specialized purposes only. It is not guaranteed to exist in all > implementations of Python." > > So, this trick works today, but what about tomorow ? > > Is anybody have an idea how to get the the same result without _getframe ? Here is a way to do it using the traceback module. Under the hood it is still using implementation details contained in traceback and stack frame objects but the public interface in the traceback module should be stable. import sys, traceback def whoami(): stack = traceback.extract_stack(limit=2) print "Who call me ? : ", stack[0][2] print "Who am I ? : ", stack[1][2] def print_caller_name(): whoami() if __name__ == "__main__": print_caller_name() Kent From david at pythontoo.com Sat Feb 13 19:58:34 2010 From: david at pythontoo.com (David Abbott) Date: Sat, 13 Feb 2010 13:58:34 -0500 Subject: [Tutor] operators >> and & Message-ID: <1266087514.23188.6.camel@opteron.dwabbott.com> I am attempting to understand this little program that converts a network byte order 32-bit integer to a dotted quad ip address. #!/usr/bin/python # Filename : int2ip.py MAX_IP = 0xffffffffL ip = 2130706433 def int2ip(l): if MAX_IP < l < 0: raise TypeError, "expected int between 0 and %d inclusive" % MAX_IP return '%d.%d.%d.%d' % (l>>24 & 255, l>>16 & 255, l>>8 & 255, l & 255) result = int2ip(ip) print result I don't understand the l>>24 & 255. from the docs; Right Shift a >> b rshift(a, b) Bitwise And a & b and_(a, b) thanks -- David Abbott From steve at alchemy.com Sat Feb 13 20:32:56 2010 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 13 Feb 2010 11:32:56 -0800 Subject: [Tutor] operators >> and & In-Reply-To: <1266087514.23188.6.camel@opteron.dwabbott.com> References: <1266087514.23188.6.camel@opteron.dwabbott.com> Message-ID: <20100213193256.GA48938@dragon.alchemy.com> On Sat, Feb 13, 2010 at 01:58:34PM -0500, David Abbott wrote: > I don't understand the l>>24 & 255. The >> and << operators (when applied to integers) shift the bits left or right a number of positions. The number 5, for example, is 101 in binary, or if you want to picture that as a 16-bit value, 0000000000000101. When you do 5 << 3 that takes those bits and shifts them 3 places to the left, so you end up with: 0000000000101000 The >> works similarly but shifting to the right. The & operator performs a logical "AND" to the individual bits of two numbers, where A & B is 1 if A and B are both 1 and 0 otherwise. People often use them for "masking" out a set of bits from a bigger value, like this. To get just the least significant octet from an IP address like 1.2.3.4, you would AND it with 255 (0xff) like so: ip = 00000001000000100000001100000100 # 1.2.3.4 0xff= 00000000000000000000000011111111 & -------------------------------- 00000000000000000000000000000100 # 4 Then you can shift 8 places right and AND again to get the next octet: ip = 00000001000000100000001100000100 # 1.2.3.4 >>8= 00000000000000010000001000000011 # 0.1.2.3 0xff= 00000000000000000000000011111111 & -------------------------------- 00000000000000000000000000000011 # 3 -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From zepangolin at gmail.com Sat Feb 13 20:38:45 2010 From: zepangolin at gmail.com (patrice laporte) Date: Sat, 13 Feb 2010 20:38:45 +0100 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <1c2a2c591002131057g316ebf5dtb824e9c4504cdae5@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <1c2a2c591002131057g316ebf5dtb824e9c4504cdae5@mail.gmail.com> Message-ID: <954757881002131138l247cee3bjc42b26cc68a841ce@mail.gmail.com> 2010/2/13 Kent Johnson > > > >Here is a way to do it using the traceback module. Under the hood it > >is still using implementation details contained in traceback and stack > >frame objects but the public interface in the traceback module should > >be stable. > > >import sys, traceback > > >def whoami(): > > stack = traceback.extract_stack(limit=2) > > print "Who call me ? : ", stack[0][2] > > print "Who am I ? : ", stack[1][2] > > >def print_caller_name(): > > whoami() > > >if __name__ == "__main__": > > print_caller_name() > > >Kent > Thanks for the help, I will look closer at the traceback module and at your solution Patrice -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sat Feb 13 20:45:52 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 13 Feb 2010 13:45:52 -0600 Subject: [Tutor] operators >> and & In-Reply-To: <1266087514.23188.6.camel@opteron.dwabbott.com> References: <1266087514.23188.6.camel@opteron.dwabbott.com> Message-ID: <333efb451002131145s5fbfcc0an76df01e8f950aa68@mail.gmail.com> On Sat, Feb 13, 2010 at 12:58 PM, David Abbott wrote: > > I don't understand the l>>24 & 255. > > from the docs; > Right Shift a >> b rshift(a, b) > Bitwise And a & b and_(a, b) > They're binary operations... If you're not familiar, wikipedia or google can find you many sources. In a nutshell: 0110 >> 1 == 0011 0011 >> 1 == 0001 0110 & 0101 == 0100 0100 & 0001 == 0000 HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at pythontoo.com Sat Feb 13 21:51:08 2010 From: david at pythontoo.com (David Abbott) Date: Sat, 13 Feb 2010 15:51:08 -0500 Subject: [Tutor] operators >> and & In-Reply-To: <20100213193256.GA48938@dragon.alchemy.com> References: <1266087514.23188.6.camel@opteron.dwabbott.com> <20100213193256.GA48938@dragon.alchemy.com> Message-ID: <1266094268.28047.9.camel@opteron.dwabbott.com> On Sat, 2010-02-13 at 11:32 -0800, Steve Willoughby wrote: On Sat, 2010-02-13 at 13:45 -0600, Wayne Werner wrote: Thanks Steve and Wayne your explanations; HAL (helps a lot) -- David Abbott From shurui91 at gmail.com Sat Feb 13 22:08:05 2010 From: shurui91 at gmail.com (=?GB2312?B?wfXK6e6j?=) Date: Sat, 13 Feb 2010 16:08:05 -0500 Subject: [Tutor] ask Message-ID: <2b9003cf1002131308t6ff53396m38cd201a4557d92c@mail.gmail.com> Here are my assignment about Python, I don't know if anything is wrong. Is there anybody can help me? 1. assignment 9a and 9b hyperlink: http://cset.sp.utoledo.edu/cset1100py/cset1100_assign.html#simplepy 2. I don't know how to run a program in putty.exe, who knows? Cause i don't know the relationship between putty.exe and python. Thank you! Aaron -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 13 22:33:59 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Feb 2010 16:33:59 -0500 Subject: [Tutor] ask In-Reply-To: <2b9003cf1002131308t6ff53396m38cd201a4557d92c@mail.gmail.com> References: <2b9003cf1002131308t6ff53396m38cd201a4557d92c@mail.gmail.com> Message-ID: <1c2a2c591002131333o5791b5d5ud2b25052e8308d04@mail.gmail.com> On Sat, Feb 13, 2010 at 4:08 PM, ??? wrote: > Here are my assignment about Python, I don't know if anything is wrong. Is > there anybody can help me? > > 1. assignment 9a and 9b hyperlink: > > http://cset.sp.utoledo.edu/cset1100py/cset1100_assign.html#simplepy > > 2. I don't know how to run a program in putty.exe, who knows? Cause i don't > know the relationship between putty.exe and python. These assignments are more about learning your local computing environment and tools than they are about Python. If you are having trouble you should ask for help at school. Kent From rabidpoobear at gmail.com Sat Feb 13 22:38:57 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 13 Feb 2010 15:38:57 -0600 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> Message-ID: On Sat, Feb 13, 2010 at 9:56 AM, patrice laporte wrote: > > Hi, > > Being in an exeption of my own, I want to print the name of the caller, and > I'm looking for a way to have it. > > Could you tell us exactly why you want to do this? It seems sort of strange. Also couldn't you pass the caller as an argument to your function? -------------- next part -------------- An HTML attachment was scrubbed... URL: From shurui91 at gmail.com Sat Feb 13 22:40:18 2010 From: shurui91 at gmail.com (Shurui Liu (Aaron Liu)) Date: Sat, 13 Feb 2010 16:40:18 -0500 Subject: [Tutor] ask In-Reply-To: <1c2a2c591002131333o5791b5d5ud2b25052e8308d04@mail.gmail.com> References: <2b9003cf1002131308t6ff53396m38cd201a4557d92c@mail.gmail.com> <1c2a2c591002131333o5791b5d5ud2b25052e8308d04@mail.gmail.com> Message-ID: <2b9003cf1002131340v16e843fah13e3ed0d1db9ddc9@mail.gmail.com> Yeah, i know. I don't want somebody tell me all the answers of these assignment directly. I just want to know is there any error in the commands listed online? My teacher told us there is some, but I cannot find out. He said we can run them on putty.exe as soon as we fix the errors. I have found some format error, but still "command not found" Thank you! 2010/2/13 Kent Johnson > On Sat, Feb 13, 2010 at 4:08 PM, ??? wrote: > > Here are my assignment about Python, I don't know if anything is wrong. > Is > > there anybody can help me? > > > > 1. assignment 9a and 9b hyperlink: > > > > http://cset.sp.utoledo.edu/cset1100py/cset1100_assign.html#simplepy > > > > 2. I don't know how to run a program in putty.exe, who knows? Cause i > don't > > know the relationship between putty.exe and python. > > These assignments are more about learning your local computing > environment and tools than they are about Python. If you are having > trouble you should ask for help at school. > > Kent > -- Shurui Liu (Aaron Liu) Computer Science & Engineering Technology University of Toledo -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 13 23:04:41 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Feb 2010 17:04:41 -0500 Subject: [Tutor] ask In-Reply-To: <2b9003cf1002131340v16e843fah13e3ed0d1db9ddc9@mail.gmail.com> References: <2b9003cf1002131308t6ff53396m38cd201a4557d92c@mail.gmail.com> <1c2a2c591002131333o5791b5d5ud2b25052e8308d04@mail.gmail.com> <2b9003cf1002131340v16e843fah13e3ed0d1db9ddc9@mail.gmail.com> Message-ID: <1c2a2c591002131404x63de5da1j77c2cdf88b5e910d@mail.gmail.com> 2010/2/13 Shurui Liu (Aaron Liu) : > Yeah, i know. I don't want somebody tell me all the answers of these > assignment directly. I just want to know is there any error in the commands > listed online? My teacher told us there is some, but I cannot find out. He > said we can run them on putty.exe as soon as we fix the errors. I have found > some format error, but still "command not found" Thank you! We can help you with Python homework if you have specific questions, but don't ask us to do the homework for you. The point of the assignment seems to be for you to learn to run Python programs and find and fix errors. Putty is a ssh client that will help you run programs on a server, but you should be able to try running the programs on your own computer first. Kent From denis.spir at free.fr Sat Feb 13 23:17:27 2010 From: denis.spir at free.fr (spir) Date: Sat, 13 Feb 2010 23:17:27 +0100 Subject: [Tutor] operators >> and & In-Reply-To: <1266087514.23188.6.camel@opteron.dwabbott.com> References: <1266087514.23188.6.camel@opteron.dwabbott.com> Message-ID: <20100213231727.7f08b984@o> On Sat, 13 Feb 2010 13:58:34 -0500 David Abbott wrote: > I am attempting to understand this little program that converts a > network byte order 32-bit integer to a dotted quad ip address. > > #!/usr/bin/python > # Filename : int2ip.py > > MAX_IP = 0xffffffffL > ip = 2130706433 > > def int2ip(l): > if MAX_IP < l < 0: > raise TypeError, "expected int between 0 and %d inclusive" % > MAX_IP > return '%d.%d.%d.%d' % (l>>24 & 255, l>>16 & 255, l>>8 & 255, l & > 255) > > result = int2ip(ip) > print result > > I don't understand the l>>24 & 255. > > from the docs; > Right Shift a >> b rshift(a, b) > Bitwise And a & b and_(a, b) > > thanks > In addition to Steve's excellent explanation: Shifting to the left n bits is equivalent to multiplying by 2^n. Shifting to the right n bits is equivalent to dividing by 2^n. Shifting to the right 8 bits is thus equivalent to dividing by 2^8=256; which means making each octet (in a long integer) one level less significant. AND-ing is equivalent to masking (this is actually called a mask operating) all bits wich are not 1 in the mask. So AND-ing with 11111111=255 masks all bits except the ones of the least significant octet. If you represent a 32-bit integer as 4 octets, or 8 hex digits, the picture is easier to catch: n = 0x12345678 # 0x12345678 = abcd (b=0x34=52) # to get b: temp = n >> 16 # 0x00001234 = 00ab b = temp & 255 # 0x00000034 = 000b You can perform the same operation without bit-level operators, using modulo and integer division. To understand this, again consider the "abcd" representation: this means a 32-bit integer can be seen as 4-digit number written in base 256 (yes!). Division by 256^n gets rid of n lowest digits, moving down all other ones. Modulo 256^n gets rid of digits in higher position than n. (This may help and fully catch the sense of "base n"). n = 0x12345678 # 0x12345678 = abcd (b=0x34) # to get b: temp = n // (256**2) # 0x00001234 = 00ab b = temp % 256 # 0x00000034 = 000b (examples untested) Bit operations are by far faster, indeed. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Sat Feb 13 23:28:31 2010 From: denis.spir at free.fr (spir) Date: Sat, 13 Feb 2010 23:28:31 +0100 Subject: [Tutor] operators >> and & In-Reply-To: <20100213231727.7f08b984@o> References: <1266087514.23188.6.camel@opteron.dwabbott.com> <20100213231727.7f08b984@o> Message-ID: <20100213232831.5c1c1d83@o> On Sat, 13 Feb 2010 23:17:27 +0100 spir wrote: > On Sat, 13 Feb 2010 13:58:34 -0500 > David Abbott wrote: > > > I am attempting to understand this little program that converts a > > network byte order 32-bit integer to a dotted quad ip address. > > > > #!/usr/bin/python > > # Filename : int2ip.py > > > > MAX_IP = 0xffffffffL > > ip = 2130706433 > > > > def int2ip(l): > > if MAX_IP < l < 0: > > raise TypeError, "expected int between 0 and %d inclusive" % > > MAX_IP > > return '%d.%d.%d.%d' % (l>>24 & 255, l>>16 & 255, l>>8 & 255, l & > > 255) PS: in "l>>24 & 255", the & operation is useless, since all 24 higher bits are already thrown away by the shift: >>> 0x12345678 >> 24 18 # = 0x12 Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From alan.gauld at btinternet.com Sun Feb 14 00:54:24 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Feb 2010 23:54:24 -0000 Subject: [Tutor] operators >> and & References: <1266087514.23188.6.camel@opteron.dwabbott.com> Message-ID: "David Abbott" wrote > I am attempting to understand this little program that converts a > network byte order 32-bit integer to a dotted quad ip address. > def int2ip(l): > if MAX_IP < l < 0: > raise TypeError, "expected int between 0 and %d inclusive" % > MAX_IP > return '%d.%d.%d.%d' % (l>>24 & 255, l>>16 & 255, l>>8 & 255, l & > 255) The >>> shifts the number bitwise to the right. Thus the number 8 is 1000 in binary 8 >> 3 -> 0001 So taking a 32 bit number and shifting it right 24 bits leaves the top 8 bits N & 255 uses a bitwise and to filter the number N by removing anything outside the 8 bits (should any spurious 1's sneak in...) In bitwise and a 1 and 1 gives 1 any other combination gives 0. So and'ing with 255 (11111111) simply repeats the 8 bits of N while zeroing all the other bits. Similarly >> 16 gets the top 16 bits and andintg with 255 processes bits 16-24 and zeros the rest. And so on for the other two groups of 8 bits. There is more on using bitwise operators and "masking" in my Using the OS topic in my tutorial(v2). (Look for a "sidebar" half way down) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Feb 14 00:58:10 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Feb 2010 23:58:10 -0000 Subject: [Tutor] operators >> and & References: <1266087514.23188.6.camel@opteron.dwabbott.com><20100213231727.7f08b984@o> <20100213232831.5c1c1d83@o> Message-ID: "spir" wrote > PS: in "l>>24 & 255", the & operation is useless, since all 24 higher > bits are already thrown away by the shift: They are not gone however there are still 32 bits in an integer so the top bits *should* be set to zero. But glitches can occur from time to time... It is good practice to restrict the range to the 8 bits needed by and'ing with 255 even when you think you should be safe. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Feb 14 01:41:41 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Feb 2010 11:41:41 +1100 Subject: [Tutor] aliasing an imported module In-Reply-To: <0A04999D-5173-4355-A1E6-1BAD757DC2BD@newcastle.edu.au> References: <0A04999D-5173-4355-A1E6-1BAD757DC2BD@newcastle.edu.au> Message-ID: <201002141141.41510.steve@pearwood.info> On Sat, 13 Feb 2010 10:51:38 am Garry Willgoose wrote: > I want to be able to import multiple instances of a module and call > each by a unique name and it doesn't appear at first glance that > either import or __import__ have what I need. No, such a thing is not officially supported by Python. Python treats modules as singletons -- there is only one instance of any module at any time. It is possible to force Python to break that promise, but that is fighting the language, and there's no guarantee that it won't cause other breakages further along. So if you choose to create multiple instances of a module, you're doing something the language doesn't want you to do, and if you end up shooting yourself in the foot you'll have no one to blame but yourself. Having said that, the following trick should do what you want. Start with a simple module holding state: # mymodule.py state = [] Here's Python's normal behaviour: >>> import mymodule >>> mymodule.state [] >>> mymodule.state.append(123) >>> mymodule.state [123] >>> import mymodule as something_else >>> something_else.state [123] And here's the trick: >>> import sys >>> del sys.modules['mymodule'] >>> import mymodule as another_name >>> another_name.state [] >>> mymodule.state # Check the original. [123] This *should* work across all versions and implementations of Python, but remember that it's a hack. You're fighting the language rather than working with it. Another problem is that there's no guarantee that the module holds all its state inside itself: it might in turn import a second module, and store state in there. Many packages, in particular, may do this. The best solution is to avoid global state if you possibly can. You also say: > The key problem is that ? > the ?module might locally store some partial results ready for the ? > next time its called to save CPU time (typically the results for one ? > timestep ready for the next timestep). I'm going to take a wild guess as to what you're doing, and make a suggestion for how you can do something better. I guess you have functions something like this: STATE = None def func(): global STATE if STATE is None: # No global state recorded, so we start from scratch. step = 1 partial = 0 else: step, partial = STATE step += 1 partial = do_some_calculations(step, partial) STATE = (step, partial) return partial But as you point out, that means all calls to func() use the same global state. Here are two alternatives. Here's a rather messy one, but it tickles my fancy: use a token to identify the caller, so each caller gets their own state and not somebody else's. LAST_TOKEN = 0 def get_token(): global LAST_TOKEN LAST_TOKEN += 1 return LAST_TOKEN STATE = {} def func(token): global STATE if not STATE[token]: # No global state recorded, so we start from scratch. step = 1 partial = 0 else: step, partial = STATE[token] step += 1 partial = do_some_calculations(step, partial) # Defined elsewhere. STATE[token] = (step, partial) return partial Then, before each independent use of func, the caller simply calls get_token() and passes that to the function. I'm sure you can see problems with this: - the caller has to store their tokens and make sure they pass the right one; - the function needs to deal with invalid tokens; - the global STATE ends up storing the result of intermediate calculations long after they are no longer needed; - the separation is a "gentleman's agreement" -- there is nothing stopping one caller from guessing another valid token. Although I'm remarkably fond of this solution in theory, in practice I would never use it. A better solution is to write func in a more object-oriented fashion: class FuncCalculator(object): """Class that calculates func""" def __init__(self): # Start with initial state. self.STATE = (1, 0.0) def __call__(self): step, partial = self.STATE step += 1 partial = self.do_some_calculations(step, partial) self.STATE = (step, partial) return partial def do_some_calculations(self, step, partial): return partial + 1.0/step # or whatever Instances of the class are callable as if they were functions. In C++ terminology, this is called a "functor". In Python, we normally just call it a callable. So we can create as many independent "functions" as needed, each with their own state: >>> f = FuncCalculator() >>> g = FuncCalculator() >>> h = FuncCalculator() >>> f() 0.5 >>> f() 0.83333333333333326 >>> f() 1.0833333333333333 >>> g() 0.5 >>> g() 0.83333333333333326 >>> h() 0.5 >>> f() 1.2833333333333332 Hope this helps! -- Steven D'Aprano From eduardo.susan at gmail.com Sun Feb 14 02:02:45 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Sat, 13 Feb 2010 18:02:45 -0700 Subject: [Tutor] Not understanding this code example. Help, please. In-Reply-To: <1c2a2c591002130659h4e3f40cfh5cc304f5c53397e4@mail.gmail.com> References: <9356b9f31002122049w5cde73cbqb8c1f231367bd15a@mail.gmail.com> <1c2a2c591002130659h4e3f40cfh5cc304f5c53397e4@mail.gmail.com> Message-ID: <9356b9f31002131702x72364500l21a0b2c080a59e57@mail.gmail.com> On Sat, Feb 13, 2010 at 7:59 AM, Kent Johnson wrote: > On Fri, Feb 12, 2010 at 11:49 PM, Eduardo Vieira > wrote: >> Hello! I was reading the latest version of Mark Pilgrim's "Dive into >> Python" and am confused with these example about the pluralization >> rules. See http://diveintopython3.org/examples/plural3.py and >> http://diveintopython3.org/generators.html#a-list-of-patterns >> Here is part of the code: >> import re >> >> def build_match_and_apply_functions(pattern, search, replace): >> ? ?def matches_rule(word): >> ? ? ? ?return re.search(pattern, word) >> ? ?def apply_rule(word): >> ? ? ? ?return re.sub(search, replace, word) >> ? ?return (matches_rule, apply_rule) >> >> patterns = \ >> ?( >> ? ?('[sxz]$', ? ? ? ? ? '$', ?'es'), >> ? ?('[^aeioudgkprt]h$', '$', ?'es'), >> ? ?('(qu|[^aeiou])y$', ?'y$', 'ies'), >> ? ?('$', ? ? ? ? ? ? ? ?'$', ?'s') >> ?) >> rules = [build_match_and_apply_functions(pattern, search, replace) >> ? ? ? ? for (pattern, search, replace) in patterns] >> >> def plural(noun): >> ? ?for matches_rule, apply_rule in rules: >> ? ? ? ?if matches_rule(noun): >> ? ? ? ? ? ?return apply_rule(noun) >> >> this example works on IDLE: print plural("baby") >> My question is "baby" assigned to "word" in the inner function? It's a >> little mind bending for me... > > It is a little mind bending when you first start seeing functions used > as first-class objects. In Python functions are values that can be > passed as arguments, returned, and assigned just like any other value. > This can simplify a lot of problems. > > In this case I think the use of functions makes the code needlessly > complicated. Without build_match_and_apply_functions() and the rules > list it would look like this: > > def plural(noun): > ? for (pattern, search, replace) in patterns: > ? ? ? if re.search(pattern, noun): > ? ? ? ? ? return re.replace(search, replace, noun) > > which is not much longer that the original plural(), doesn't require > all the helper machinery and IMO is easier to understand. > > Kent > Thanks for the input. Yes, there are simple ways to do it. If I recall the author shows 3 or 4 different ways of doing this, each showing some of python's features. This one was to introduce the concept of closures. Cheers, Eduardo From steve at pearwood.info Sun Feb 14 02:21:49 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Feb 2010 12:21:49 +1100 Subject: [Tutor] operators >> and & In-Reply-To: References: <1266087514.23188.6.camel@opteron.dwabbott.com> <20100213232831.5c1c1d83@o> Message-ID: <201002141221.49429.steve@pearwood.info> On Sun, 14 Feb 2010 10:58:10 am Alan Gauld wrote: > "spir" wrote > > > PS: in "l>>24 & 255", the & operation is useless, since all 24 > > higher bits are already thrown away by the shift: > > They are not gone however there are still 32 bits in an integer so > the top bits *should* be set to zero. No, Python ints are not 32 bit native ints. They're not even 64 bit ints. Python has unified the old "int" type with "long", so that ints automatically grow as needed. This is in Python 3.1: >>> (0).bit_length() 0 >>> (1).bit_length() 1 >>> (2).bit_length() 2 >>> (3).bit_length() 2 >>> (10**100).bit_length() 333 Consequently, if you have an arbitrary int that you don't know where it came from, you can't make any assumptions about the number of bits it uses. > But glitches can occur from time to time... If Python had a glitch of the magnitude of right-shifting non-zero bits into a number, that would be not just a bug but a HUGE bug. That would be as serious as having 1+1 return 374 instead of 2. Guarding against (say) 8 >> 1 returning anything other than 4 makes as much sense as guarding against 8//2 returning something other than 4: if you can't trust Python to get simple integer arithmetic right, then you can't trust it to do *anything*, and your guard (ANDing it with 255) can't be trusted either. > It is good practice to restrict the range to the 8 bits needed by > and'ing with 255 > even when you think you should be safe. It is certainly good practice if you are dealing with numbers which might be more than 24 bits to start with: >>> n = 5**25 >>> n >> 24 17763568394 >>> n >> 24 & 255 10 But *if* you know the int is no more than 32 bits, then adding in a guard to protect against bugs in the >> operator is just wasting CPU cycles and needlessly complicating the code. The right way to guard against "this will never happen" scenarios is with assert: assert n.bit_length() <= 32 # or "assert 0 <= n < 2**32" print(n >> 24) This has two additional advantages: (1) It clearly signals to the reader what your intention is ("I'm absolutely 100% sure than n will not be more than 32 bits, but since I'm a fallible human, I'd rather find out about an error in my logic as soon as possible"). (2) If the caller cares enough about speed to object to the tiny little cost of the assertion, he or she can disable it by passing the -O (O for Optimise) switch to Python. (More likely, while each assert is very cheap, a big application might have many, many asserts.) -- Steven D'Aprano From steve at pearwood.info Sun Feb 14 03:08:51 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Feb 2010 13:08:51 +1100 Subject: [Tutor] Tutor list as pair progamming plush toy In-Reply-To: <1265988784.21902.10.camel@jabbar> References: <1265988784.21902.10.camel@jabbar> Message-ID: <201002141308.51725.steve@pearwood.info> On Sat, 13 Feb 2010 02:33:04 am Mac Ryan wrote: > whenever I get stuck, I begin to write a message to the > list, and in the process of explaining what is the intended behaviour > and outcome of my code, I systematically find the bug by myself. [...] > Does anybody else experience the same? Yes! -- Steven D'Aprano From the7hansons at msn.com Sun Feb 14 02:08:40 2010 From: the7hansons at msn.com (the kids) Date: Sat, 13 Feb 2010 18:08:40 -0700 Subject: [Tutor] asigning class variables Message-ID: Hi, my name is John Paul. I was trying to define a class but I can't make it asign particular objects particular variables at their creation. Please help. John Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Feb 14 04:39:25 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Feb 2010 22:39:25 -0500 Subject: [Tutor] json file In-Reply-To: <5f3def2d1002131200r2e5a2eb8wc70fb33460767b9e@mail.gmail.com> References: <5f3def2d1002130421q4115c300ic2e38f9726a2c1f@mail.gmail.com> <1c2a2c591002130711t247e2538vce591036a0bf733a@mail.gmail.com> <5f3def2d1002131200r2e5a2eb8wc70fb33460767b9e@mail.gmail.com> Message-ID: <1c2a2c591002131939l99b5e11v32c76682beb70509@mail.gmail.com> On Sat, Feb 13, 2010 at 3:00 PM, Chris Patillo wrote: > Thanks for your response.? i did some research on json.load() and I don't > understand how you extract the data from it.? How do I get just the name and > number from the file? The value returned from json.load() is a Python dictionary. The structure of the dict will be the same as that of your initial data. In your case, the value of the 'records' key is itself a list of dicts containing names and phone numbers. To get the desired data you have to navigate this structure using standard python. Here is an example using your sample data. Note that I use json.loads() because I have the data in a string, rather than a file. import json from pprint import pprint json_data = '''{ "table":"contacts", "records":[ { "name":"John", "phone":"555-555-4444" }, { "name":"Jane", "phone":"555-555-3333" } ] }''' data = json.loads(json_data) pprint(data) for record in data['records']: print record['name'], record['phone'] The output of the program is {u'records': [{u'name': u'John', u'phone': u'555-555-4444'}, ??????????????{u'name': u'Jane', u'phone': u'555-555-3333'}], ?u'table': u'contacts'} John 555-555-4444 Jane 555-555-3333 Kent PS Please Reply All to reply on list. From kent37 at tds.net Sun Feb 14 04:41:59 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 13 Feb 2010 22:41:59 -0500 Subject: [Tutor] asigning class variables In-Reply-To: References: Message-ID: <1c2a2c591002131941l5245a9eelf993db7539e2cf55@mail.gmail.com> On Sat, Feb 13, 2010 at 8:08 PM, the kids wrote: > Hi, my name is John Paul. > > I was trying to define a class but I?can't make it asign particular objects > particular variables at their creation.? Please help. It would help to see some details of what you are trying to do. It sounds like you want an __init__() method in your class: In [1]: class Data(object): ...: def __init__(self, a, b): ...: self.a = a ...: self.b = b In [2]: d = Data(1, 2) In [3]: d.a Out[3]: 1 In [4]: d.b Out[4]: 2 In [5]: dd = Data(42, 57) In [6]: dd.a, dd.b Out[6]: (42, 57) Kent From steve at pearwood.info Sun Feb 14 07:53:07 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Feb 2010 17:53:07 +1100 Subject: [Tutor] asigning class variables In-Reply-To: References: Message-ID: <201002141753.08334.steve@pearwood.info> On Sun, 14 Feb 2010 12:08:40 pm the kids wrote: > Hi, my name is John Paul. > > I was trying to define a class but I can't make it asign particular > objects particular variables at their creation. Please help. > > John Paul I don't quite follow what you mean, it is best if you can show example code and describe what you expect and what you get instead. But first a brief note on terminology. In some other languages, people talk about "class variables" being variables that are part of the class. To me, that's inconsistent with everything else: an int variable holds an int; a string variable holds a string; a list variable holds a list; so a class variable should hold a class. (You might argue, why would you ever need a variable that was a class? As an experience Python programmer, I can tell you such a thing is very, very useful, and far more common than you might think.) Anyway, in Python circles, it is much more common to describe class variables as attributes. Other languages use the term "members", and people who used Apple's Hypercard will remember the term "properties" (but properties in Python are slightly different). Python has two sorts of attributes (class variables, a.k.a. members): * Attributes which are attached to the class itself, and therefore shared by all the instances. These are known as "class attributes". * Much more common is the ordinary sort of attribute that is attached to instances; these are usually known as "instance attributes", or more often, just plain old attributes. You create a class attribute (shared by all instances) by assigning to a name inside the class definition: class K: shared = [] This is now shared between all instances. You create an instance attribute (not shared) by assigning it inside a method, using the usual attribute syntax. The usual place to do this is inside the __init__ method. (Note that __init__ has TWO underscores at both the beginning and end.) class K: shared = [] def __init__(self): self.attribute = [] And in use: >>> a = K() >>> b = K() >>> a.shared.append(23) >>> b.shared [23] >>> a.attribute.append(23) >>> a.attribute [23] >>> b.attribute [] Using class attributes is sometimes tricky, because Python makes it really easy to accidentally hide a class attribute with an instance attribute with the same name, but fortunately having shared data like this is quite rare, so it's unusual to be a problem. Hope this helps, -- Steven D'Aprano From alan.gauld at btinternet.com Sun Feb 14 10:16:18 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Feb 2010 09:16:18 -0000 Subject: [Tutor] operators >> and & References: <1266087514.23188.6.camel@opteron.dwabbott.com><20100213232831.5c1c1d83@o> <201002141221.49429.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> They are not gone however there are still 32 bits in an integer so >> the top bits *should* be set to zero. > > No, Python ints are not 32 bit native ints. They're not even 64 bit > ints. Python has unified the old "int" type with "long", so that ints > automatically grow as needed. This is in Python 3.1: Valid point but irrelevant to the one I was making which is that the number after shifting is longer than 8 bits. >> But glitches can occur from time to time... > > If Python had a glitch of the magnitude of right-shifting non-zero bits > into a number, that would be not just a bug but a HUGE bug. Bit shifting is machine specific. Some CPUs (the DEC PDP range from memory is an example) will add the carry bit for example, most will not. But you can never be sure unless you know exactly which artchiotecture the program will run on. And of course data can always be corrupted at any time so its always wise to take as many precautions as possibe to keep it clean (although corruption within the CPU itself is, I agree, extremely unlikely) > be as serious as having 1+1 return 374 instead of 2. Guarding against > (say) 8 >> 1 returning anything other than 4 Not if you have a 4 bit processor and the previous opertation set the carry flag. In that case returning 12 would be emminently sensible....and used to be a common assembler trick for recovering from overflow errors. > guarding against 8//2 returning something other than 4: if you can't > trust Python to get simple integer arithmetic right, But ths is not simple integer arithmetic it is bit m,anippulation. You can use bit manipulation to fake arithmetic but they are fundamentally different operations and may not always produce the same results depending on how the designer built it! > trust it to do *anything*, and your guard (ANDing it with 255) can't be > trusted either. Nothing can be trusted 100% on a computer because, as you say the guard might itself be corrupted. Itas all about risk management. But when it comes to bit operations I'd always have at least one extra level of check, whether it be a mask or a checksum. > It is certainly good practice if you are dealing with numbers which > might be more than 24 bits to start with: Its more than good practice there, its essential. > But *if* you know the int is no more than 32 bits, then adding in a > guard to protect against bugs in the >> operator is just wasting CPU It may not be a bug it may be a design feature. Now all modern CPUs behave as you would expect but if you are running on older equipment (or specialised hardware - but that's more unlikely to have Python onboard!) you can never be quite sure how bitwise operations will react at boundary cases. If you know for certainty what the runtime environment will be then you can afford to take a chance. In the case in point the & 255 keeps the coding style consistent and provides an extra measure of protection against unexpected oddities so I would keep it in there. > cycles and needlessly complicating the code. The right way to guard > against "this will never happen" scenarios is with assert: > > assert n.bit_length() <= 32 # or "assert 0 <= n < 2**32" I would accept the second condition but the mask is much faster. bit_length doesn't seem to work on any of my Pythons (2.5,2.6 and 3.1) > This has two additional advantages: > > (1) It clearly signals to the reader what your intention is ("I'm > absolutely 100% sure than n will not be more than 32 bits, but since > I'm a fallible human, I'd rather find out about an error in my logic as > soon as possible"). The assert approach is perfectly valid, but since the mask is more consistent I'd still prefer to use it in this case. Alan G. From steve at alchemy.com Sun Feb 14 10:33:56 2010 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 14 Feb 2010 01:33:56 -0800 Subject: [Tutor] operators >> and & In-Reply-To: References: <201002141221.49429.steve@pearwood.info> Message-ID: <20100214093356.GA87164@dragon.alchemy.com> On Sun, Feb 14, 2010 at 09:16:18AM -0000, Alan Gauld wrote: > But ths is not simple integer arithmetic it is bit m,anippulation. > You can use bit manipulation to fake arithmetic but they are > fundamentally different operations and may not always > produce the same results depending on how the designer > built it! And this brings us back to one of Python's philosophical points. State clearly and explicitly what you mean to be doing. If you are doing bit manipulation, use bit manipulation operators. All the valid points above in this thread aside, it will make maintain- ing your code easier in the future if it's very clear what you intended the code to accomplish, and how. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From amit.pureenergy at gmail.com Sun Feb 14 12:10:17 2010 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Sun, 14 Feb 2010 16:40:17 +0530 Subject: [Tutor] Editing html using python Message-ID: Hi I need to edit html programmatically . Sadly the html might be broken at places . I was using BeautifulSoup but there were lots of problems and it is also not maintained can some one guide me to any tutorials on editing html using lxml . -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From zepangolin at gmail.com Sun Feb 14 12:33:09 2010 From: zepangolin at gmail.com (patrice laporte) Date: Sun, 14 Feb 2010 12:33:09 +0100 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> Message-ID: <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> 2010/2/13 Luke Paireepinart > > > On Sat, Feb 13, 2010 at 9:56 AM, patrice laporte wrote: > >> >> Hi, >> >> Being in an exeption of my own, I want to print the name of the caller, >> and I'm looking for a way to have it. >> >> Could you tell us exactly why you want to do this? It seems sort of > strange. Also couldn't you pass the caller as an argument to your function? > > Hi, I don't know if it's strange, maybe, so tell me why. Or maybe it's me.... Maybe the fact I'm ? pure C coder for a longtime prevent me from thinking in Python, maybe my brain is only capable of thinking and viewing in C..... and maybe there's an obvious way to solve my problem that I can't see yet... or maybe it's because I'm French, genetically programed to live in the past ? ... so this mailing list is my starting point to improve my Python understanding. And now, something different : what I want to do, and why. I got a class that takes a file name in its __init__ method (it could be elsewhere, but why not here ?). Then, somewhere in that class, a method will do something with that file name, such as "try to open that file". If the file do esn't exist, bing ! I got an exception "I/O Error n?2 : file doesn't exist". That's nice, I of course catch this exception, but it's not enough for the user : What file are we talking about ? And how to tell the user what is that file, and make him understand he tell the app to use a file that doesn't exist ? And this is not enough for developer : where that error happened ? what class ? what method ? There is many solution, and mine is : - don't check for the existence of the file in __init__ - don't use a default value for the file name parameter in __init__ : coder MUST provide it. - try/catch open(this_file_name) and if I got an IOErro exception, I re-raise my own exception with : - the name of the class where that IOError occured - the name of the method in that class that make that error occured - the name of the file the method tried to opened - some other info to help diagnostic Then my exception object can : - log in a file dedicated to the team (so, just me for the moment) - and/or log in a file dedicated to the user And then the app can popup a message box or something like that. Currently, I'm thinking about "how to get that class/method name", easily, and make something usefull with that. I don't want to write the name of the method and the class each time I need to use my exception class, and I don't want to modify that name each time I'm doing a refactoring operation : I just want to do something like : except IOError, (errno, errmes): raise myexceptioniwanttobenice ("IO Error %d -> %s ('%s')" % (errno, errmes, self.__csv) ) And then I print somewhere a message like : Error in csv2db.getColumnFromCsv : IO Error 2 -> No such file or directory ('toto') What I don't want is to write something like : except IOError, (errno, errmes): raise myexceptioniwanttobenice ("cvs2db.getColumnFromCsv IO Error %d -> %s ('%s')" % (errno, errmes, self.__csv) ) I don't want because it's to much to write, and if I change the class name, I don't want to rewrite all my call to change that name. So, I was looking for a way to retrieve : The name of the class the object that throw the exception belongs to The name of the method in that class And I finally found those recipe with the sys._getframe call. My first solution, currently, is (I didn't yet rewrite it with the solution with the traceback module) : class argError(Exception): def __init__(self, callerClass, errorMessage): self.__class = callerClass.__class__.__name__ self.__method = sys._getframe(1).f_code.co_name self.__message = errorMessage def __str__(self): return "Error in %s.%s : %s" % (self.__class, self.__method, self.__message) And how I use it : try: f = open(self.__csv) except IOError, (errno, errmes): raise argError (self, "IO Error %d -> %s ('%s')" % (errno, errmes, self.__csv) ) I now will : - rewrite it with the solution with traceback module - read about that module and find how to get rid of the need to pass "self" as an argument in the call "raise argError (*self*, "IO Error %d -> %s ('%s')" % (errno, errmes, self.__csv) )". That call enable me to get the name of the class. All of that is a way to me to experiment Python, I try a lot of thing to understand, and then I will make a choice. But now, it's time to lunch. Did I gave you enough information about what I want ? Patrice -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Feb 14 13:10:20 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 14 Feb 2010 06:10:20 -0600 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> Message-ID: I see why you would want the error messages but why is the default error message not enough, that is why I am curious, and typically introspection on objects is not necessary (for example, people often want to convert a string into a variable name to store a value (say they have the string "foobar1" and they want to store the value "f" in the variable "foobar1", how do they change foobar1 to reference a string? well you can just use exec but the core issue is that there's really no reason to do it in the first place, they can just use a dictionary and store dict['foobar1'] = 'f' and it is functionally equivalent (without the danger in the code)). I get the feeling that your issue is the same sort of thing, where an easier solution exists but for whatever reason you don't see it. I don't know if this is true or not. Here's my take on this: >>> class x(object): def __init__(self, fname): self.temp = open(fname).read() >>> a = x('foobar') Traceback (most recent call last): File "", line 1, in # this is the module it's in a = x('foobar') # this is the line where I tried to initialize it File "", line 3, in __init__ # which called this function, which is the one that has the error self.temp = open(fname).read() #and the error occurred while trying to perform this operation IOError: [Errno 2] No such file or directory: 'foobar' #and the error was that the file 'foobar' could not be found. This is implicitly stated that 'x' is the class with the method that had the issue, and it was specifically the __init__ method, and the file that could not be read was called 'foobar'. How does this not satisfy your requirements? Is it the form of the output that you do not agree with (you want it all on one line?) I've never had issues with Python's exception statements, I've always had no trouble finding where exceptions occurred, and I'm not sure what information is missing from the traceback that you'd like to convey to the user. On Sun, Feb 14, 2010 at 5:33 AM, patrice laporte wrote: > > 2010/2/13 Luke Paireepinart > > >> >> On Sat, Feb 13, 2010 at 9:56 AM, patrice laporte wrote: >> >>> >>> Hi, >>> >>> Being in an exeption of my own, I want to print the name of the caller, >>> and I'm looking for a way to have it. >>> >>> Could you tell us exactly why you want to do this? It seems sort of >> strange. Also couldn't you pass the caller as an argument to your function? >> >> > Hi, > > I don't know if it's strange, maybe, so tell me why. Or maybe it's me.... > Maybe the fact I'm ? pure C coder for a longtime prevent me from thinking in > Python, maybe my brain is only capable of thinking and viewing in C..... and > maybe there's an obvious way to solve my problem that I can't see yet... or > maybe it's because I'm French, genetically programed to live in the past ? > ... so this mailing list is my starting point to improve my Python > understanding. > > And now, something different : what I want to do, and why. > > I got a class that takes a file name in its __init__ method (it could be > elsewhere, but why not here ?). Then, somewhere in that class, a method will > do something with that file name, such as "try to open that file". > > If the file do esn't exist, bing ! I got an exception "I/O Error n?2 : file > doesn't exist". > > That's nice, I of course catch this exception, but it's not enough for the > user : What file are we talking about ? And how to tell the user what is > that file, and make him understand he tell the app to use a file that > doesn't exist ? > And this is not enough for developer : where that error happened ? what > class ? what method ? > > There is many solution, and mine is : > > - don't check for the existence of the file in __init__ > - don't use a default value for the file name parameter in __init__ : coder > MUST provide it. > - try/catch open(this_file_name) and if I got an IOErro exception, I > re-raise my own exception with : > - the name of the class where that IOError occured > - the name of the method in that class that make that error occured > - the name of the file the method tried to opened > - some other info to help diagnostic > > Then my exception object can : > - log in a file dedicated to the team (so, just me for the moment) > - and/or log in a file dedicated to the user > > And then the app can popup a message box or something like that. > > Currently, I'm thinking about "how to get that class/method name", easily, > and make something usefull with that. > > I don't want to write the name of the method and the class each time I need > to use my exception class, and I don't want to modify that name each time > I'm doing a refactoring operation : I just want to do something like : > > except IOError, (errno, errmes): > raise myexceptioniwanttobenice ("IO Error %d -> %s ('%s')" % > (errno, errmes, self.__csv) ) > > And then I print somewhere a message like : > > Error in csv2db.getColumnFromCsv : IO Error 2 -> No such file or > directory ('toto') > > What I don't want is to write something like : > > except IOError, (errno, errmes): > raise myexceptioniwanttobenice ("cvs2db.getColumnFromCsv IO > Error %d -> %s ('%s')" % (errno, errmes, self.__csv) ) > > I don't want because it's to much to write, and if I change the class name, > I don't want to rewrite all my call to change that name. > > So, I was looking for a way to retrieve : > The name of the class the object that throw the exception belongs to > The name of the method in that class > > And I finally found those recipe with the sys._getframe call. > > My first solution, currently, is (I didn't yet rewrite it with the solution > with the traceback module) : > > class argError(Exception): > def __init__(self, callerClass, errorMessage): > self.__class = callerClass.__class__.__name__ > self.__method = sys._getframe(1).f_code.co_name > self.__message = errorMessage > > def __str__(self): > return "Error in %s.%s : %s" % (self.__class, self.__method, > self.__message) > > And how I use it : > > try: > f = open(self.__csv) > except IOError, (errno, errmes): > raise argError (self, "IO Error %d -> %s ('%s')" % (errno, > errmes, self.__csv) ) > > I now will : > - rewrite it with the solution with traceback module > - read about that module and find how to get rid of the need to pass "self" > as an argument in the call "raise argError (*self*, "IO Error %d -> %s > ('%s')" % (errno, errmes, self.__csv) )". That call enable me to get the > name of the class. > > All of that is a way to me to experiment Python, I try a lot of thing to > understand, and then I will make a choice. > > But now, it's time to lunch. Did I gave you enough information about what I > want ? > > Patrice > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Feb 14 13:12:33 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 14 Feb 2010 06:12:33 -0600 Subject: [Tutor] Editing html using python In-Reply-To: References: Message-ID: On Sun, Feb 14, 2010 at 5:10 AM, Amit Sethi wrote: > Hi I need to edit html programmatically . Sadly the html might be broken at > places . I was using BeautifulSoup but there were lots of problems and it is > also not maintained can some one guide me to any tutorials on editing html > using lxml . > This is a rather specific question and if you really just want tutorials why don't you just google for them? Or are you also asking in a roundabout way if anyone on the list has a better idea for parsing broken html? It would help if you would take the time to explain how the html is broken and what exactly "lost of problems" with BeautifulSoup were. Also I think beautifulsoup is part of the Python standardlib now, isn't it? Why do you think it is not maintained? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Feb 14 14:25:10 2010 From: kent37 at tds.net (Kent Johnson) Date: Sun, 14 Feb 2010 08:25:10 -0500 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> Message-ID: <1c2a2c591002140525k7c47b81ar9efc62b9896cdd7c@mail.gmail.com> On Sun, Feb 14, 2010 at 6:33 AM, patrice laporte wrote: > - try/catch open(this_file_name) and if I got an IOErro exception, I > re-raise my own exception with : > - the name of the class where that IOError occured > - the name of the method in that class that make that error occured > - the name of the file the method tried to opened > - some other info to help diagnostic > > Then my exception object can : > - log in a file dedicated to the team (so, just me for the moment) > - and/or log in a file dedicated to the user > > And then the app can popup a message box or something like that. For simple applications that run from the command line and just do one thing, it is often adequate to let the exceptions propagate to the top level of the program and abort it, printing the stack trace. If the programming is doing some kind of repeated processing and you don't want an error in one iteration to abort the rest of the processing, then catch the exception inthe loop and log the error, then continue. The logging module makes it pretty easy to log exceptions. You can even have it log a detailed error to a file and a shortened version to the console. For GUI programs I usually install an exception handler in the event loop so if there is a problem running any event the error is caught and logged and the program continues. Kent From kent37 at tds.net Sun Feb 14 14:30:37 2010 From: kent37 at tds.net (Kent Johnson) Date: Sun, 14 Feb 2010 08:30:37 -0500 Subject: [Tutor] Editing html using python In-Reply-To: References: Message-ID: <1c2a2c591002140530h54084b13ned63675fa719bfdd@mail.gmail.com> On Sun, Feb 14, 2010 at 6:10 AM, Amit Sethi wrote: > Hi I need to edit html programmatically . Sadly the html might be broken at > places . I was using BeautifulSoup but there were lots of problems and it is > also not maintained can some one guide me to any tutorials on editing html > using lxml . What version of BS are you using? 3.0.8 seems to be the best choice for Python 2.6. Kent From denis.spir at free.fr Sun Feb 14 14:30:51 2010 From: denis.spir at free.fr (spir) Date: Sun, 14 Feb 2010 14:30:51 +0100 Subject: [Tutor] file exception & behaviour (was: Getting caller name...) In-Reply-To: <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> Message-ID: <20100214143051.744f8388@o> On Sun, 14 Feb 2010 12:33:09 +0100 patrice laporte wrote: > 2010/2/13 Luke Paireepinart > > > > > > > On Sat, Feb 13, 2010 at 9:56 AM, patrice laporte wrote: > > > >> > >> Hi, > >> > >> Being in an exeption of my own, I want to print the name of the caller, > >> and I'm looking for a way to have it. > >> > >> Could you tell us exactly why you want to do this? It seems sort of > > strange. Also couldn't you pass the caller as an argument to your function? > > > > > Hi, > > I don't know if it's strange, maybe, so tell me why. Or maybe it's me.... > Maybe the fact I'm ? pure C coder for a longtime prevent me from thinking in > Python, maybe my brain is only capable of thinking and viewing in C..... and > maybe there's an obvious way to solve my problem that I can't see yet... or > maybe it's because I'm French, genetically programed to live in the past ? > ... so this mailing list is my starting point to improve my Python > understanding. > > And now, something different : what I want to do, and why. > > I got a class that takes a file name in its __init__ method (it could be > elsewhere, but why not here ?). Then, somewhere in that class, a method will > do something with that file name, such as "try to open that file". > > If the file do esn't exist, bing ! I got an exception "I/O Error n?2 : file > doesn't exist". > > That's nice, I of course catch this exception, but it's not enough for the > user : What file are we talking about ? And how to tell the user what is > that file, and make him understand he tell the app to use a file that > doesn't exist ? > And this is not enough for developer : where that error happened ? what > class ? what method ? > > There is many solution, and mine is : > > - don't check for the existence of the file in __init__ > - don't use a default value for the file name parameter in __init__ : coder > MUST provide it. > - try/catch open(this_file_name) and if I got an IOErro exception, I > re-raise my own exception with : > - the name of the class where that IOError occured > - the name of the method in that class that make that error occured > - the name of the file the method tried to opened > - some other info to help diagnostic > > Then my exception object can : > - log in a file dedicated to the team (so, just me for the moment) > - and/or log in a file dedicated to the user > > And then the app can popup a message box or something like that. > > Currently, I'm thinking about "how to get that class/method name", easily, > and make something usefull with that. > > I don't want to write the name of the method and the class each time I need > to use my exception class, and I don't want to modify that name each time > I'm doing a refactoring operation : I just want to do something like : > > except IOError, (errno, errmes): > raise myexceptioniwanttobenice ("IO Error %d -> %s ('%s')" % > (errno, errmes, self.__csv) ) > > And then I print somewhere a message like : > > Error in csv2db.getColumnFromCsv : IO Error 2 -> No such file or > directory ('toto') > > What I don't want is to write something like : > > except IOError, (errno, errmes): > raise myexceptioniwanttobenice ("cvs2db.getColumnFromCsv IO > Error %d -> %s ('%s')" % (errno, errmes, self.__csv) ) > > I don't want because it's to much to write, and if I change the class name, > I don't want to rewrite all my call to change that name. > > So, I was looking for a way to retrieve : > The name of the class the object that throw the exception belongs to > The name of the method in that class > > And I finally found those recipe with the sys._getframe call. > > My first solution, currently, is (I didn't yet rewrite it with the solution > with the traceback module) : > > class argError(Exception): > def __init__(self, callerClass, errorMessage): > self.__class = callerClass.__class__.__name__ > self.__method = sys._getframe(1).f_code.co_name > self.__message = errorMessage > > def __str__(self): > return "Error in %s.%s : %s" % (self.__class, self.__method, > self.__message) > > And how I use it : > > try: > f = open(self.__csv) > except IOError, (errno, errmes): > raise argError (self, "IO Error %d -> %s ('%s')" % (errno, > errmes, self.__csv) ) > > I now will : > - rewrite it with the solution with traceback module > - read about that module and find how to get rid of the need to pass "self" > as an argument in the call "raise argError (*self*, "IO Error %d -> %s > ('%s')" % (errno, errmes, self.__csv) )". That call enable me to get the > name of the class. > > All of that is a way to me to experiment Python, I try a lot of thing to > understand, and then I will make a choice. > > But now, it's time to lunch. Did I gave you enough information about what I > want ? > > Patrice First, here is a kind of implementation of your specification. I just wrote it because I had something similar in mind (a file proxy, not the special exception type) and a few time. But this is globally useless. See below more comments. ========== code =============== #!/usr/bin/env python # coding: utf-8 class FileError(Exception): NO_CALLER = "" def __init__(self, name, info, caller=None): if caller is None: caller = FileError.NO_CALLER self.name, self.caller, self.info = name, caller, info def __str__(self): text = "File error in %s.\nTried to open non-existent file '%s'\n%s" \ % (self.caller,self.name,self.info) logFile = open("error.log", 'w') logFile.write(text) logFile.close() return text class File(object): NAME_MESSAGE = "A File must have a name." FILE_MESSAGE = "File '%s' is closed." def __init__(self, name=None): ''' Init name. ''' if name is None: raise ValueError(File.NAME_MESSAGE) self.name = name self.file = None def __str__(self): ''' File output ''' return "File '%s'" %self.name def open(self, mode = 'r', caller=None): ''' (Try to) open actual file. ''' try: self.file = open(self.name, mode) except IOError, e: raise FileError(self.name, str(e), caller) print "%s is open in mode '%s'." %(self,mode) def close(self): ''' Close actual file. ''' if self.file is None: message = File.FILE_MESSAGE %self.name raise ValueError(message) self.file.close print "%s is closed." %self def __getattr__(self, key): ''' Delegate file method to actual file. ''' print "* method: %s" %key return getattr(self.file, key) def content(self): ''' Close actual file. ''' self.open(mode='r') content = self.read() self.close() return content def writeContent(self, content): ''' Close actual file. ''' self.open(mode='w') self.write(content) self.close() def test(): f = File("test.txt") print f f.open() for line in f.readlines(): print line.rstrip() f.close() print f.content() f.writeContent("foo bar baz") f = File("goo.txt") f.open('r', test) test() ================================= ========== output =============== File 'test.txt' File 'test.txt' is open in mode 'r'. * method: readlines foo bar baz File 'test.txt' is closed. File 'test.txt' is open in mode 'r'. * method: read File 'test.txt' is closed. foo bar baz File 'test.txt' is open in mode 'w'. * method: write File 'test.txt' is closed. Traceback (most recent call last): File "__essai__.py", line 73, in test() File "__essai__.py", line 72, in test f.open('r', test) File "__essai__.py", line 38, in open raise FileError(self.name, str(e), caller) __main__.FileError: File error in . Tried to open non-existent file 'goo.txt' [Errno 2] No such file or directory: 'goo.txt' ===================================== I think you do not need any special treatment of files to get all the info you need when errors occur. The file name and caller already appear in python error texts. In other words: FileError is useless: def test2(): f = file("goo.txt", 'r') test2() ==> Traceback (most recent call last): File "__essai__.py", line 77, in test2() File "__essai__.py", line 76, in test2 ************** f = file("goo.txt", 'r') IOError: [Errno 2] No such file or directory: 'goo.txt' But a file wrapper (or rather: a proxy) can be useful, i guess, to get a kind of "potential" File object type that behaves a bit differently, as illustrated above by transparent opening and closing in content() and writeContent() methods. (That's what I wanted to try, and I rather like it.) Denis PS: Les programmeurs fran?ais ne sont pas suppos?s avoir un capital de g?nes diff?rent, former une race ? part; mais il me semble bien pourtant que toi & moi sommes des programmeurs python pas comme les autres. ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Sun Feb 14 14:42:05 2010 From: denis.spir at free.fr (spir) Date: Sun, 14 Feb 2010 14:42:05 +0100 Subject: [Tutor] operators >> and & In-Reply-To: <20100213231727.7f08b984@o> References: <1266087514.23188.6.camel@opteron.dwabbott.com> <20100213231727.7f08b984@o> Message-ID: <20100214144205.282cf92e@o> Just reviewed this post and wonder whether the explanation is clear for anyone else as myself ;-) Denis On Sat, 13 Feb 2010 23:17:27 +0100 spir wrote: > On Sat, 13 Feb 2010 13:58:34 -0500 > David Abbott wrote: > > > I am attempting to understand this little program that converts a > > network byte order 32-bit integer to a dotted quad ip address. > > > > #!/usr/bin/python > > # Filename : int2ip.py > > > > MAX_IP = 0xffffffffL > > ip = 2130706433 > > > > def int2ip(l): > > if MAX_IP < l < 0: > > raise TypeError, "expected int between 0 and %d inclusive" % > > MAX_IP > > return '%d.%d.%d.%d' % (l>>24 & 255, l>>16 & 255, l>>8 & 255, l & > > 255) > > > > result = int2ip(ip) > > print result > > > > I don't understand the l>>24 & 255. > > > > from the docs; > > Right Shift a >> b rshift(a, b) > > Bitwise And a & b and_(a, b) > > > > thanks > > > > In addition to Steve's excellent explanation: > Shifting to the left n bits is equivalent to multiplying by 2^n. Shifting to the right n bits is equivalent to dividing by 2^n. Shifting to the right 8 bits is thus equivalent to dividing by 2^8=256; which means making each octet (in a long integer) one level less significant. > AND-ing is equivalent to masking (this is actually called a mask operating) all bits wich are not 1 in the mask. So AND-ing with 11111111=255 masks all bits except the ones of the least significant octet. > If you represent a 32-bit integer as 4 octets, or 8 hex digits, the picture is easier to catch: > n = 0x12345678 # 0x12345678 = abcd (b=0x34=52) > # to get b: > temp = n >> 16 # 0x00001234 = 00ab > b = temp & 255 # 0x00000034 = 000b > > You can perform the same operation without bit-level operators, using modulo and integer division. To understand this, again consider the "abcd" representation: this means a 32-bit integer can be seen as 4-digit number written in base 256 (yes!). Division by 256^n gets rid of n lowest digits, moving down all other ones. Modulo 256^n gets rid of digits in higher position than n. (This may help and fully catch the sense of "base n"). > n = 0x12345678 # 0x12345678 = abcd (b=0x34) > # to get b: > temp = n // (256**2) # 0x00001234 = 00ab > b = temp % 256 # 0x00000034 = 000b > > (examples untested) > Bit operations are by far faster, indeed. > > > Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Sun Feb 14 14:46:13 2010 From: denis.spir at free.fr (spir) Date: Sun, 14 Feb 2010 14:46:13 +0100 Subject: [Tutor] operators >> and & In-Reply-To: References: <1266087514.23188.6.camel@opteron.dwabbott.com> <20100213232831.5c1c1d83@o> <201002141221.49429.steve@pearwood.info> Message-ID: <20100214144613.3433139a@o> On Sun, 14 Feb 2010 09:16:18 -0000 "Alan Gauld" wrote: > In the case in point the & 255 keeps the coding style consistent > and provides an extra measure of protection against unexpected > oddities so I would keep it in there. You're right on that, Kent. My comment was rather wrong. Especially for consistent code I would now keep it, too. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From steve at pearwood.info Sun Feb 14 16:37:37 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Feb 2010 02:37:37 +1100 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> Message-ID: <201002150237.38504.steve@pearwood.info> On Sun, 14 Feb 2010 10:33:09 pm patrice laporte wrote: > I got a class that takes a file name in its __init__ method (it > could be elsewhere, but why not here ?). Then, somewhere in that > class, a method will do something with that file name, such as "try > to open that file". > > If the file do esn't exist, bing ! I got an exception "I/O Error n?2 > : file doesn't exist". Are you sure? What version of Python are you using? I get a completely different error message: >>> open("no such file.txt", "r") Traceback (most recent call last): File "", line 1, in IOError: [Errno 2] No such file or directory: 'no such file.txt' Note carefully that the exception shows you the file name. > That's nice, I of course catch this exception, but it's not enough > for the user : What file are we talking about ? And how to tell the > user what is that file, and make him understand he tell the app to > use a file that doesn't exist ? >>> try: ... open("no such file.txt", "r") ... except IOError, e: ... pass ... >>> e.filename 'no such file.txt' > And this is not enough for developer : where that error happened ? > what class ? what method ? All these things are displayed by the default traceback mechanism. -- Steven D'Aprano From shurui91 at gmail.com Sun Feb 14 16:44:56 2010 From: shurui91 at gmail.com (Shurui Liu (Aaron Liu)) Date: Sun, 14 Feb 2010 10:44:56 -0500 Subject: [Tutor] command error help In-Reply-To: <2b9003cf1002140744r70a77d0cic9e70427da626c06@mail.gmail.com> References: <2b9003cf1002140734l2dba2af5j29cb7c57e40c9404@mail.gmail.com> <2b9003cf1002140744r70a77d0cic9e70427da626c06@mail.gmail.com> Message-ID: <2b9003cf1002140744j40548ae3v2c6cd1ccc5192985@mail.gmail.com> SyntaxError: EOL while scanning single-quoted string. 2010/2/14 Shurui Liu (Aaron Liu) > Here is a program I need to run in putty.exe, but there is an error in it. > I cannot find out. When I ran this program, it mentions that the error is in > red line.It shows that "SyntaxError: EOL while scanning single-quoted > string." Would you please help me? Thank you! > > > # Useless Trivia > > # > # Gets personal information from the user and then > # prints true, but useless information about him or her > > name = raw_input("Hi. What's your name? ") > > age = raw_input("And how old are you? ") > > > age = int(age) > > weight = raw_input("Okay, last question. How many pounds do you weigh? ") > weight = int(weight) > > print "\nIf poet ee cummings were to email you, he'd address you as", name.lower() > > > ee_mad = name.upper() > print "But if ee were mad, he'd call you", ee_mad > > dog_years = age / 7 > print "\nDid you know that you're just", dog_years, "in dog years?" > > > > seconds = age * 365 * 24 * 60 * 60 > print "But you're also over", seconds, "seconds old." > > called = name * 5 > print "\nIf a small child were trying to get your attention, " \ > > > "your name would become:" > print called > > moon_weight = weight / 6.0 > print "\nDid you know that on the moon you would weigh only", moon_weight, "pounds?" > > sun_weight = weight * 27.1 > > print "But on the sun, you'd weigh", sun_weight, "(but, ah... not for long)." > > raw_input("\n\nPress the enter key to exit.") > > > > -- > Shurui Liu (Aaron Liu) > Computer Science & Engineering Technology > University of Toledo > > > > -- > Shurui Liu (Aaron Liu) > Computer Science & Engineering Technology > University of Toledo > -- Shurui Liu (Aaron Liu) Computer Science & Engineering Technology University of Toledo -------------- next part -------------- An HTML attachment was scrubbed... URL: From shurui91 at gmail.com Sun Feb 14 16:34:29 2010 From: shurui91 at gmail.com (Shurui Liu (Aaron Liu)) Date: Sun, 14 Feb 2010 10:34:29 -0500 Subject: [Tutor] command error help Message-ID: <2b9003cf1002140734l2dba2af5j29cb7c57e40c9404@mail.gmail.com> Here is a program I need to run in putty.exe, but there is an error in it. I cannot find out. When I ran this program, it mentions that the error is in red line. Would you please help me? Thank you! # Useless Trivia # # Gets personal information from the user and then # prints true, but useless information about him or her name = raw_input("Hi. What's your name? ") age = raw_input("And how old are you? ") age = int(age) weight = raw_input("Okay, last question. How many pounds do you weigh? ") weight = int(weight) print "\nIf poet ee cummings were to email you, he'd address you as", name.lower() ee_mad = name.upper() print "But if ee were mad, he'd call you", ee_mad dog_years = age / 7 print "\nDid you know that you're just", dog_years, "in dog years?" seconds = age * 365 * 24 * 60 * 60 print "But you're also over", seconds, "seconds old." called = name * 5 print "\nIf a small child were trying to get your attention, " \ "your name would become:" print called moon_weight = weight / 6.0 print "\nDid you know that on the moon you would weigh only", moon_weight, "pounds?" sun_weight = weight * 27.1 print "But on the sun, you'd weigh", sun_weight, "(but, ah... not for long)." raw_input("\n\nPress the enter key to exit.") -- Shurui Liu (Aaron Liu) Computer Science & Engineering Technology University of Toledo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 14 17:02:19 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Feb 2010 16:02:19 -0000 Subject: [Tutor] command error help References: <2b9003cf1002140734l2dba2af5j29cb7c57e40c9404@mail.gmail.com><2b9003cf1002140744r70a77d0cic9e70427da626c06@mail.gmail.com> <2b9003cf1002140744j40548ae3v2c6cd1ccc5192985@mail.gmail.com> Message-ID: "Shurui Liu (Aaron Liu)" wrote > SyntaxError: EOL while scanning single-quoted string. Yes, that sounds about right. But it doesn't add much. Can you print the entifre error message not just that single line? Or.... >> Here is a program I need to run in putty.exe, but there is an error in >> it. >> I cannot find out. When I ran this program, it mentions that the error >> is in >> red line. How are you running the code in putty. I don't get any red lines in my terminal... It suggests you might be using some other tool or IDE perhaps? Since I can't see any single quoted strings in your code we can't begin to guess what line the error pertains to. It might for example be one of the apostraphes thats causing the error? >> name = raw_input("Hi. What's your name? ") >> age = raw_input("And how old are you? ") >> age = int(age) >> >> weight = raw_input("Okay, last question. How many pounds do you weigh? >> ") >> weight = int(weight) >> >> print "\nIf poet ee cummings were to email you, he'd address you as", >> name.lower() >> ee_mad = name.upper() >> print "But if ee were mad, he'd call you", ee_mad >> >> dog_years = age / 7 >> print "\nDid you know that you're just", dog_years, "in dog years?" >> seconds = age * 365 * 24 * 60 * 60 >> print "But you're also over", seconds, "seconds old." >> >> called = name * 5 >> print "\nIf a small child were trying to get your attention, " \ >> >> "your name would become:" >> print called >> >> moon_weight = weight / 6.0 >> print "\nDid you know that on the moon you would weigh only", >> moon_weight, "pounds?" >> >> sun_weight = weight * 27.1 >> print "But on the sun, you'd weigh", sun_weight, "(but, ah... not for >> long)." >> >> raw_input("\n\nPress the enter key to exit.") -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Feb 14 17:17:23 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Feb 2010 16:17:23 -0000 Subject: [Tutor] Getting caller name without the help of"sys._getframe(1).f_code.co_name" ? References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> Message-ID: "patrice laporte" wrote > Maybe the fact I'm ? pure C coder for a longtime prevent me from thinking > in > Python, ... > And now, something different : what I want to do, and why. Based on that last line I think your brain is well on the way to thinking like a Python programmer! :-) Others have addressed your main issues. Alan G From grigor.kolev at gmail.com Sun Feb 14 20:10:40 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Sun, 14 Feb 2010 21:10:40 +0200 Subject: [Tutor] try MySQLdb Error Message-ID: <1266174640.22465.6.camel@dedal-laptop> Hi. I want to catch MySQL error. This is my code. -------------- next part -------------- A non-text attachment was scrubbed... Name: mail_list.py Type: text/x-python Size: 7776 bytes Desc: not available URL: From sierra_mtnview at sbcglobal.net Sun Feb 14 23:19:35 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 14 Feb 2010 14:19:35 -0800 Subject: [Tutor] A Stuborn Tab Problem in IDLE Message-ID: <4B7876F7.10806@sbcglobal.net> When I use F5 to execute a py program in IDLE, Win7, I get a tab error on an indented else. I've selected all and untabifed with 4 spaces several times, and get the same problem. I've tried re-typing the line with zero results. What next? I had been modifying the program repeatedly over several hours, and executing it without any trouble like this. -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From steve at pearwood.info Sun Feb 14 23:51:00 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Feb 2010 09:51:00 +1100 Subject: [Tutor] A Stuborn Tab Problem in IDLE In-Reply-To: <4B7876F7.10806@sbcglobal.net> References: <4B7876F7.10806@sbcglobal.net> Message-ID: <201002150951.01221.steve@pearwood.info> On Mon, 15 Feb 2010 09:19:35 am Wayne Watson wrote: > When I use F5 to execute a py program in IDLE, Win7, I get a tab > error on an indented else. I've selected all and untabifed with 4 > spaces several times, and get the same problem. I've tried re-typing > the line with zero results. What next? I had been modifying the > program repeatedly over several hours, and executing it without any > trouble like this. Can you copy and paste the exact error message displayed? -- Steven D'Aprano From steve at pearwood.info Mon Feb 15 00:34:00 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Feb 2010 10:34:00 +1100 Subject: [Tutor] operators >> and & In-Reply-To: References: <1266087514.23188.6.camel@opteron.dwabbott.com> <201002141221.49429.steve@pearwood.info> Message-ID: <201002151034.00384.steve@pearwood.info> On Sun, 14 Feb 2010 08:16:18 pm Alan Gauld wrote: > >> But glitches can occur from time to time... > > > > If Python had a glitch of the magnitude of right-shifting non-zero > > bits into a number, that would be not just a bug but a HUGE bug. > > Bit shifting is machine specific. Pardon me, but that's incorrect. Python is not assembly, or C, and the behaviour of bit shifting in Python is NOT machine specific. Python doesn't merely expose the native bit shift operations on native ints, it is a high-level object-oriented method with carefully defined semantics. http://docs.python.org/library/stdtypes.html#bit-string-operations-on-integer-types In Python, a left shift of n MUST return the equivalent of multiplication by 2**n, and a right shift MUST return the equivalent of integer division by 2**n. Any other result is a SERIOUS bug in Python of the same magnitude (and the same likelihood) as 10/2 returning 18. So while I bow to your knowledge of bit operations in assembler on obscure four bit processors, Python does not do that. (I'm not even sure if Python runs on any four bit CPUs!) Python is a high-level language, not an assembler, and the behaviour of the bit operators >> and << is guaranteed to be the same no matter what CPU you are using. (The only low-level ops that Python exposes are floating point ops: Python mostly does whatever the C library on your platform does.) > > It is certainly good practice if you are dealing with numbers which > > might be more than 24 bits to start with: > > Its more than good practice there, its essential. Hardly. There are other ways of truncating a number to 8 bits, e.g. by using n % 256. If you're dealing with signed numbers, using & 255 will throw away the sign bit, which may be undesirable. And of course, it isn't desirable (let alone essential) to truncate the number if you don't need an 8 bit number in the first place! [and discussing the case where you know your input is already 8 bits] > In the case in point the & 255 keeps the coding style consistent > and provides an extra measure of protection against unexpected > oddities so I would keep it in there. So you add unnecessary operations to be consistent? That's terrible practice. So if you have an operation like this: n = 12*i**3 + 7 and later on, you then want n = i+1, do you write: n = 1*i**1 + 1 instead to be "consistent"? I would hope not! > > cycles and needlessly complicating the code. The right way to guard > > against "this will never happen" scenarios is with assert: > > > > assert n.bit_length() <= 32 # or "assert 0 <= n < 2**32" > > I would accept the second condition but the mask is much faster. Premature (micro) optimizations is the root of all evil. An assert that can be turned off and not executed is infinitely faster than a bit shift which is always executed whether you want it or not. And either way, the 20 seconds I lose trying to interpret the bit ops when I read the code is far more important than the 0.000001 seconds I lose executing the assert :) > bit_length doesn't seem to work on any of my Pythons (2.5,2.6 and > 3.1) It won't work in 2.5 or 2.6. You're probably trying this: 123.bit_length() and getting a syntax error. That's because the Python parser sees the . and interprets it as a float, and 123.bit_length is not a valid decimal float. You need to either group the int, or refer to it by name: (123).bit_length() n = 123 n.bit_length() -- Steven D'Aprano From sierra_mtnview at sbcglobal.net Mon Feb 15 01:58:56 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 14 Feb 2010 16:58:56 -0800 Subject: [Tutor] A Stuborn Tab Problem in IDLE In-Reply-To: <201002150951.01221.steve@pearwood.info> References: <4B7876F7.10806@sbcglobal.net> <201002150951.01221.steve@pearwood.info> Message-ID: <4B789C50.8070307@sbcglobal.net> I'm not sure it's postable or attachable for this mail list. I'll give it a try. Attachments do work with other lists. On 2/14/2010 2:51 PM, Steven D'Aprano wrote: > On Mon, 15 Feb 2010 09:19:35 am Wayne Watson wrote: > >> When I use F5 to execute a py program in IDLE, Win7, I get a tab >> error on an indented else. I've selected all and untabifed with 4 >> spaces several times, and get the same problem. I've tried re-typing >> the line with zero results. What next? I had been modifying the >> program repeatedly over several hours, and executing it without any >> trouble like this. >> > Can you copy and paste the exact error message displayed? > > > > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From alan.gauld at btinternet.com Mon Feb 15 02:02:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Feb 2010 01:02:59 -0000 Subject: [Tutor] operators >> and & References: <1266087514.23188.6.camel@opteron.dwabbott.com><201002141221.49429.steve@pearwood.info> <201002151034.00384.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote > Pardon me, but that's incorrect. Python is not assembly, or C, and the > behaviour of bit shifting in Python is NOT machine specific. > > http://docs.python.org/library/stdtypes.html#bit-string-operations-on-integer-types > > In Python, a left shift of n MUST return the equivalent of > multiplication by 2**n, and a right shift MUST return the equivalent of > integer division by 2**n. Any other result is a SERIOUS bug in Python So it seems, I apologise, I had assumed that for bit shifting Python did indeed just pass it down to the C compiler which in turn passes it to the CPU. As someone who works a lot at the CPU level that's slightly dissappointing since it makes bit shifting predictable but unreliable from my perspective - I can't guarantee the effect on the CPU... But since it's never actually caused me a problem I won't lose sleep over it. > So while I bow to your knowledge of bit operations in assembler on > obscure four bit processors, I haven't used 4 bit CPUs since working on the millenium bug ~10 years ago but the same applies in higher order processors too. I only used a 4 bit CPU since you gave a 4 bit example. But given the above it's irrelevant, the language defines the behaviour and I was wrong about that. > Python does not do that. (I'm not even > sure if Python runs on any four bit CPUs!) Probably not but it does run on some 8 bit ones. >> > It is certainly good practice if you are dealing with numbers which >> > might be more than 24 bits to start with: >> >> Its more than good practice there, its essential. > > Hardly. There are other ways of truncating a number to 8 bits I meant the truncating was needed not the & mechanism. > [and discussing the case where you know your input is already 8 bits] >> In the case in point the & 255 keeps the coding style consistent >> and provides an extra measure of protection against unexpected >> oddities so I would keep it in there. > > So you add unnecessary operations to be consistent? That's terrible > practice. No but I don't mix two styles of guard. If I need a guard and I'm already using masks then I'll use a mask, I certainly wouldn't mix asserts and masks for similar functions. If I'm sure I don't need the guard then I definitely wouldn't add one just for consistency of style. > So if you have an operation like this: > > n = 12*i**3 + 7 > > and later on, you then want n = i+1, do you write: > > n = 1*i**1 + 1 No I'd write n = i+1 rather than n = lambda x: x+1(i) or even (if Python had such an incr function) n = incr(i) since the arithmetic version is more consistent that the function call or the lambda. >> > cycles and needlessly complicating the code. The right way to guard >> > against "this will never happen" scenarios is with assert: >> > >> > assert n.bit_length() <= 32 # or "assert 0 <= n < 2**32" >> >> I would accept the second condition but the mask is much faster. > > Premature (micro) optimizations is the root of all evil. An assert that > can be turned off and not executed is infinitely faster than a bit > shift which is always executed whether you want it or not. But I did want it :-) > And either way, the 20 seconds I lose trying to interpret the bit ops > when I read the code is far more important than the 0.000001 seconds I > lose executing the assert :) Ah, but to me bit ops are normal code so I don't lose time reading them. In fact I'd take longer to figure out the assert. Readability is all about idioms and if you do a lot of bit tweaking masking is the normal idiom. (The only difference is that I would have used hex rather than decimal numbers for the masks - because I read bit patterns in hex faster than in decimal) >> bit_length doesn't seem to work on any of my Pythons (2.5,2.6 and >> 3.1) > > It won't work in 2.5 or 2.6. You're probably trying this: > > 123.bit_length() Indeed, I tried using a variable and it worked. Thanks for that I hadn't come across bit_length() before. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 15 02:05:16 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Feb 2010 01:05:16 -0000 Subject: [Tutor] A Stuborn Tab Problem in IDLE References: <4B7876F7.10806@sbcglobal.net> Message-ID: "Wayne Watson" wrote > When I use F5 to execute a py program in IDLE, Win7, I get a tab error > on an indented else. What happens if you execute from a command line? Do you get the same error? If so look at the lines before. If not try closing and restarting IDLE HTH, Alan G From sierra_mtnview at sbcglobal.net Mon Feb 15 03:14:35 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 14 Feb 2010 18:14:35 -0800 Subject: [Tutor] A Stuborn Tab Problem in IDLE In-Reply-To: References: <4B7876F7.10806@sbcglobal.net> Message-ID: <4B78AE0B.5090200@sbcglobal.net> I rebooted, and no change. I saved it under a new name, and no change. I tried to activate it as a file, and it put up a screen and down that I had no chance to read it. Since I have been on W7 for a month, have no clue as how to run it from a command line. I'll check with help, and report back. Maybe stuffing it in a txt file with NotePad might reveal something. On 2/14/2010 5:05 PM, Alan Gauld wrote: > > "Wayne Watson" wrote >> When I use F5 to execute a py program in IDLE, Win7, I get a tab >> error on an indented else. > > What happens if you execute from a command line? Do you get the same > error? > If so look at the lines before. > If not try closing and restarting IDLE > > HTH, > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From sierra_mtnview at sbcglobal.net Mon Feb 15 03:18:39 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 14 Feb 2010 18:18:39 -0800 Subject: [Tutor] A Stuborn Tab Problem in IDLE In-Reply-To: References: <4B7876F7.10806@sbcglobal.net> Message-ID: <4B78AEFF.9090202@sbcglobal.net> Well, command line was easy to get to. It's on the menu for python, but it gives me >>>. How do I get to the folder with the py file? Can I switch to a c:\ type operation? Back to exploring. On 2/14/2010 5:05 PM, Alan Gauld wrote: > > "Wayne Watson" wrote >> When I use F5 to execute a py program in IDLE, Win7, I get a tab >> error on an indented else. > > What happens if you execute from a command line? Do you get the same > error? > If so look at the lines before. > If not try closing and restarting IDLE > > HTH, > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From sierra_mtnview at sbcglobal.net Mon Feb 15 03:37:35 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 14 Feb 2010 18:37:35 -0800 Subject: [Tutor] A Stuborn Tab Problem in IDLE In-Reply-To: <4B78AEFF.9090202@sbcglobal.net> References: <4B7876F7.10806@sbcglobal.net> <4B78AEFF.9090202@sbcglobal.net> Message-ID: <4B78B36F.1030004@sbcglobal.net> I got to the dos command line facility and got to the file. I executed the program, and it failed with a syntax error. I can't copy it out of the window to paste here, but here's the code surrounding the problem: (arrow ==> points at the problem. The console code shows [ missing. I SEE the syntax error. It's two lines above the line with the arrow. The code now works. Thanks very much. Console wins again! (I suspect you are not into matplotlib, but the plot requires a list for x and y in plot(x,y). xy[0,0] turns out to be a float64, which the syntax rejects. I put [] around it, and it works. Is there a better way? ax1.plot([xy[0,0]],[xy[0,1]],'gs') if npts == 90: # exactly 90 frames ax1.plot([xy[npts-1,0]], xy[npts-1,1]],'rs') # mark it is a last frame else: ax1.plot([xy[npts-1,0]], ==>[xy[npts-1,1]],'ys') # mark 90th frame in path last_pt = len(xy[:,0]) ax1.plot([xy[npts-1,0]],[xy[npts-1,1]],'rs') On 2/14/2010 6:18 PM, Wayne Watson wrote: > Well, command line was easy to get to. It's on the menu for python, > but it gives me >>>. How do I get to the folder with the py file? > Can I switch to a c:\ type operation? > > Back to exploring. > > On 2/14/2010 5:05 PM, Alan Gauld wrote: >> >> "Wayne Watson" wrote >>> When I use F5 to execute a py program in IDLE, Win7, I get a tab >>> error on an indented else. >> >> What happens if you execute from a command line? Do you get the same >> error? >> If so look at the lines before. >> If not try closing and restarting IDLE >> >> HTH, >> >> Alan G >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From davea at ieee.org Mon Feb 15 04:01:19 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 14 Feb 2010 22:01:19 -0500 Subject: [Tutor] A Stuborn Tab Problem in IDLE In-Reply-To: <4B78B36F.1030004@sbcglobal.net> References: <4B7876F7.10806@sbcglobal.net> <4B78AEFF.9090202@sbcglobal.net> <4B78B36F.1030004@sbcglobal.net> Message-ID: <4B78B8FF.4030005@ieee.org> Wayne Watson wrote: >
I got to > the dos command line facility and got to the file. I executed the > program, and it failed with a syntax error. I can't copy it out of the > window to paste here, but here's the code surrounding the problem: > (arrow ==> points at the problem. > The console code shows [ missing. I SEE the syntax error. It's two > lines above the line with the arrow. The code now works. Thanks very > much. Console wins again! > > (I suspect you are not into matplotlib, but the plot requires a list > for x and y in plot(x,y). xy[0,0] turns out to be a float64, which the > syntax rejects. I put [] around it, and it works. Is there a better way? > > ax1.plot([xy[0,0]],[xy[0,1]],'gs') > if npts == 90: # exactly 90 frames > ax1.plot([xy[npts-1,0]], xy[npts-1,1]],'rs') # mark it is > a last frame > else: > ax1.plot([xy[npts-1,0]], ==>[xy[npts-1,1]],'ys') # mark > 90th frame in path > last_pt = len(xy[:,0]) > ax1.plot([xy[npts-1,0]],[xy[npts-1,1]],'rs') > > On 2/14/2010 6:18 PM, Wayne Watson wrote: >> Well, command line was easy to get to. It's on the menu for python, >> but it gives me >>>. How do I get to the folder with the py file? >> Can I switch to a c:\ type operation? >> >> Back to exploring. >> >> On 2/14/2010 5:05 PM, Alan Gauld wrote: >>> >>> "Wayne Watson" wrote >>>> When I use F5 to execute a py program in IDLE, Win7, I get a tab >>>> error on an indented else. >>> >>> What happens if you execute from a command line? Do you get the same >>> error? >>> If so look at the lines before. >>> If not try closing and restarting IDLE >>> >>> HTH, >>> >>> Alan G >>> Once you've discovered the DOS box, you should also discover QuickEdit mode. In the DOS box, right click on the title bar, and choose "Properties". First tab is Options. Enable Quick-Edit mode, and press OK. Now, you can drag a rectangle on the DOS box, and use right click to paste it to the clipboard. Practice a bit and you'll find it easy. An essential tool. DaveA From sierra_mtnview at sbcglobal.net Mon Feb 15 06:47:04 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 14 Feb 2010 21:47:04 -0800 Subject: [Tutor] A Stuborn Tab Problem in IDLE In-Reply-To: <4B78B8FF.4030005@ieee.org> References: <4B7876F7.10806@sbcglobal.net> <4B78AEFF.9090202@sbcglobal.net> <4B78B36F.1030004@sbcglobal.net> <4B78B8FF.4030005@ieee.org> Message-ID: <4B78DFD8.3060802@sbcglobal.net> Thanks for the reminder on that. I haven't need the DOS box for 8 months. Just off on other non-programming efforts for the most part. Things have picked up of late. I was beginning to think for awhile that Win7 might have dropped it. I don't see any changes to it. On 2/14/2010 7:01 PM, Dave Angel wrote: > Wayne Watson wrote: >>
I got to >> the dos command line facility and got to the file. I executed the >> program, and it failed with a syntax error. I can't copy it out of >> the window to paste here, >>>> "Wayne Watson" wrote >>>>> When I use F5 to execute a py program in IDLE, Win7, I get a tab >>>>> error on an indented else. >>>> >>>> What happens if you execute from a command line? Do you get the >>>> same error? >>>> If so look at the lines before. >>>> If not try closing and restarting IDLE >>>> >>>> HTH, >>>> >>>> Alan G >>>> > Once you've discovered the DOS box, you should also discover QuickEdit > mode. In the DOS box, right click on the title bar, and choose > "Properties". First tab is Options. Enable Quick-Edit mode, and > press OK. Now, you can drag a rectangle on the DOS box, and use right > click to paste it to the clipboard. Practice a bit and you'll find it > easy. An essential tool. > > DaveA > > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From stefan_ml at behnel.de Mon Feb 15 09:25:41 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 15 Feb 2010 09:25:41 +0100 Subject: [Tutor] Editing html using python In-Reply-To: References: Message-ID: Luke Paireepinart, 14.02.2010 13:12: > Also I think beautifulsoup is part of the Python standardlib now, isn't it? No, it's not. Stefan From alan.gauld at btinternet.com Mon Feb 15 09:31:07 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Feb 2010 08:31:07 -0000 Subject: [Tutor] A Stuborn Tab Problem in IDLE References: <4B7876F7.10806@sbcglobal.net> <4B78AEFF.9090202@sbcglobal.net><4B78B36F.1030004@sbcglobal.net> <4B78B8FF.4030005@ieee.org> <4B78DFD8.3060802@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Thanks for the reminder on that. I haven't need the DOS box for 8 > months. Just off on other non-programming efforts for the most part. > Things have picked up of late. I was beginning to think for awhile that > Win7 might have dropped it. I don't see any changes to it. Its worth running HELP on CMD and reading through it. MS usually add a few extra tricks with each new OS. And if nothing else it will remind you of the settings and registry tweaks you need to get the most out of the DOS box. The default settings are very limited. Alan G. From alan.gauld at btinternet.com Mon Feb 15 10:00:21 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Feb 2010 09:00:21 -0000 Subject: [Tutor] Editing html using python References: Message-ID: "Luke Paireepinart" wrote > with BeautifulSoup were. Also I think beautifulsoup is part of the > Python > standardlib now, isn't it? Why do you think it is not maintained? I think you may be getting confused with element tree which is part of the standard lib? BS is still an add-on. Alan G. From zepangolin at gmail.com Mon Feb 15 12:07:51 2010 From: zepangolin at gmail.com (patrice laporte) Date: Mon, 15 Feb 2010 12:07:51 +0100 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> Message-ID: <954757881002150307reeeddb7lb95ab0f09a0d69f9@mail.gmail.com> 2010/2/14 Luke Paireepinart > I see why you would want the error messages but why is the default error > message not enough, that is why I am curious, and typically introspection on > objects is not necessary (for example, people often want to convert a string > into a variable name to store a value (say they have the string "foobar1" > and they want to store the value "f" in the variable "foobar1", how do they > change foobar1 to reference a string? well you can just use exec but the > core issue is that there's really no reason to do it in the first place, > they can just use a dictionary and store dict['foobar1'] = 'f' and it is > functionally equivalent (without the danger in the code)). I get the > feeling that your issue is the same sort of thing, where an easier solution > exists but for whatever reason you don't see it. I don't know if this is > true or not. Here's my take on this: > > >>> class x(object): > def __init__(self, fname): > self.temp = open(fname).read() > > > >>> a = x('foobar') > > Traceback (most recent call last): > File "", line 1, in # this is the > module it's in > a = x('foobar') # > this is the line where I tried to initialize it > File "", line 3, in __init__ # which called > this function, which is the one that has the error > self.temp = open(fname).read() #and the error > occurred while trying to perform this operation > IOError: [Errno 2] No such file or directory: 'foobar' #and the error was > that the file 'foobar' could not be found. > > Hi and thank to everybody... First of all, I consider my first question is now answered : I wanted to get rid of that sys._getframe call, I got an explanation (thanks to Kent). The rest of the discussion is not about Python, it's more about the way of thinking how to help the user having ? good feeling with your app. I try to clarify my need and share you my anxiety. Of course, a lot of thing are available with Python, from a coder point of view. But what I want to do is to think about the user, and give him a way to understand that what he did was wrong. Traceback give me all I need, but my opinion is that it's not acceptable to give it back to the user without a minimum of "d?corating". I didn't yet look at the logging module, and maybe it can help me to make that d?corating. And the user must be a priority (it's still my conviction here) My own experience is that there is too much coder that forget the app they work on is aim to be used by "real human", not by C/C++/Python/put what ever you want here/ guru : if your app popups to the user a message that is just what the traceback gave, it's not a good thing : How can it be reasonable to imagine the user will read that kinda message ? : *Traceback (most recent call last): File "", line 1, in a = x('foobar') File "", line 3, in __init__ self.temp = open(fname).read() IOError: [Errno 2] No such file or directory: 'foobar' * Of course the origin of his problem is in the message : "*No such file or directory: 'foobar'*", but a customer will never read that @?^$#? uggly message, there is too much extraterrestrial words in it. Traceback doesn' give more thant that, it doesn't say, as an example : we (the name of app) was trying to open the file "foobar" in order to do something with it (put here what it was supposed to do with the file) : app failed to open it because "foobar" doen't exist. According to me, traceback is what we need during "coding" phases, but it's not something to give to the user. This problem has to be solved by thinking the app in the way I'm trying to explain (but not only in that way) : think about the user. This is not something I expect Python to do for me, I'm just looking for everything Python can provide me to make me think about the user. I'm new to Python, and I make a lot of exploration to understand and answer myself to my question. Python library is huge, and I don't have as enough time as I wanted to deal with it. But I'm conviced the solutions are here, I don't try to re-invent the wheel... Thant to you all. -------------- next part -------------- An HTML attachment was scrubbed... URL: From amit.pureenergy at gmail.com Mon Feb 15 13:28:06 2010 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Mon, 15 Feb 2010 17:58:06 +0530 Subject: [Tutor] Editing html using python In-Reply-To: References: Message-ID: Well ya I was kind of hoping to know about more tools and recommendations on how to edit broken html . Their were tags that I wanted to replace using beautifulSoup however i saw that the replacewith function was not available for many of the tags I wanted to replace . Also BeautifulSoup does not have unicode support . So in a sense I did want recommendation perhaps I should have put my question in a better manner . -------------- next part -------------- An HTML attachment was scrubbed... URL: From peterjohnanderson at gmail.com Mon Feb 15 13:34:11 2010 From: peterjohnanderson at gmail.com (pja) Date: Mon, 15 Feb 2010 23:34:11 +1100 Subject: [Tutor] Problem with "input" in Python 3 Message-ID: <4B793F43.3070304@gmail.com> Hi! I am trying to teach myself how to program in Python using Zelle's "Python Programming: An Introduction to Computer Science" (a very good text). At the same time I have decided to start with Python 3 (3.1.1). That means that I have to convert Zelle's example code to Python 3 (which generally I cope with). I'm hoping that somebody can help with what's probably a very simple problem. There is a quadratic equation example involving multiple user inputs from the one "input" statement. The code works fine with Python 2.5 but when I convert it to Python 3 I get error messages. The code looks like: 05 import math 06 07 def main(): 08 print("This program finds the real solutions to a quadratic\n") 09 10 a, b, c = input("Please enter the coefficients (a, b, c): ") 11 12 ''' 13 a = int(input("Please enter the first coefficient: ")) 14 b = int(input("Please enter the second coefficient: ")) 15 c = int(input("Please enter the third coefficient: ")) 16 ''' 17 18 discrim = b * b - 4 * a * c 19 ... 25 main() Lines 08 to 12 are my Python 3 working solution but line 06 does not work in Python 3. When it runs it produces: Please enter the coefficients (a, b, c): 1,2,3 Traceback (most recent call last): File "C:\Program Files\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 25, in File "C:\Program Files\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 10, in main builtins.ValueError: too many values to unpack >>> Clearly the problem lies in the input statement. If I comment out line 10 and remove the comments at lines 12 and 16 then the program runs perfectly. However, I feel this is a clumsy solution. Could somebody please guide me on the correct use of "input" for multiple values. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From peter.anderson at internode.on.net Mon Feb 15 13:09:23 2010 From: peter.anderson at internode.on.net (Peter Anderson) Date: Mon, 15 Feb 2010 23:09:23 +1100 Subject: [Tutor] Problem with "input" in Python 3 Message-ID: <4B793973.2000102@internode.on.net> Hi! I am trying to teach myself how to program in Python using Zelle's "Python Programming: An Introduction to Computer Science" (a very good text). At the same time I have decided to start with Python 3 (3.1.1). That means that I have to convert Zelle's example code to Python 3 (which generally I cope with). I'm hoping that somebody can help with what's probably a very simple problem. There is a quadratic equation example involving multiple user inputs from the one "input" statement. The code works fine with Python 2.5 but when I convert it to Python 3 I get error messages. The code looks like: 05 import math 06 07 def main(): 08 print("This program finds the real solutions to a quadratic\n") 09 10 a, b, c = input("Please enter the coefficients (a, b, c): ") 11 12 ''' 13 a = int(input("Please enter the first coefficient: ")) 14 b = int(input("Please enter the second coefficient: ")) 15 c = int(input("Please enter the third coefficient: ")) 16 ''' 17 18 discrim = b * b - 4 * a * c 19 ... 25 main() Lines 08 to 12 are my Python 3 working solution but line 06 does not work in Python 3. When it runs it produces: Please enter the coefficients (a, b, c): 1,2,3 Traceback (most recent call last): File "C:\Program Files\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 25, in File "C:\Program Files\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 10, in main builtins.ValueError: too many values to unpack >>> Clearly the problem lies in the input statement. If I comment out line 10 and remove the comments at lines 12 and 16 then the program runs perfectly. However, I feel this is a clumsy solution. Could somebody please guide me on the correct use of "input" for multiple values. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From cwitts at compuscan.co.za Mon Feb 15 13:56:40 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 15 Feb 2010 14:56:40 +0200 Subject: [Tutor] Problem with "input" in Python 3 In-Reply-To: <4B793F43.3070304@gmail.com> References: <4B793F43.3070304@gmail.com> Message-ID: <4B794488.8030804@compuscan.co.za> pja wrote: > Hi! > > I am trying to teach myself how to program in Python using Zelle's > "Python Programming: An Introduction to Computer Science" (a very good > text). At the same time I have decided to start with Python 3 (3.1.1). > That means that I have to convert Zelle's example code to Python 3 > (which generally I cope with). > > I'm hoping that somebody can help with what's probably a very simple > problem. There is a quadratic equation example involving multiple user > inputs from the one "input" statement. The code works fine with Python > 2.5 but when I convert it to Python 3 I get error messages. The code > looks like: > > 05 import math > 06 > 07 def main(): > 08 print("This program finds the real solutions to a quadratic\n") > 09 > 10 a, b, c = input("Please enter the coefficients (a, b, c): ") > 11 > 12 ''' > 13 a = int(input("Please enter the first coefficient: ")) > 14 b = int(input("Please enter the second coefficient: ")) > 15 c = int(input("Please enter the third coefficient: ")) > 16 ''' > 17 > 18 discrim = b * b - 4 * a * c > 19 ... > > 25 main() > > Lines 08 to 12 are my Python 3 working solution but line 06 does not > work in Python 3. When it runs it produces: > > Please enter the coefficients (a, b, c): 1,2,3 > Traceback (most recent call last): > File "C:\Program Files\Wing IDE 101 > 3.2\src\debug\tserver\_sandbox.py", line 25, in > File "C:\Program Files\Wing IDE 101 > 3.2\src\debug\tserver\_sandbox.py", line 10, in main > builtins.ValueError: too many values to unpack > >>> > > Clearly the problem lies in the input statement. If I comment out line > 10 and remove the comments at lines 12 and 16 then the program runs > perfectly. However, I feel this is a clumsy solution. > > Could somebody please guide me on the correct use of "input" for > multiple values. > > Regards, > Peter You will need to split your input. no_input = True while no_input: in = input("Please enter the coefficients (a, b, c): ") try: a, b, c = map(int, in.split(',')) no_input = False except ValueError: print("Please enter your input in a comma-seperated format with no space. Only 3 numbers allowed") That will loop allowing input until the person enters 3 numbers seperated purely by commas in for input. -- Kind Regards, Christian Witts Business Intelligence C o m p u s c a n | Confidence in Credit Telephone: +27 21 888 6000 National Cell Centre: 0861 51 41 31 Fax: +27 21 413 2424 E-mail: cwitts at compuscan.co.za NOTE: This e-mail (including attachments )is subject to the disclaimer published at: http://www.compuscan.co.za/live/content.php?Item_ID=494. If you cannot access the disclaimer, request it from email.disclaimer at compuscan.co.za or 0861 514131. National Credit Regulator Credit Bureau Registration No. NCRCB6 From stefan_ml at behnel.de Mon Feb 15 13:53:52 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 15 Feb 2010 13:53:52 +0100 Subject: [Tutor] Editing html using python In-Reply-To: References: Message-ID: Amit Sethi, 15.02.2010 13:28: > Well ya I was kind of hoping to know about more tools and recommendations on > how to edit broken html. You already found lxml, don't think you can do any better. Note that you shouldn't "edit broken html" but "fix broken HTML and then edit correct HTML". Writing out broken HTML after editing it is likely not what you want. > Their were tags that I wanted to replace using beautifulSoup > however i saw that the replacewith function was not available for many of > the tags I wanted to replace. To understand your problem better, it would be helpful if you provided more information, such as the names of the tags and a short example code snippet that showed what you were trying to do. > Also BeautifulSoup does not have unicode support. Try to learn a tool before making blatantly false claims about it. > So in a sense I did want recommendation perhaps I should have put my > question in a better manner. That's a very good idea. This will help: http://catb.org/~esr/faqs/smart-questions.html Stefan From kent37 at tds.net Mon Feb 15 13:59:32 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Feb 2010 07:59:32 -0500 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <954757881002150307reeeddb7lb95ab0f09a0d69f9@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> <954757881002150307reeeddb7lb95ab0f09a0d69f9@mail.gmail.com> Message-ID: <1c2a2c591002150459l29f60f21ia00a99bae8a7d26f@mail.gmail.com> On Mon, Feb 15, 2010 at 6:07 AM, patrice laporte wrote: > My own experience is that there is too much coder that forget the app they > work on is aim to be used by "real human", not by C/C++/Python/put what ever > you want here/ guru : if your app popups to the user a message that is just > what the traceback gave, it's not a good thing : How can it be reasonable to > imagine the user will read that kinda message ? : > > Traceback (most recent call last): > ? File "", line 1, in > ??? a = x('foobar') > ? File "", line 3, in __init__ > ??? self.temp = open(fname).read() > IOError: [Errno 2] No such file or directory: 'foobar' > > Of course the origin of his problem is in the message : "No such file or > directory: 'foobar'", but a customer will never read that @?^$#? uggly > message, there is too much extraterrestrial words in it. It's easy to give the user just the actual error message, either the full IOError: [Errno 2] No such file or directory: 'foobar' or slightly friendlier: No such file or directory: 'foobar' Then log the full trackback to a file. If the user needs help, ask them to send you the log file. They never see the full traceback and you get all the information available. > Traceback doesn' give more thant that, it doesn't say, as an example : we > (the name of app) was trying to open the file "foobar" in order to do > something with it (put here what it was supposed to do with the file) : app > failed to open it because "foobar" doen't exist. In a GUI app the user will often know what was happening, because they asked to do it. Often it is more useful to give context from the point where the exception is caught because that is a higher-level location than the point of failure. When you catch the exception you can tell the user Error processing No such file or directory: 'foobar' This will make more sense than the low-level details of the error. > According to me, traceback is what we need during "coding" phases, but it's > not something to give to the user. > > This problem has to be solved by thinking the app in the way I'm trying to > explain? (but not only in that way) : think about the user. This is not > something I expect Python to do for me, I'm just looking for everything > Python can provide me to make me think about the user. This is a good goal. I'm not sure it requires wrapping the exception mechanism to achieve it. Kent From kent37 at tds.net Mon Feb 15 14:05:19 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Feb 2010 08:05:19 -0500 Subject: [Tutor] Editing html using python In-Reply-To: References: Message-ID: <1c2a2c591002150505m741d417dufb13d2e69d5effb@mail.gmail.com> On Mon, Feb 15, 2010 at 7:28 AM, Amit Sethi wrote: > Well ya I was kind of hoping to know about more tools and recommendations on > how to edit broken html . This page lists several alternatives: html5, lxml, elementtree: http://www.crummy.com/software/BeautifulSoup/3.1-problems.html > Their were tags that I wanted to replace using > beautifulSoup > however i saw that the replacewith function was not available for many of > the tags I > wanted to replace . Also BeautifulSoup does not have unicode support . ?? http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit Kent From kent37 at tds.net Mon Feb 15 14:09:26 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 15 Feb 2010 08:09:26 -0500 Subject: [Tutor] Problem with "input" in Python 3 In-Reply-To: <4B793F43.3070304@gmail.com> References: <4B793F43.3070304@gmail.com> Message-ID: <1c2a2c591002150509y29849c8cr4fe7fba2ea09fa70@mail.gmail.com> On Mon, Feb 15, 2010 at 7:34 AM, pja wrote: > 05 import math > 06 > 07 def main(): > 08 print("This program finds the real solutions to a quadratic\n") > 09 > 10 a, b, c = input("Please enter the coefficients (a, b, c): ") > 11 > 12 ''' > 13 a = int(input("Please enter the first coefficient: ")) > 14 b = int(input("Please enter the second coefficient: ")) > 15 c = int(input("Please enter the third coefficient: ")) > 16 ''' > 17 > 18 discrim = b * b - 4 * a * c > 19 ... > > 25 main() > > Lines 08 to 12 are my Python 3 working solution but line 06 does not work in > Python 3. When it runs it produces: > > Please enter the coefficients (a, b, c): 1,2,3 > Traceback (most recent call last): > File "C:\Program Files\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line > 25, in > File "C:\Program Files\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line > 10, in main > builtins.ValueError: too many values to unpack >>>> > > Clearly the problem lies in the input statement. If I comment out line 10 > and remove the comments at lines 12 and 16 then the program runs perfectly. > However, I feel this is a clumsy solution. > > Could somebody please guide me on the correct use of "input" for multiple > values. Python 3 input() is the same as Python 2 raw_input() - the result is a string. You could use a, b, c = ast.literal_eval(input("Please enter the coefficients (a, b, c): ")) Kent From waynejwerner at gmail.com Mon Feb 15 14:10:57 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 15 Feb 2010 07:10:57 -0600 Subject: [Tutor] Problem with "input" in Python 3 In-Reply-To: <4B793973.2000102@internode.on.net> References: <4B793973.2000102@internode.on.net> Message-ID: <333efb451002150510t66d0c650mcff40e94f2883fd8@mail.gmail.com> On Mon, Feb 15, 2010 at 6:09 AM, Peter Anderson < peter.anderson at internode.on.net> wrote: > Hi! > > I am trying to teach myself how to program in Python using Zelle's "Python > Programming: An Introduction to Computer Science" (a very good text). At the > same time I have decided to start with Python 3 (3.1.1). That means that I > have to convert Zelle's example code to Python 3 (which generally I cope > with). > > I'm hoping that somebody can help with what's probably a very simple > problem. There is a quadratic equation example involving multiple user > inputs from the one "input" statement. The code works fine with Python 2.5 > but when I convert it to Python 3 I get error messages. The code looks like: > > 05 import math > 06 > 07 def main(): > 08 print("This program finds the real solutions to a quadratic\n") > 09 > 10 a, b, c = input("Please enter the coefficients (a, b, c): ") > 11 > 12 ''' > 13 a = int(input("Please enter the first coefficient: ")) > 14 b = int(input("Please enter the second coefficient: ")) > 15 c = int(input("Please enter the third coefficient: ")) > 16 ''' > 17 > 18 discrim = b * b - 4 * a * c > 19 ... > > 25 main() > > Lines 08 to 12 are my Python 3 working solution but line 06 does not work > in Python 3. When it runs it produces: > > Please enter the coefficients (a, b, c): 1,2,3 > Traceback (most recent call last): > File "C:\Program Files\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", > line 25, in > File "C:\Program Files\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", > line 10, in main > builtins.ValueError: too many values to unpack > >>> > > Clearly the problem lies in the input statement. If I comment out line 10 > and remove the comments at lines 12 and 16 then the program runs perfectly. > However, I feel this is a clumsy solution. > > Could somebody please guide me on the correct use of "input" for multiple > values. > First off, it's much healthier to use "raw_input", and then try to convert it (float, int, whatever). Example: In [1]: x = input("Test: ") Test: print "Ha ha, this is some input" ------------------------------------------------------------ File "", line 1 print "Ha ha, this is some input" ^ SyntaxError: invalid syntax In [3]: x = raw_input("Test: ") Test: print "ha ha, this is some raw_input" In [4]: x Out[4]: 'print "ha ha, this is some raw_input"' The first one is susceptible to people inserting malicious code (at least in pre-3.0 versions). The reason your code is throwing an error is input (or raw_input) gives you one value, and you're trying to assign it to three variables. If you want to get 3 floating point values, the most concise (but maybe not so readable if you're not familiar with the syntax) is probably this: a, b, c = [float(x) for x in raw_input("Please enter (a, b, c): ").split()] Example: In [6]: a, b, c = [float(x) for x in raw_input("Please enter (a, b, c): ").split()] Please enter (a, b, c): 3.1 2.99 1 In [7]: a Out[7]: 3.1000000000000001 In [8]: b Out[8]: 2.9900000000000002 In [9]: c Out[9]: 1.0 to understand what the above code is doing: print raw_input("Please enter (a,b, c): ") print raw_input("Please enter (a,b, c): ").split() print [x for x in raw_input("Please enter (a,b, c): ").split()] print [float(x) for x in raw_input("Please enter (a,b, c): ").split()] HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Feb 15 14:11:09 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 15 Feb 2010 08:11:09 -0500 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <954757881002150307reeeddb7lb95ab0f09a0d69f9@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> <954757881002150307reeeddb7lb95ab0f09a0d69f9@mail.gmail.com> Message-ID: <4B7947ED.1060000@ieee.org> patrice laporte wrote: > 2010/2/14 Luke Paireepinart > > >> I see why you would want the error messages but why is the default error >> message not enough, that is why I am curious, and typically introspection on >> objects is not necessary (for example, people often want to convert a string >> into a variable name to store a value (say they have the string "foobar1" >> and they want to store the value "f" in the variable "foobar1", how do they >> change foobar1 to reference a string? well you can just use exec but the >> core issue is that there's really no reason to do it in the first place, >> they can just use a dictionary and store dict['foobar1'] = 'f' and it is >> functionally equivalent (without the danger in the code)). I get the >> feeling that your issue is the same sort of thing, where an easier solution >> exists but for whatever reason you don't see it. I don't know if this is >> true or not. Here's my take on this: >> >> >>>>> class x(object): >>>>> >> def __init__(self, fname): >> self.temp = open(fname).read() >> >> >> >>>>> a = x('foobar') >>>>> >> Traceback (most recent call last): >> File "", line 1, in # this is the >> module it's in >> a = x('foobar') # >> this is the line where I tried to initialize it >> File "", line 3, in __init__ # which called >> this function, which is the one that has the error >> self.temp = open(fname).read() #and the error >> occurred while trying to perform this operation >> IOError: [Errno 2] No such file or directory: 'foobar' #and the error was >> that the file 'foobar' could not be found. >> >> >> > Hi and thank to everybody... > > First of all, I consider my first question is now answered : I wanted to get > rid of that sys._getframe call, I got an explanation (thanks to Kent). > > The rest of the discussion is not about Python, it's more about the way of > thinking how to help the user having ? good feeling with your app. > > I try to clarify my need and share you my anxiety. Of course, a lot of thing > are available with Python, from a coder point of view. But what I want to do > is to think about the user, and give him a way to understand that what he > did was wrong. > > Traceback give me all I need, but my opinion is that it's not acceptable to > give it back to the user without a minimum of "d?corating". I didn't yet > look at the logging module, and maybe it can help me to make that > d?corating. > > And the user must be a priority (it's still my conviction here) > > My own experience is that there is too much coder that forget the app they > work on is aim to be used by "real human", not by C/C++/Python/put what ever > you want here/ guru : if your app popups to the user a message that is just > what the traceback gave, it's not a good thing : How can it be reasonable to > imagine the user will read that kinda message ? : > > *Traceback (most recent call last): > File "", line 1, in > a = x('foobar') > File "", line 3, in __init__ > self.temp = open(fname).read() > IOError: [Errno 2] No such file or directory: 'foobar' > * > > Of course the origin of his problem is in the message : "*No such file or > directory: 'foobar'*", but a customer will never read that @?^$#? uggly > message, there is too much extraterrestrial words in it. > > Traceback doesn' give more thant that, it doesn't say, as an example : we > (the name of app) was trying to open the file "foobar" in order to do > something with it (put here what it was supposed to do with the file) : app > failed to open it because "foobar" doen't exist. > > According to me, traceback is what we need during "coding" phases, but it's > not something to give to the user. > > This problem has to be solved by thinking the app in the way I'm trying to > explain (but not only in that way) : think about the user. This is not > something I expect Python to do for me, I'm just looking for everything > Python can provide me to make me think about the user. > > I'm new to Python, and I make a lot of exploration to understand and answer > myself to my question. Python library is huge, and I don't have as enough > time as I wanted to deal with it. But I'm conviced the solutions are here, I > don't try to re-invent the wheel... > > > Thant to you all. > > This makes lots of sense. If the message doesn't make sense to the user, there's no point. But why then is your thread titled "Getting caller name" ? Why does the user care about the caller (function) name? When you started the thread, it seemed clear that your user was a programmer, presumably who was adding code to your system and who wanted to see context error messages in coding terms. If you have a duality of users, consider using a "DEBUG" variable, that changes the amount of detail you display upon an error. DaveA From peterjohnanderson at gmail.com Mon Feb 15 14:16:49 2010 From: peterjohnanderson at gmail.com (pja) Date: Tue, 16 Feb 2010 00:16:49 +1100 Subject: [Tutor] Problem with "input" in Python 3 In-Reply-To: <4B794488.8030804@compuscan.co.za> References: <4B794488.8030804@compuscan.co.za> Message-ID: <4B794941.5020002@gmail.com> Christian, You are a genius! There was one minor bug; the variable "in" needed to be changed to something like "in_value" and it works perfectly. Many thanks for that. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From davea at ieee.org Mon Feb 15 14:20:35 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 15 Feb 2010 08:20:35 -0500 Subject: [Tutor] Problem with "input" in Python 3 In-Reply-To: <4B793973.2000102@internode.on.net> References: <4B793973.2000102@internode.on.net> Message-ID: <4B794A23.2090605@ieee.org> Peter Anderson wrote: >
Hi! > > I am trying to teach myself how to program in Python using Zelle's > "Python Programming: An Introduction to Computer Science" (a very good > text). At the same time I have decided to start with Python 3 (3.1.1). > That means that I have to convert Zelle's example code to Python 3 > (which generally I cope with). > > I'm hoping that somebody can help with what's probably a very simple > problem. There is a quadratic equation example involving multiple user > inputs from the one "input" statement. The code works fine with Python > 2.5 but when I convert it to Python 3 I get error messages. The code > looks like: > > 05 import math > 06 > 07 def main(): > 08 print("This program finds the real solutions to a quadratic\n") > 09 > 10 a, b, c = input("Please enter the coefficients (a, b, c): ") > 11 > 12 ''' > 13 a = int(input("Please enter the first coefficient: ")) > 14 b = int(input("Please enter the second coefficient: ")) > 15 c = int(input("Please enter the third coefficient: ")) > 16 ''' > 17 > 18 discrim = b * b - 4 * a * c > 19 ... > > 25 main() > > Lines 08 to 12 are my Python 3 working solution but line 06 does not > work in Python 3. When it runs it produces: > > Please enter the coefficients (a, b, c): 1,2,3 > Traceback (most recent call last): > File "C:\Program Files\Wing IDE 101 > 3.2\src\debug\tserver\_sandbox.py", line 25, in > File "C:\Program Files\Wing IDE 101 > 3.2\src\debug\tserver\_sandbox.py", line 10, in main > builtins.ValueError: too many values to unpack > >>> > > Clearly the problem lies in the input statement. If I comment out line > 10 and remove the comments at lines 12 and 16 then the program runs > perfectly. However, I feel this is a clumsy solution. > > Could somebody please guide me on the correct use of "input" for > multiple values. > > Regards, > Peter The input() function in Python3 produces a string, and does not evaluate it into integers, or into a tuple, or whatever. See for yourself by trying print ( repr(input("prompt ")) ) on both systems. You can subvert Python3's improvement by adding an eval to the return value. a, b, c = eval(input("Enter exactly three numbers, separated by commas")) is roughly equivalent to Python 2.x input expression. (Python 3's input is equivalent to Python 2.x raw_input) DaveA From zepangolin at gmail.com Mon Feb 15 14:27:22 2010 From: zepangolin at gmail.com (patrice laporte) Date: Mon, 15 Feb 2010 14:27:22 +0100 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <4B7947ED.1060000@ieee.org> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> <954757881002150307reeeddb7lb95ab0f09a0d69f9@mail.gmail.com> <4B7947ED.1060000@ieee.org> Message-ID: <954757881002150527h2fbe7a59t6ac250acec23dd61@mail.gmail.com> 2010/2/15 Dave Angel > > This makes lots of sense. If the message doesn't make sense to the user, > there's no point. But why then is your thread titled "Getting caller name" > ? Why does the user care about the caller (function) name? When you > started the thread, it seemed clear that your user was a programmer, > presumably who was adding code to your system and who wanted to see context > error messages in coding terms. > > If you have a duality of users, consider using a "DEBUG" variable, that > changes the amount of detail you display upon an error. > > DaveA > > No, it's not, I don't have duality at all... As I said in a previous answer, when I started the thread, I was looking for a way not to use sys._getframe. And I have now both the answer and an explanation. But someone asked me "why do you want to do this ? explain it to us." And I started to explain, and the thread then moved to new horizon, driffting to other consideration : the user. To answer you, the user I think about is the one who use the application, not the programmer. But yes, the user who need to know the "caller name" is the programmer, and that programmer must think himself as the other user, the first one. This is just my point of view : never forget the final user. So, maybe we can close that thread now ? But any new question/answer is wellcome thanks. Patrice -------------- next part -------------- An HTML attachment was scrubbed... URL: From peterjohnanderson at gmail.com Mon Feb 15 14:29:31 2010 From: peterjohnanderson at gmail.com (pja) Date: Tue, 16 Feb 2010 00:29:31 +1100 Subject: [Tutor] Problem with "input" in Python 3 In-Reply-To: <1c2a2c591002150509y29849c8cr4fe7fba2ea09fa70@mail.gmail.com> References: <1c2a2c591002150509y29849c8cr4fe7fba2ea09fa70@mail.gmail.com> Message-ID: <4B794C3B.4020500@gmail.com> Kent, Thanks! That works well! Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From stefan_ml at behnel.de Mon Feb 15 14:32:44 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 15 Feb 2010 14:32:44 +0100 Subject: [Tutor] Editing html using python In-Reply-To: <1c2a2c591002150505m741d417dufb13d2e69d5effb@mail.gmail.com> References: <1c2a2c591002150505m741d417dufb13d2e69d5effb@mail.gmail.com> Message-ID: Kent Johnson, 15.02.2010 14:05: > On Mon, Feb 15, 2010 at 7:28 AM, Amit Sethi wrote: >> Well ya I was kind of hoping to know about more tools and recommendations on >> how to edit broken html . > > This page lists several alternatives: html5, lxml, elementtree: > http://www.crummy.com/software/BeautifulSoup/3.1-problems.html Except that elementtree isn't an alternative as it can't parse HTML. The ElementSoup module uses the BS parser to create an ElementTree, not the other way round. That's reported incorrectly on that page. Stefan From yaraslau.shanhin at gmail.com Mon Feb 15 15:23:02 2010 From: yaraslau.shanhin at gmail.com (Yaraslau Shanhin) Date: Mon, 15 Feb 2010 15:23:02 +0100 Subject: [Tutor] Input() is not working as expected in Python 3.1 Message-ID: Hello All, I am working with Python tutorial in wiki and one of the exercises is as follows: Ask the user for a string, and then for a number. Print out that string, that many times. (For example, if the string is hello and the number is 3 you should print out hellohellohello.) Solution for this exercise is: text = str(raw_input("Type in some text: ")) number = int(raw_input("How many times should it be printed? "))print (text * number) Since in Python raw_input() function was renamed to input() according to PEP 3111 I have respectively updated this code to: text = str(input("Type in some text: ")) number = int(input("How many times should it be printed? "))print (text * number) However when I try to execute this code in Python 3.1 interpreter error message is generated: Type in some text: some How many times should it be printed? 3 Traceback (most recent call last): File "test4.py", line 2, in number = int(input("How many times should it be printed? ")) ValueError: invalid literal for int() with base 10: 'How many times should it be printed? 3' Can you please advise me how to resolve this issue? -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Feb 15 15:48:45 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 15 Feb 2010 08:48:45 -0600 Subject: [Tutor] Input() is not working as expected in Python 3.1 In-Reply-To: References: Message-ID: <333efb451002150648n7f1f3682yff7a286ed54b7923@mail.gmail.com> On Mon, Feb 15, 2010 at 8:23 AM, Yaraslau Shanhin < yaraslau.shanhin at gmail.com> wrote: > Hello All, > > I am working with Python tutorial in wiki and one of the exercises is as > follows: > > Ask the user for a string, and then for a number. Print out that string, > that many times. (For example, if the string is hello and the number is 3 you > should print out hellohellohello.) > > Solution for this exercise is: > > text = str(raw_input("Type in some text: ")) > number = int(raw_input("How many times should it be printed? "))print (text * number) > > > > Since in Python raw_input() function was renamed to input() according to PEP 3111 I have respectively updated this code to: > > > text = str(input("Type in some text: ")) > > This str() is redundant - input returns a string by default. > > number = int(input("How many times should it be printed? "))print (text * number) > > > > However when I try to execute this code in Python 3.1 interpreter error message is generated: > > > Type in some text: some > How many times should it be printed? 3 > Traceback (most recent call last): > File "test4.py", line 2, in > number = int(input("How many times should it be printed? ")) > ValueError: invalid literal for int() with base 10: 'How many times should it be printed? 3' > > That means you're having an issue with getting something that isn't just a number. try: number = input("How many ... ") print (number) number = int(number) print (number) HTH, Wayne > > Can you please advise me how to resolve this issue? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > 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 davea at ieee.org Mon Feb 15 16:03:45 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 15 Feb 2010 10:03:45 -0500 Subject: [Tutor] Input() is not working as expected in Python 3.1 In-Reply-To: References: Message-ID: <4B796251.70402@ieee.org> Yaraslau Shanhin wrote: > Hello All, > > I am working with Python tutorial in wiki and one of the exercises is as > follows: > > Ask the user for a string, and then for a number. Print out that string, > that many times. (For example, if the string is hello and the number is 3 you > should print out hellohellohello.) > > Solution for this exercise is: > > text = str(raw_input("Type in some text: ")) > number = int(raw_input("How many times should it be printed? "))print > (text * number) > > > > Since in Python raw_input() function was renamed to input() according > to PEP 3111 I have > respectively updated this code to: > > > text = str(input("Type in some text: ")) > number = int(input("How many times should it be printed? "))print > (text * number) > > > > However when I try to execute this code in Python 3.1 interpreter > error message is generated: > > > Type in some text: some > How many times should it be printed? 3 > Traceback (most recent call last): > File "test4.py", line 2, in > number = int(input("How many times should it be printed? ")) > ValueError: invalid literal for int() with base 10: 'How many times > should it be printed? 3' > > > Can you please advise me how to resolve this issue? > > When I correct for your missing newline, it works for me. I don't know of any version of Python which would copy the prompt string into the result value of input or raw_input() function. Try pasting the exact console session, rather than paraphrasing it. DaveA From bgailer at gmail.com Mon Feb 15 16:06:42 2010 From: bgailer at gmail.com (bob gailer) Date: Mon, 15 Feb 2010 10:06:42 -0500 Subject: [Tutor] Input() is not working as expected in Python 3.1 In-Reply-To: References: Message-ID: <4B796302.3000101@gmail.com> Yaraslau Shanhin wrote: > Hello All, Hello. Suggestion for future questions - just include enough to identify the problem. We don't need to know that this is from a tutorial or what the exercise is. Also (at least I prefer) plain text without formatting or color. Sufficient therefore is: ------------------------------------------- using Python 3.1: text = str(input("Type in some text: ")) number = int(input("How many times should it be printed? ")) Traceback (most recent call last): File "test4.py", line 2, in number = int(input("How many times should it be printed? ")) ValueError: invalid literal for int() with base 10: ------------------------------------------- Now carefully read the message "invalid literal for int()". This tells you the argument to int is not a string representation of an integer. There is nothing wrong with input()! Since we don't know what you typed at the input() prompt we can't diagnose it further. One way to solve problems like these is to capture and print the output of input(): text = str(input("Type in some text: ")) snumber = input("How many times should it be printed?") print snumber A good robust alternative is to try int() and capture / report the failure: text = str(input("Type in some text: ")) snumber = input("How many times should it be printed?") try: number = int(snumber) except ValueError: print(number, "is not an integer.") else: print (text * number) -- Bob Gailer 919-636-4239 Chapel Hill NC From yaraslau.shanhin at gmail.com Mon Feb 15 16:15:12 2010 From: yaraslau.shanhin at gmail.com (Yaraslau Shanhin) Date: Mon, 15 Feb 2010 16:15:12 +0100 Subject: [Tutor] Input() is not working as expected in Python 3.1 In-Reply-To: <4B796302.3000101@gmail.com> References: <4B796302.3000101@gmail.com> Message-ID: Code: text = str(input("Type in some text: ")) number = int(input("How many times should it be printed? ")) print (text * number) Output: Type in some text: some How many times should it be printed? 5 Traceback (most recent call last): File "test4.py", line 2, in number = int(input("How many times should it be printed? ")) ValueError: invalid literal for int() with base 10: 'How many times should it be printed? 5' That is exactly how it looks like. It is happening all the time when I run program in Komodo Edit, but in IDLE everything works fine (interpreter is the same): Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> text = str(input("Type in some text: ")) Type in some text: some >>> number = int(input("How many times should it be printed? ")) How many times should it be printed? 5 >>> print (text * number) somesomesomesomesome >>> For your suggestion Code: text = str(input("Type in some text: ")) snumber = input("How many times should it be printed?") try: number = int(snumber) except ValueError: print(ssnumber, "is not an integer.") else: print (text * snumber) Output: Type in some text: some How many times should it be printed?5 How many times should it be printed?5 is not an integer. On Mon, Feb 15, 2010 at 4:06 PM, bob gailer wrote: > Yaraslau Shanhin wrote: > > > Hello All, > > Hello. > > Suggestion for future questions - just include enough to identify the > problem. We don't need to know that this is from a tutorial or what the > exercise is. Also (at least I prefer) plain text without formatting or > color. > > Sufficient therefore is: > > ------------------------------------------- > using Python 3.1: > > text = str(input("Type in some text: ")) > number = int(input("How many times should it be printed? ")) > > Traceback (most recent call last): > File "test4.py", line 2, in > number = int(input("How many times should it be printed? ")) > ValueError: invalid literal for int() with base 10: > ------------------------------------------- > > Now carefully read the message "invalid literal for int()". This tells you > the argument to int is not a string representation of an integer. There is > nothing wrong with input()! > > Since we don't know what you typed at the input() prompt we can't diagnose > it further. One way to solve problems like these is to capture and print the > output of input(): > > > text = str(input("Type in some text: ")) > snumber = input("How many times should it be printed?") > print snumber > > A good robust alternative is to try int() and capture / report the failure: > > > text = str(input("Type in some text: ")) > snumber = input("How many times should it be printed?") > try: > number = int(snumber) > except ValueError: > print(number, "is not an integer.") > else: > print (text * number) > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Mon Feb 15 16:45:08 2010 From: roadierich at googlemail.com (Rich Lovely) Date: Mon, 15 Feb 2010 15:45:08 +0000 Subject: [Tutor] Input() is not working as expected in Python 3.1 In-Reply-To: References: <4B796302.3000101@gmail.com> Message-ID: On 15 February 2010 15:15, Yaraslau Shanhin wrote: > Code: > text = str(input("Type in some text: ")) > number = int(input("How many times should it be printed? ")) > print (text * number) > Output: > Type in some text: some > How many times should it be printed? 5 > Traceback (most recent call last): > ??File "test4.py", line 2, in > ?? ?number = int(input("How many times should it be printed? ")) > ValueError: invalid literal for int() with base 10: 'How many times should > it be printed? 5' > > That is exactly how it looks like. It is?happening?all the time when I run > program in Komodo Edit, but in IDLE everything works fine (interpreter is > the same): > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] > on win32 > Type "copyright", "credits" or "license()" for more information. >>>> text = str(input("Type in some text: ")) > Type in some text: some >>>> number = int(input("How many times should it be printed? ")) > How many times should it be printed? 5 >>>> print (text * number) > somesomesomesomesome >>>> > For your suggestion > Code: > text = str(input("Type in some text: ")) > snumber = input("How many times should it be printed?") > try: > ?number = int(snumber) > except ValueError: > ?print(ssnumber, "is not an integer.") > else: > ?print (text * snumber) > > > Output: > Type in some text: some > How many times should it be printed?5 > How many times should it be printed?5 is not an integer. > On Mon, Feb 15, 2010 at 4:06 PM, bob gailer wrote: >> >> Yaraslau Shanhin wrote: >> >> > Hello All, >> >> Hello. >> >> Suggestion for future questions - just include enough to identify the >> problem. We don't need to know that this is from a tutorial or what the >> exercise is. Also (at least I prefer) plain text without formatting or >> color. >> >> Sufficient therefore is: >> >> ------------------------------------------- >> using ?Python 3.1: >> text = str(input("Type in some text: ")) >> number = int(input("How many times should it be printed? ")) >> >> Traceback (most recent call last): >> File "test4.py", line 2, in >> ? number = int(input("How many times should it be printed? ")) >> ValueError: invalid literal for int() with base 10: >> ------------------------------------------- >> >> Now carefully read the message "invalid literal for int()". This tells you >> the argument to int is not a string representation of an integer. There is >> nothing wrong with input()! >> >> Since we don't know what you typed at the input() prompt we can't diagnose >> it further. One way to solve problems like these is to capture and print the >> output of input(): >> >> text = str(input("Type in some text: ")) >> snumber = input("How many times should it be printed?") >> print snumber >> >> A good robust alternative is to try int() and capture / report the >> failure: >> >> text = str(input("Type in some text: ")) >> snumber = input("How many times should it be printed?") >> try: >> ?number = int(snumber) >> except ValueError: >> ?print(number, "is not an integer.") >> else: >> ?print (text * number) >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC >> > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > This is a known bug with Komodo (see http://bugs.activestate.com/show_bug.cgi?id=71319). The developers are working on it, by the looks of things. -- Rich "Roadie Rich" Lovely Just because you CAN do something, doesn't necessarily mean you SHOULD. In fact, more often than not, you probably SHOULDN'T. Especially if I suggested it. 10 re-discover BASIC 20 ??? 30 PRINT "Profit" 40 GOTO 10 From zstumgoren at gmail.com Mon Feb 15 17:14:32 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 15 Feb 2010 11:14:32 -0500 Subject: [Tutor] Editing html using python In-Reply-To: References: <1c2a2c591002150505m741d417dufb13d2e69d5effb@mail.gmail.com> Message-ID: In the few cases I had where BeautifulSoup couldn't handle poorly formed HTML, I've found that html5lib was able to get the job done. And of course, lxml is great too, but has a bit more overhead installation-wis. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zepangolin at gmail.com Mon Feb 15 21:32:07 2010 From: zepangolin at gmail.com (patrice laporte) Date: Mon, 15 Feb 2010 21:32:07 +0100 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <201002150237.38504.steve@pearwood.info> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> <954757881002140333m2e839324v441aa81de06b51ac@mail.gmail.com> <201002150237.38504.steve@pearwood.info> Message-ID: <954757881002151232m6a7bb3b4m5012db40825a3016@mail.gmail.com> 2010/2/14 Steven D'Aprano > > > If the file do esn't exist, bing ! I got an exception "I/O Error n?2 > > : file doesn't exist". > > Are you sure? What version of Python are you using? I get a completely > different error message: > > Yes I'm not sure .... when I wrote : *I got an exception "I/O Error n?2 : file doesn't exist".* It was just to stress the point, it was not the real message. >>> open("no such file.txt", "r") > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 2] No such file or directory: 'no such file.txt' > And of course, If I do this, I got the same traceback, and I can see the file name. > >>> try: > ... open("no such file.txt", "r") > ... except IOError, e: > ... pass > ... > >>> e.filename > 'no such file.txt' > > This is it, this way to catch the exception what I wanted. Reading the documentation and articles over the web, I found that : try: f = open("bling") except IOError, (errno, errmes): # that way, I can only print the erreor number and the message # but the message doesn't contain the file name, and it confused me because traceback can # give it. So where to find it ? But with your example, I can access all attribute I can read doing >>*help(e) *in the interpreter* * With documentation, I understood filename is an attribute, but I didn't understand how to use it. The part of the documentation about 'buil-tins Exception' and the other part about "how to handle exceptin" didn't help me, there is something I missed about how to handle exception. Thank you for this help, I will look closer again to exception. Many thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From grigor.kolev at gmail.com Mon Feb 15 22:02:30 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Mon, 15 Feb 2010 23:02:30 +0200 Subject: [Tutor] Input() is not working as expected in Python 3.1 In-Reply-To: <4B796302.3000101@gmail.com> References: <4B796302.3000101@gmail.com> Message-ID: <1266267750.27745.3.camel@dedal-laptop> ? 10:06 -0500 ?? 15.02.2010 (??), bob gailer ??????: > Yaraslau Shanhin wrote: > > > Hello All, > > Hello. > > Suggestion for future questions - just include enough to identify the > problem. We don't need to know that this is from a tutorial or what the > exercise is. Also (at least I prefer) plain text without formatting or > color. > > Sufficient therefore is: > > ------------------------------------------- > using Python 3.1: > text = str(input("Type in some text: ")) > number = int(input("How many times should it be printed? ")) > > Traceback (most recent call last): > File "test4.py", line 2, in > number = int(input("How many times should it be printed? ")) > ValueError: invalid literal for int() with base 10: > ------------------------------------------- > > Now carefully read the message "invalid literal for int()". This tells > you the argument to int is not a string representation of an integer. > There is nothing wrong with input()! > > Since we don't know what you typed at the input() prompt we can't > diagnose it further. One way to solve problems like these is to capture > and print the output of input(): > > text = str(input("Type in some text: ")) > snumber = input("How many times should it be printed?") > print snumber > > A good robust alternative is to try int() and capture / report the failure: > > text = str(input("Type in some text: ")) > snumber = input("How many times should it be printed?") > try: > number = int(snumber) > except ValueError: > print(number, "is not an integer.") > else: > print (text * number) > Try this: >>>text = str(input("Type in some text: ")) Type in some text:"some text" >>>snumber = int(input("How many times should it be printed?")) How many times should it be printed?3 >>>print text*snumber -- Grigor Kolev From sierra_mtnview at sbcglobal.net Mon Feb 15 22:50:18 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 15 Feb 2010 13:50:18 -0800 Subject: [Tutor] A Stuborn Tab Problem in IDLE In-Reply-To: <4B7957E3.1000105@mwalsh.org> References: <4B7876F7.10806@sbcglobal.net> <4B78AEFF.9090202@sbcglobal.net> <4B78B36F.1030004@sbcglobal.net> <4B795742.1000207@mwalsh.org> <4B7957E3.1000105@mwalsh.org> Message-ID: <4B79C19A.8010807@sbcglobal.net> I've found there's quite a bit of discrepancy in top vs bottom posting. It's hardly worth thinking about. I seem to navigate through top, bottom or mixed. The real problem, IMHO, is very long posts from various people. Marty > Ah ha! Sorry for the noise, I should really read the whole message > before pressing send. :-D Glad you fixed the problem. > > > -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From peterjohnanderson at gmail.com Tue Feb 16 00:02:12 2010 From: peterjohnanderson at gmail.com (pja) Date: Tue, 16 Feb 2010 10:02:12 +1100 Subject: [Tutor] Problem with "input" in Python 3 In-Reply-To: <4B794941.5020002@gmail.com> References: <4B794941.5020002@gmail.com> Message-ID: <4B79D274.4010004@gmail.com> Here is an interesting solution that I developed using the EasyGUI (http://easygui.sourceforge.net/) graphics library: # 7.2_quadratic2easy.py # A program that computes the real roots of a quadratic equation. # Bad version using a simple if to avoid program crash # This version uses the EasyGUI graphics library # See http://easygui.sourceforge.net/ for EasyGUI details import math from easygui import * def main(): msg = "This program finds the real solutions to a quadratic" + "\n" + \ "Please enter the three coefficients below." title = "quadratic2easy.py" fieldNames = ["First coefficient","Second coefficient","Third coefficient"] fieldValues = [] # we start with blanks for the values fieldValues = multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) print("Reply was:", fieldValues) a = int(fieldValues[0]) b = int(fieldValues[1]) c = int(fieldValues[2]) discrim = a * a - 4 * b * c if discrim >= 0: discRoot = math.sqrt(discrim) root1 = (-a + discRoot) / (2 * b) root2 = (-a - discRoot) / (2 * b) message = "The real solutions to the quadratic equation are " + str(root1) + " and " + str(root2) msgbox(msg=message, title="quadratic2easy.py", ok_button="OK", image=None) main() Thanks to all those who provided advice; this is a great resource for us learners. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From peterjohnanderson at gmail.com Tue Feb 16 00:09:35 2010 From: peterjohnanderson at gmail.com (pja) Date: Tue, 16 Feb 2010 10:09:35 +1100 Subject: [Tutor] Problem with "input" in Python 3 In-Reply-To: <4B79D274.4010004@gmail.com> References: <4B79D274.4010004@gmail.com> Message-ID: <4B79D42F.6090703@gmail.com> Sorry about the previous post; I didn't check the code format before I posted the reply and thus lost all the indentation. Here I go again, hopefully with the correct indentation. # 7.2_quadratic2easy.py # A program that computes the real roots of a quadratic equation. # Bad version using a simple if to avoid program crash # This version uses the EasyGUI graphics library # See http://easygui.sourceforge.net/ for EasyGUI details import math from easygui import * def main(): msg = "This program finds the real solutions to a quadratic" + "\n" + \ "Please enter the three coefficients below." title = "quadratic2easy.py" fieldNames = ["First coefficient","Second coefficient","Third coefficient"] fieldValues = [] # we start with blanks for the values fieldValues = multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) print("Reply was:", fieldValues) a = int(fieldValues[0]) b = int(fieldValues[1]) c = int(fieldValues[2]) discrim = a * a - 4 * b * c if discrim >= 0: discRoot = math.sqrt(discrim) root1 = (-a + discRoot) / (2 * b) root2 = (-a - discRoot) / (2 * b) message = "The real solutions to the quadratic equation are " + str(root1) + " and " + str(root2) msgbox(msg=message, title="quadratic2easy.py", ok_button="OK", image=None) main() Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From peterjohnanderson at gmail.com Tue Feb 16 00:18:38 2010 From: peterjohnanderson at gmail.com (Peter Anderson) Date: Tue, 16 Feb 2010 10:18:38 +1100 Subject: [Tutor] Problem with "input" in Python 3 Message-ID: <456400161002151518l2dd43985r6a3efb0a11f48bef@mail.gmail.com> I seem to be having a formatting problem between Thunderbird on my PC and the mailing list; I am loosing all indentation. The Gmail account settings on Thunderbird are for plain text and I set the e-mail content to fixed width text so I'm not sure what's going wrong. I am trying one last time sending from Gmail (as fixed text). # 7.2_quadratic2easy.py # A program that computes the real roots of a quadratic equation. # Bad version using a simple if to avoid program crash # This version uses the EasyGUI graphics library # See http://easygui.sourceforge.net/ for EasyGUI details import math from easygui import * def main(): msg = "This program finds the real solutions to a quadratic" + "\n" + \ "Please enter the three coefficients below." title = "quadratic2easy.py" fieldNames = ["First coefficient","Second coefficient","Third coefficient"] fieldValues = [] # we start with blanks for the values fieldValues = multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) print("Reply was:", fieldValues) a = int(fieldValues[0]) b = int(fieldValues[1]) c = int(fieldValues[2]) discrim = a * a - 4 * b * c if discrim >= 0: discRoot = math.sqrt(discrim) root1 = (-a + discRoot) / (2 * b) root2 = (-a - discRoot) / (2 * b) message = "The real solutions to the quadratic equation are " + str(root1) + " and " + str(root2) msgbox(msg=message, title="quadratic2easy.py", ok_button="OK", image=None) main() -- There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things -- Niccolo Machiavelli, The Prince, ch. 6 From yaraslau.shanhin at gmail.com Tue Feb 16 08:21:29 2010 From: yaraslau.shanhin at gmail.com (Yaraslau Shanhin) Date: Tue, 16 Feb 2010 08:21:29 +0100 Subject: [Tutor] Input() is not working as expected in Python 3.1 In-Reply-To: <1266267750.27745.3.camel@dedal-laptop> References: <4B796302.3000101@gmail.com> <1266267750.27745.3.camel@dedal-laptop> Message-ID: Thanks for try but print without () does not work at all, at least in newer version of python (3.1) Anyway source of problem is now discovered: Komodo Edit tool, in Python shell (IDLE) everything works fine. Perhaps anyone has any ideas why? On Mon, Feb 15, 2010 at 10:02 PM, Grigor Kolev wrote: > ? 10:06 -0500 ?? 15.02.2010 (??), bob gailer ??????: > > Yaraslau Shanhin wrote: > > > > > Hello All, > > > > Hello. > > > > Suggestion for future questions - just include enough to identify the > > problem. We don't need to know that this is from a tutorial or what the > > exercise is. Also (at least I prefer) plain text without formatting or > > color. > > > > Sufficient therefore is: > > > > ------------------------------------------- > > using Python 3.1: > > text = str(input("Type in some text: ")) > > number = int(input("How many times should it be printed? ")) > > > > Traceback (most recent call last): > > File "test4.py", line 2, in > > number = int(input("How many times should it be printed? ")) > > ValueError: invalid literal for int() with base 10: > > ------------------------------------------- > > > > Now carefully read the message "invalid literal for int()". This tells > > you the argument to int is not a string representation of an integer. > > There is nothing wrong with input()! > > > > Since we don't know what you typed at the input() prompt we can't > > diagnose it further. One way to solve problems like these is to capture > > and print the output of input(): > > > > text = str(input("Type in some text: ")) > > snumber = input("How many times should it be printed?") > > print snumber > > > > A good robust alternative is to try int() and capture / report the > failure: > > > > text = str(input("Type in some text: ")) > > snumber = input("How many times should it be printed?") > > try: > > number = int(snumber) > > except ValueError: > > print(number, "is not an integer.") > > else: > > print (text * number) > > > Try this: > >>>text = str(input("Type in some text: ")) > Type in some text:"some text" > >>>snumber = int(input("How many times should it be printed?")) > How many times should it be printed?3 > >>>print text*snumber > -- > Grigor Kolev > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas at kostyrka.org Tue Feb 16 13:08:29 2010 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 16 Feb 2010 13:08:29 +0100 Subject: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ? In-Reply-To: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> References: <954757881002130756y77df8885o42d313f5a6477aaa@mail.gmail.com> Message-ID: <201002161308.30064.andreas@kostyrka.org> Am Samstag, 13. Februar 2010 16:56:08 schrieb patrice laporte: > Hi, > > Being in an exeption of my own, I want to print the name of the caller, and > I'm looking for a way to have it. > > I've found a lot of recipe all of them using what seems to be, according to > me, a not so good trick : all those recipe make use of > sys._getframe(1).f_code.co_name, such as in this exemple : > > import sys > > def whoami(): > print "Who call me ? : ", sys._getframe(1).f_code.co_name > print "Who am I ? : ", sys._getframe(0).f_code.co_name > > def print_caller_name(): > whoami() > > if __name__ == "__main__": > > print_caller_name() > > With the following result, as expected : > > Who call me ? : print_caller_name > Who am I ? : whoami > > A closer look at the documentation about sys._getframe at > http://docs.python.org/library/sys.html make me think it's not a good idea, > because of the note : > "*CPython implementation detail:* This function should be used for internal > and specialized purposes only. *It is not guaranteed to exist in all > implementations of Python*." > > So, this trick works today, but what about tomorow ? Well, the trick has worked for the better part of a decade. If you need it (but there are probably better suited more specialized modules like traceback available), and you can live with the limitation to CPython, then use it. Put differently, should the usage change, it will probably be for a very very good reason (and not before Python4, as Python3 does have a sys._getframe()). Generally speaking, while sys._getframe does have a bad smell, a number of use cases come to mind which will probably assure it's existence eternally. (e.g. accessing the class name space during definition of a class, which a ton of libraries, e.g. ORMs or probably zope.interface do use) > Is anybody have an idea how to get the the same result without _getframe ? Well, you've got basically the following options: 1.) sys._getframe 2.) sys._getframe hidden in a nicer API, e.g. traceback. 3.) manually (e.g. decorators, metaclasses, whatever) maintaining the "caller" site in your framework. 4.) use sys.settrace to maintain the caller site automatically (slow) 5.) use hotshot to log your execution to disc, and analyze that as needed. 6.) other obscure ideas that I forgot ;) All of these can have their good reason, depending upon your requirements, and all of these are ugly in some way (and some of these incur a significant performance drop), so you need to decide why you need that stuff. Another observation is that you'll probably want to isolate stuff like that in a small number of places, e.g. some top level loop that has to generally handle any exception (traceback would be your solution there, I guess), or some helper functions for some framework that do magic during class definition (getframe it is here I guess), or you need a general "sender" identity troughout your framework (then you'll go probably with some python constructs that maintain it manually/semi-automatically). And last but not least you might be debugging then settrace comes to mind. But whatever you do it will probably be isolated to a small part of your source code. Andreas From sierra_mtnview at sbcglobal.net Tue Feb 16 13:27:02 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 16 Feb 2010 04:27:02 -0800 Subject: [Tutor] A Stuborn Tab Problem in IDLE In-Reply-To: <4B78B8FF.4030005@ieee.org> References: <4B7876F7.10806@sbcglobal.net> <4B78AEFF.9090202@sbcglobal.net> <4B78B36F.1030004@sbcglobal.net> <4B78B8FF.4030005@ieee.org> Message-ID: <4B7A8F16.9050802@sbcglobal.net> On 2/14/2010 7:01 PM, Dave Angel wrote: > Wayne Watson wrote: >>
I got to >> the dos command line facility and got to the file. I executed the >> program, and it failed with a syntax error. I can't copy it out of >> the window to paste here, >>> > Once you've discovered the DOS box, you should also discover QuickEdit > mode. In the DOS box, right click on the title bar, and choose > "Properties". First tab is Options. Enable Quick-Edit mode, and > press OK. Now, you can drag a rectangle on the DOS box, and use right > click to paste it to the clipboard. Practice a bit and you'll find it > easy. An essential tool. > > DaveA I have QuickEdit on, but ... I was going to say I couldn't copy and paste. I just did it. However, I guess one can only select on a rectangle, and it has to sweep all the way from left to right. Time to use help, and print it out. -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From kent37 at tds.net Tue Feb 16 15:26:04 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Feb 2010 09:26:04 -0500 Subject: [Tutor] PyCon anyone? Message-ID: <1c2a2c591002160626k6953dfb8u22c63493bd08d4b@mail.gmail.com> Hi all, I'm going to PyCon this year for the first time (yeah!) and I would love to meet other regular contributors to the tutor list. Is anyone else going to be there? Any interest in a "Meet the tutors" Open Space or dinner? Kent From vceder at canterburyschool.org Tue Feb 16 16:09:17 2010 From: vceder at canterburyschool.org (Vern Ceder) Date: Tue, 16 Feb 2010 10:09:17 -0500 Subject: [Tutor] PyCon anyone? In-Reply-To: <1c2a2c591002160626k6953dfb8u22c63493bd08d4b@mail.gmail.com> References: <1c2a2c591002160626k6953dfb8u22c63493bd08d4b@mail.gmail.com> Message-ID: <4B7AB51D.6090204@canterburyschool.org> Kent Johnson wrote: > Hi all, > > I'm going to PyCon this year for the first time (yeah!) and I would > love to meet other regular contributors to the tutor list. Is anyone > else going to be there? Any interest in a "Meet the tutors" Open Space > or dinner? > > Kent Hi Kent, I'm not a very regular contributor here, but we'd love have you (and anyone else who's on the tutor list) join the edu-sig group for dinner and open space, if you're so inclined... Our open space page is at http://us.pycon.org/2010/openspace/edu-sig/ Cheers, Vern Ceder > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- 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 The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW From sierra_mtnview at sbcglobal.net Tue Feb 16 16:17:26 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 16 Feb 2010 07:17:26 -0800 Subject: [Tutor] PyCon anyone? In-Reply-To: <1c2a2c591002160626k6953dfb8u22c63493bd08d4b@mail.gmail.com> References: <1c2a2c591002160626k6953dfb8u22c63493bd08d4b@mail.gmail.com> Message-ID: <4B7AB706.3020908@sbcglobal.net> > > Hi all, > > I'm going to PyCon this year for the first time (yeah!) and I would > love to meet other regular contributors to the tutor list. Is anyone > else going to be there? Any interest in a "Meet the tutors" Open Space > or dinner? > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Where is it at? -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From kent37 at tds.net Tue Feb 16 16:40:56 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Feb 2010 10:40:56 -0500 Subject: [Tutor] PyCon anyone? In-Reply-To: <4B7AB51D.6090204@canterburyschool.org> References: <1c2a2c591002160626k6953dfb8u22c63493bd08d4b@mail.gmail.com> <4B7AB51D.6090204@canterburyschool.org> Message-ID: <1c2a2c591002160740o492602ey1cc82955aa4a8fe2@mail.gmail.com> On Tue, Feb 16, 2010 at 10:09 AM, Vern Ceder wrote: > Kent Johnson wrote: >> >> Hi all, >> >> I'm going to PyCon this year for the first time (yeah!) and I would >> love to meet other regular contributors to the tutor list. Is anyone >> else going to be there? Any interest in a "Meet the tutors" Open Space >> or dinner? >> >> Kent > > Hi Kent, > > I'm not a very regular contributor here, but we'd love have you (and anyone > else who's on the tutor list) join the edu-sig group for dinner and open > space, if you're so inclined... Our open space page is at > http://us.pycon.org/2010/openspace/edu-sig/ Thanks, that sounds good. I'll add myself to that page with a note. Any idea when the open space or dinner will be? Kent From kent37 at tds.net Tue Feb 16 16:42:40 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Feb 2010 10:42:40 -0500 Subject: [Tutor] PyCon anyone? In-Reply-To: <4B7AB706.3020908@sbcglobal.net> References: <1c2a2c591002160626k6953dfb8u22c63493bd08d4b@mail.gmail.com> <4B7AB706.3020908@sbcglobal.net> Message-ID: <1c2a2c591002160742m310860a7j253cf6bbbcffa1a8@mail.gmail.com> On Tue, Feb 16, 2010 at 10:17 AM, Wayne Watson wrote: >> >> Hi all, >> >> I'm going to PyCon this year for the first time (yeah!) and I would >> love to meet other regular contributors to the tutor list. Is anyone >> else going to be there? Any interest in a "Meet the tutors" Open Space >> or dinner? >> >> Kent > > Where is it at? Where is PyCon or where is the open space? PyCon is in Atlanta this weekend. http://us.pycon.org/2010/about/ Don't know about the open space. Kent From washakie at gmail.com Tue Feb 16 16:46:20 2010 From: washakie at gmail.com (John [H2O]) Date: Tue, 16 Feb 2010 07:46:20 -0800 (PST) Subject: [Tutor] ipython, PYTHONPATH, on a MAC Message-ID: <27610302.post@talk.nabble.com> Hello, I'm not a Mac user, but I'm a promoter of Python! I have a good friend using a Mac who's becoming sceptical of python due to frustrations with the PYTHONPATH. I'm trying to help... Everything is fine running vanilla python. Importing modules works fine. But in ipython, the module paths need to be appended individually. I can't even set a module directory into which ipython will look recursively for modules. There is nothing custom set in .ipython/ipythonrc or ipy_user_conf.py The PYTHONPATH variable doesn't need to be set using vanilla python. The path settings are set somehow, however (I can see this from import sys; sys.path). I'm not sure where this is all happening. Any ideas on the best way to set the PYTHONPATH for a mac? Thanks! -- View this message in context: http://old.nabble.com/ipython%2C-PYTHONPATH%2C-on-a-MAC-tp27610302p27610302.html Sent from the Python - tutor mailing list archive at Nabble.com. From vceder at canterburyschool.org Tue Feb 16 16:52:04 2010 From: vceder at canterburyschool.org (Vern Ceder) Date: Tue, 16 Feb 2010 10:52:04 -0500 Subject: [Tutor] PyCon anyone? In-Reply-To: <1c2a2c591002160740o492602ey1cc82955aa4a8fe2@mail.gmail.com> References: <1c2a2c591002160626k6953dfb8u22c63493bd08d4b@mail.gmail.com> <4B7AB51D.6090204@canterburyschool.org> <1c2a2c591002160740o492602ey1cc82955aa4a8fe2@mail.gmail.com> Message-ID: <4B7ABF24.9070202@canterburyschool.org> Kent Johnson wrote: > On Tue, Feb 16, 2010 at 10:09 AM, Vern Ceder >> >> I'm not a very regular contributor here, but we'd love have you (and anyone >> else who's on the tutor list) join the edu-sig group for dinner and open >> space, if you're so inclined... Our open space page is at >> http://us.pycon.org/2010/openspace/edu-sig/ > > Thanks, that sounds good. I'll add myself to that page with a note. > Any idea when the open space or dinner will be? > > Kent I believe we're aiming for Friday evening for dinner, but we're still working on where... The open space might be either after dinner on Friday or on Saturday evening... depending on interest. So go ahead and add your preferences. 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 The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW From Michael.Fourman at ed.ac.uk Tue Feb 16 17:03:30 2010 From: Michael.Fourman at ed.ac.uk (Michael Fourman) Date: Tue, 16 Feb 2010 16:03:30 +0000 Subject: [Tutor] ipython, PYTHONPATH, on a MAC In-Reply-To: <27610302.post@talk.nabble.com> References: <27610302.post@talk.nabble.com> Message-ID: If you start Python from command line you can just use usual bash methods put PYTHONPATH= xxx in ~/.profile or for use in a single shell export PYTHONPATH=xxx If you start Python from a dbl-clickable application you need to get the PYTHONPATH into the application's environment See http://mactip.blogspot.com/2004/04/setting-environment-variables.html Hope this helps, michael On 16 Feb 2010, at 15:46, John [H2O] wrote: > > Hello, > > I'm not a Mac user, but I'm a promoter of Python! I have a good friend using > a Mac who's becoming sceptical of python due to frustrations with the > PYTHONPATH. I'm trying to help... > > Everything is fine running vanilla python. Importing modules works fine. But > in ipython, the module paths need to be appended individually. I can't even > set a module directory into which ipython will look recursively for modules. > > There is nothing custom set in .ipython/ipythonrc or ipy_user_conf.py > > The PYTHONPATH variable doesn't need to be set using vanilla python. The > path settings are set somehow, however (I can see this from import sys; > sys.path). I'm not sure where this is all happening. > > Any ideas on the best way to set the PYTHONPATH for a mac? > > Thanks! > -- > View this message in context: http://old.nabble.com/ipython%2C-PYTHONPATH%2C-on-a-MAC-tp27610302p27610302.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Professor Michael Fourman FBCS CITP Director, iDEA lab Informatics Forum 10 Crichton Street Edinburgh EH8 9AB http://idea.ed.ac.uk/ twitter @iDEAatEd For diary appointments contact : mdunlop2(at)ed-dot-ac-dot-uk +44 131 650 2690 The University of Edinburgh is a charitable body, registered in Scotland, with registration number SC005336. From shurui91 at gmail.com Tue Feb 16 17:54:22 2010 From: shurui91 at gmail.com (Shurui Liu (Aaron Liu)) Date: Tue, 16 Feb 2010 11:54:22 -0500 Subject: [Tutor] count time limit Message-ID: <2b9003cf1002160854t4fcc8ffbm60bc4c7ed84ca61a@mail.gmail.com> Modify the guess_my_number.py program to limit the number of guesses to ten (10). Tell the user up front that they have ten guesses. After each guess, tell the user that they have ___ guesses remaining. Here are the requirement of my assignment. I want to ask the third one: what is the command for this mission? Cause I don't even know how to google it. Thank you! -- Shurui Liu (Aaron Liu) Computer Science & Engineering Technology University of Toledo -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Feb 16 18:41:22 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 16 Feb 2010 09:41:22 -0800 Subject: [Tutor] PyCon anyone? In-Reply-To: <1c2a2c591002160742m310860a7j253cf6bbbcffa1a8@mail.gmail.com> References: <1c2a2c591002160626k6953dfb8u22c63493bd08d4b@mail.gmail.com> <4B7AB706.3020908@sbcglobal.net> <1c2a2c591002160742m310860a7j253cf6bbbcffa1a8@mail.gmail.com> Message-ID: <4B7AD8C2.3080804@sbcglobal.net> On 2/16/2010 7:42 AM, Kent Johnson wrote: > On Tue, Feb 16, 2010 at 10:17 AM, Wayne Watson > wrote: > >>> Hi all, >>> >>> I'm going to PyCon this year for the first time (yeah!) and I would >>> love to meet other regular contributors to the tutor list. Is anyone >>> else going to be there? Any interest in a "Meet the tutors" Open Space >>> or dinner? >>> >>> Kent >>> >> Where is it at? >> > Where is PyCon or where is the open space? > > PyCon is in Atlanta this weekend. http://us.pycon.org/2010/about/ > > Don't know about the open space. > > Kent > > Unlikely I'll be in GA. Me neither. :-) -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From sierra_mtnview at sbcglobal.net Tue Feb 16 18:56:01 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 16 Feb 2010 09:56:01 -0800 Subject: [Tutor] Wrestingly with the Py2exe Install, Win7, Py2.5 Message-ID: <4B7ADC31.90401@sbcglobal.net> I've finally decided to see if I could make an executable out of a py file. Win7. Py2.5. I brought down the install file and proceeded with the install. I got two warning messages. Forgot the first. The second said,"Could not set the key value." I again used OK. I think that was the only choice. It then issued a message in a larger dialog. I've attached it here, but have had zero luck recently and in the past. It was about setting a key, and pointed me to a log. It mentions a Removepy2exe -u Although it finished, I have no idea where the program is. It does not show up on the Start menu All Programs List nore my desktop. What's up. I've had these messages (key) occur on other Python installs as I transition to Win7. So far no problem. -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From sierra_mtnview at sbcglobal.net Tue Feb 16 18:58:22 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 16 Feb 2010 09:58:22 -0800 Subject: [Tutor] "Sounding" Off, IDLE (Win7) Message-ID: <4B7ADCBE.2090601@sbcglobal.net> In Win7 IDLE, when I type in something with a syntax problem, a bell rings. How do I stop that? I've looked at Control Panel Sounds, but don't see anything of apparent use. -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW From kent37 at tds.net Tue Feb 16 19:42:17 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Feb 2010 13:42:17 -0500 Subject: [Tutor] ipython, PYTHONPATH, on a MAC In-Reply-To: <27610302.post@talk.nabble.com> References: <27610302.post@talk.nabble.com> Message-ID: <1c2a2c591002161042k6d087276s4c94bba234430985@mail.gmail.com> On Tue, Feb 16, 2010 at 10:46 AM, John [H2O] wrote: > > Hello, > > I'm not a Mac user, but I'm a promoter of Python! I have a good friend using > a Mac who's becoming sceptical of python due to frustrations with the > PYTHONPATH. I'm trying to help... > > Everything is fine running vanilla python. Importing modules works fine. But > in ipython, the module paths need to be appended individually. I can't even > set a module directory into which ipython will look recursively for modules. Python never searches recursively for modules, a module or package must me in a directory which is in sys.path. > There is nothing custom set in .ipython/ipythonrc or ipy_user_conf.py > > The PYTHONPATH variable doesn't need to be set using vanilla python. The > path settings are set somehow, however (I can see this from import sys; > sys.path). I'm not sure where this is all happening. So sys.path is different when running ipython? This is all very strange. I use Python on Mac OS X with ipython and I don't set PYTHONPATH at all. How do you start ipython? Kent > Any ideas on the best way to set the PYTHONPATH for a mac? > > Thanks! > -- > View this message in context: http://old.nabble.com/ipython%2C-PYTHONPATH%2C-on-a-MAC-tp27610302p27610302.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Feb 16 19:44:18 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 16 Feb 2010 13:44:18 -0500 Subject: [Tutor] count time limit In-Reply-To: <2b9003cf1002160854t4fcc8ffbm60bc4c7ed84ca61a@mail.gmail.com> References: <2b9003cf1002160854t4fcc8ffbm60bc4c7ed84ca61a@mail.gmail.com> Message-ID: <1c2a2c591002161044l4a19f074x3e04de65696d6ef@mail.gmail.com> On Tue, Feb 16, 2010 at 11:54 AM, Shurui Liu (Aaron Liu) wrote: > > ?Modify?the?guess_my_number.py?program?to?limit?the?number?of?guesses?to?ten?(10). > > ? ?Tell?the?user?up?front?that?they?have?ten?guesses. > > > After?each?guess,?tell?the?user?that?they?have?___?guesses?remaining. > > Here are the requirement of my assignment. I want to ask the third one: what > is the command for this mission? Cause I don't even know how to google it. Sigh. Still asking us to do your homework for you... What do you know about looping and conditionals and variables? Kent From Mike.Hansen at atmel.com Tue Feb 16 21:05:41 2010 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 16 Feb 2010 13:05:41 -0700 Subject: [Tutor] The Order of Imports and install order of modules andother matters (XP vs W7, ...) In-Reply-To: <1c2a2c591002130706i6aa1b99boc019f7f37d2c8804@mail.gmail.com> References: <4B7622BF.9000408@sbcglobal.net> <1c2a2c591002130706i6aa1b99boc019f7f37d2c8804@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D0ED7AA91@csomb01.corp.atmel.com> > -----Original Message----- > From: tutor-bounces+mike.hansen=atmel.com at python.org > [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On > Behalf Of Kent Johnson > Sent: Saturday, February 13, 2010 8:06 AM > To: Wayne Watson > Cc: Tutor Python > Subject: Re: [Tutor] The Order of Imports and install order > of modules andother matters (XP vs W7, ...) > > On Fri, Feb 12, 2010 at 10:55 PM, Wayne Watson > wrote: > > There seems to be something of a general consensus in > ordering import > > statements. Something like standard library imports first. > When using tools > > like matlablib or tkinter (maybe), must one keep an order > among the relevant > > imports? > > I don't know if there is a general consensus but what I like to do is > standard library imports > third-party library imports > application-specific imports > > Within each group I tend to group "import x" imports before "from x > import y" imports and alphabetize by module name. I'm not strict about > that though. > This make me wonder. Is there a document or web site that has Python Best Practices? Something along the lines of the Perl Best Practices book, but probably shorter. =) Mike From waynejwerner at gmail.com Tue Feb 16 21:07:01 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 16 Feb 2010 14:07:01 -0600 Subject: [Tutor] The Order of Imports and install order of modules andother matters (XP vs W7, ...) In-Reply-To: <7941B2693F32294AAF16C26B679A258D0ED7AA91@csomb01.corp.atmel.com> References: <4B7622BF.9000408@sbcglobal.net> <1c2a2c591002130706i6aa1b99boc019f7f37d2c8804@mail.gmail.com> <7941B2693F32294AAF16C26B679A258D0ED7AA91@csomb01.corp.atmel.com> Message-ID: <333efb451002161207w31a4f3f8l338661a6dd462c42@mail.gmail.com> http://www.python.org/dev/peps/pep-0008/ This make me wonder. Is there a document or web site that has Python Best > Practices? Something along the lines of the Perl Best Practices book, but > probably shorter. =) 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 mjollnir.xia at gmail.com Tue Feb 16 21:09:14 2010 From: mjollnir.xia at gmail.com (Mjollnir Xia) Date: Tue, 16 Feb 2010 12:09:14 -0800 Subject: [Tutor] Where to find the article for comparing different Python Development Environment Message-ID: <7f65ecb81002161209g4c4ba833w38827143d27c7e04@mail.gmail.com> Where to find the article for comparing different Python Development Environment -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Tue Feb 16 21:14:08 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 16 Feb 2010 15:14:08 -0500 Subject: [Tutor] Where to find the article for comparing different Python Development Environment In-Reply-To: <7f65ecb81002161209g4c4ba833w38827143d27c7e04@mail.gmail.com> References: <7f65ecb81002161209g4c4ba833w38827143d27c7e04@mail.gmail.com> Message-ID: > Where to find the article for comparing different Python Development > Environment > > The Python wiki is a good place to start: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mike.Hansen at atmel.com Tue Feb 16 21:18:44 2010 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 16 Feb 2010 13:18:44 -0700 Subject: [Tutor] The Order of Imports and install order of modules andother matters (XP vs W7, ...) In-Reply-To: <333efb451002161207w31a4f3f8l338661a6dd462c42@mail.gmail.com> References: <4B7622BF.9000408@sbcglobal.net> <1c2a2c591002130706i6aa1b99boc019f7f37d2c8804@mail.gmail.com> <7941B2693F32294AAF16C26B679A258D0ED7AA91@csomb01.corp.atmel.com> <333efb451002161207w31a4f3f8l338661a6dd462c42@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D0ED7AABA@csomb01.corp.atmel.com> ________________________________ From: srilyk at gmail.com [mailto:srilyk at gmail.com] On Behalf Of Wayne Werner Sent: Tuesday, February 16, 2010 1:07 PM To: Hansen, Mike Cc: Tutor Python Subject: Re: [Tutor] The Order of Imports and install order of modules andother matters (XP vs W7, ...) http://www.python.org/dev/peps/pep-0008/ This make me wonder. Is there a document or web site that has Python Best Practices? Something along the lines of the Perl Best Practices book, but probably shorter. =) HTH, Wayne ---------------- I'm aware of Pep8. It's a good starting point. Anything more in-depth than Pep8 and the Zen of Python? Mike From shurui91 at gmail.com Tue Feb 16 21:32:44 2010 From: shurui91 at gmail.com (Shurui Liu (Aaron Liu)) Date: Tue, 16 Feb 2010 15:32:44 -0500 Subject: [Tutor] command error Message-ID: <2b9003cf1002161232w488adf7agbc2aee84f88ffa3e@mail.gmail.com> Here is a program I wrote, I don't know why I cannot exit when I tried 10 times? Hope somebody can help me. Thank you! # Guess My Number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money import random print ("\tWelcome to 'Guess My Number'!") print ("\nI'm thinking of a number between 1 and 100.") print ("You have only 10 times to guess the number. Try to guess it in as few attempts as possible.\n") # set the initial values the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 9 # guessing loop while (guess != the_number): if (guess > the_number): print ("Lower...") print ("You were wrong, try again", tries, "times left.\n") else: print ("Higher...") print ("You were wrong, try again", tries, "times left.\n") guess = int(raw_input("Take a guess: ")) tries -= 1 print ("You guessed it! The number was"), the_number print ("And it only took you", "tries times", "tries !\n") if ("tries = 0"): print "You have tried 10 times, game over." raw_input("\n\nPress the enter key to exit.") raw_input("\n\nPress the enter key to exit.") -- Shurui Liu (Aaron Liu) Computer Science & Engineering Technology University of Toledo -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Tue Feb 16 21:55:47 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 16 Feb 2010 21:55:47 +0100 Subject: [Tutor] command error In-Reply-To: <2b9003cf1002161232w488adf7agbc2aee84f88ffa3e@mail.gmail.com> References: <2b9003cf1002161232w488adf7agbc2aee84f88ffa3e@mail.gmail.com> Message-ID: On 16 February 2010 21:32, Shurui Liu (Aaron Liu) wrote: > Here is a program I wrote, I don't know why I cannot exit when I tried 10 > times? Hope somebody can help me. Thank you! > > while (guess != the_number): > ??? if (guess > the_number): > ??????? print ("Lower...") > ??????? print ("You were wrong, try again", tries, "times left.\n") > ??? else: > ??????? print ("Higher...") > ??????? print ("You were wrong, try again", tries, "times left.\n") > > ??? guess = int(raw_input("Take a guess: ")) > ??? tries -= 1 This will loop untill guess == the_number with no other way out. Meaning unless the number is guessed it will end up in an infinite loop. You will have to figure out how to *break* out ot the while loop when tries == 0. Greets Sander From steve at pearwood.info Tue Feb 16 23:53:19 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 17 Feb 2010 09:53:19 +1100 Subject: [Tutor] command error In-Reply-To: <2b9003cf1002161232w488adf7agbc2aee84f88ffa3e@mail.gmail.com> References: <2b9003cf1002161232w488adf7agbc2aee84f88ffa3e@mail.gmail.com> Message-ID: <201002170953.19804.steve@pearwood.info> On Wed, 17 Feb 2010 07:32:44 am Shurui Liu (Aaron Liu) wrote: > Here is a program I wrote, I don't know why I cannot exit when I > tried 10 times? Hope somebody can help me. Thank you! Here is a program that loops ten times, then stops: for i in range(10): print "Loop number", i Here is another program that loops ten times counting down backwards: for i in range(10, 0, -1): # 10, 9, 8, ... , 1 print "Loop number", i Lastly, here is a program that loops ten times backwards, but exits early when a test becomes true. As a bonus, it prints a message if the test never becomes true: for i in range(10, 0, -1): # 10, 9, 8, ... , 1 if i <= 4: # the test print "we exit the loop early" break print "Loop number", i else: # for...else print "we didn't exit the loop early" -- Steven D'Aprano From piotr-kam at o2.pl Tue Feb 16 23:48:00 2010 From: piotr-kam at o2.pl (pk) Date: Tue, 16 Feb 2010 23:48:00 +0100 Subject: [Tutor] command error In-Reply-To: References: <2b9003cf1002161232w488adf7agbc2aee84f88ffa3e@mail.gmail.com> Message-ID: Dnia 16-02-2010 o 21:55:47 Sander Sweers napisa?(a): > On 16 February 2010 21:32, Shurui Liu (Aaron Liu) > wrote: >> Here is a program I wrote, I don't know why I cannot exit when I tried >> 10 >> times? Hope somebody can help me. Thank you! >> >> while (guess != the_number): >> if (guess > the_number): >> print ("Lower...") >> print ("You were wrong, try again", tries, "times left.\n") >> else: >> print ("Higher...") >> print ("You were wrong, try again", tries, "times left.\n") >> >> guess = int(raw_input("Take a guess: ")) >> tries -= 1 > > This will loop untill guess == the_number with no other way out. > Meaning unless the number is guessed it will end up in an infinite > loop. You will have to figure out how to *break* out ot the while loop > when tries == 0. Hello, Shurui Liu try adding, as Sander Sweers has written, the break keyword to your script. In the meantime I've written an alternative version of the program that does the same thing. I'm a complete beginner (Python is my first programming language) and a hobbyist so I thought I could take up the challenge and try to solve the problem in my spare time. The script seems to work, I've tested it. List members, if there are any mistakes or things that can be done better, please let me know. Here's the body of the script: #!/usr/bin/python # -*- coding: utf-16 -*- right_guess = 7 number_of_guesses = 10 print "Guess the number. You have ten guesses" for an_attempt in range(1, 11): answer = int(raw_input("Guess the number: ")) if answer == right_guess: print "That's the correct number! Congrats pal, I mean my dear teacher ;)" break else: number_of_guesses = number_of_guesses - 1 if number_of_guesses == 0: print "You have no more guesses.\n\t\tGAME OVER" break print "That's not the right number. Choose again, you have %i more guesses" % number_of_guesses Regards, Piotr -------------- next part -------------- A non-text attachment was scrubbed... Name: guess_my_number.py Type: application/octet-stream Size: 642 bytes Desc: not available URL: From alan.gauld at btinternet.com Wed Feb 17 01:57:40 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Feb 2010 00:57:40 -0000 Subject: [Tutor] The Order of Imports and install order of modulesandother matters (XP vs W7, ...) References: <4B7622BF.9000408@sbcglobal.net><1c2a2c591002130706i6aa1b99boc019f7f37d2c8804@mail.gmail.com><7941B2693F32294AAF16C26B679A258D0ED7AA91@csomb01.corp.atmel.com><333efb451002161207w31a4f3f8l338661a6dd462c42@mail.gmail.com> <7941B2693F32294AAF16C26B679A258D0ED7AABA@csomb01.corp.atmel.com> Message-ID: "Hansen, Mike" wrote > I'm aware of Pep8. It's a good starting point. Anything more in-depth > than Pep8 and the Zen of Python? There is the generic book "Code Complete" which is excellent, but definitely not short! And it's not Python specific - in fact doesn't even mention Python so far as I recall. But its advice is applicable to all languages. A bug fan, Alan g. From cubanylinks4eva at aol.com Wed Feb 17 04:32:42 2010 From: cubanylinks4eva at aol.com (cubanylinks4eva at aol.com) Date: Tue, 16 Feb 2010 22:32:42 -0500 Subject: [Tutor] DOWHILE counter Message-ID: <8CC7D98FF96648E-31D8-7019@webmail-m043.sysops.aol.com> Hi i am trying to write a pseudocode to read an input number and its 15% output value. The counter is supposed to process 4 input numbers. Help please!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From transmogribenno at gmail.com Wed Feb 17 05:01:27 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Wed, 17 Feb 2010 13:01:27 +0900 Subject: [Tutor] DOWHILE counter In-Reply-To: <8CC7D98FF96648E-31D8-7019@webmail-m043.sysops.aol.com> References: <8CC7D98FF96648E-31D8-7019@webmail-m043.sysops.aol.com> Message-ID: <9b00d1a91002162001xd40859br1ed85f73815c909b@mail.gmail.com> On 17 February 2010 12:32, wrote: > > Hi i am trying to write a pseudocode to read an input number and its 15% > output value. The counter is supposed to process 4 input numbers. Help > please!! If it's pseudocode, then you can write a loop however you like. If you have a Python-related question, please ask it clearly, and be sure to show what you've done so far. You should at least read the Python tutorial first, especially the following: http://docs.python.org/tutorial/introduction.html http://docs.python.org/tutorial/controlflow.html HTH, benno From alan.gauld at btinternet.com Wed Feb 17 09:54:01 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Feb 2010 08:54:01 -0000 Subject: [Tutor] DOWHILE counter References: <8CC7D98FF96648E-31D8-7019@webmail-m043.sysops.aol.com> Message-ID: wrote > Hi i am trying to write a pseudocode to read an input number and its 15% > output value. > The counter is supposed to process 4 input numbers. Help please!! Can you articulate what the program is supposed to do in more detail? Your description is very confusing to me. What is the program reading - one number or two? And what does it do with these to "process them"? Is there any output? Can you write down what a typical execution of this program will look like to the user? Maybe doing that will clarify in your mind what it is you must do. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From michael at shamirlens.co.uk Wed Feb 17 11:48:26 2010 From: michael at shamirlens.co.uk (Michael M Mason) Date: Wed, 17 Feb 2010 10:48:26 -0000 Subject: [Tutor] "Sounding" Off, IDLE (Win7) In-Reply-To: <4B7ADCBE.2090601@sbcglobal.net> References: <4B7ADCBE.2090601@sbcglobal.net> Message-ID: <2B7AA81C577B0942A14C2B388867E2C70E054A@harry.shamirlens.co.uk> Wayne Watson wrote on 16 February 2010 at 17:58:- > In Win7 IDLE, when I type in something with a syntax > problem, a bell rings. How do I stop that? I've looked > at Control Panel Sounds, but don't see anything of > apparent use. I don't get this on my Win7 machine. But anyway, the sound is probably the same sound you get if you type CTRL-G at a command prompt in a DOS box, in which case it isn't one of the sounds you set in Control Panel. You can disable it using Device Manager. It's called 'System Speaker' and it's under 'System devices'. Right-click and choose 'Disable'. -- Michael From sierra_mtnview at sbcglobal.net Wed Feb 17 16:48:16 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 17 Feb 2010 07:48:16 -0800 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 Message-ID: <4B7C0FC0.9080209@sbcglobal.net> (This is the same msg as above, but I meant XP. I'm transitioning from XP to Win7, and am operating with two monitors and keyboards side by side. I thought I had used W7, but nope. Corrected wrestling it Subject.) I've finally decided to see if I could make an executable out of a py file. XP. Py2.5. I brought down the install file and proceeded with the install. I got two warning messages. Forgot the first. The second said,"Could not set the key value." I again used OK. I think that was the only choice. It then issued a message in a larger dialog. I've attached it here, but have had zero luck recently and in the past. It was about setting a key, and pointed me to a log. It mentions a Removepy2exe -u Although it finished, I have no idea where the program is. It does not show up on the Start menu All Programs List nor my desktop. What's up. I've had these messages (key) occur on other Python installs as I transition to Win7. So far no problem. -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From karper12345 at yahoo.com Wed Feb 17 17:31:42 2010 From: karper12345 at yahoo.com (Karjer Jdfjdf) Date: Wed, 17 Feb 2010 08:31:42 -0800 (PST) Subject: [Tutor] Find duplicates (using dictionaries) Message-ID: <886093.9811.qm@web44709.mail.sp1.yahoo.com> I'm relatively new at Python and I'm trying to write a function that fills a dictionary acording the following rules and (example) data: Rules: * No duplicate values in field1 * No duplicates values in field2 and field3 simultaneous (highest value in field4 has to be preserved) Rec.no field1, field2, field3, field4 1. abc, def123, ghi123, 120 <-- new, insert in dictionary 2. abc, def123, ghi123, 120 <-- duplicate with 1. field4 same value. Do not insert in dictionary 3. bcd, def123, jkl125, 154 <-- new, insert in dictionary 4. efg, def123, jkl125, 175 <-- duplicate with 3 in field 2 and 3, but higher value in field4. Remove 3. from dict and replace with 4. 5. hij, ghi345, jkl125, 175 <-- duplicate field3, but not in field4. New, insert in dict. The resulting dictionary should be: hij ?? ?{'F2': ' ghi345', 'F3': ' jkl125', 'F4': 175} abc ?? ?{'F2': ' def123', 'F3': ' ghi123', 'F4': 120} efg ?? ?{'F2': ' def123', 'F3': ' jkl125', 'F4': 175} This is wat I came up with up to now, but there is something wrong with it. The 'bcd' should have been removed. When I run it it says: bcd ?? ?{'F2': ' def123', 'F3': ' jkl125', 'F4': 154} hij ?? ?{'F2': ' ghi345', 'F3': ' jkl125', 'F4': 175} abc ?? ?{'F2': ' def123', 'F3': ' ghi123', 'F4': 120} efg ?? ?{'F2': ' def123', 'F3': ' jkl125', 'F4': 175} Below is wat I brew (simplified). It took me some time to figure out that I was looking at the wrong values the wrong dictionary. I started again, but am ending up with a lot of dictionaries and for x in y-loops. I think there is a simpler way to do this. Can somebody point me in the right direction and explain to me how to do this? (and maybe have an alternative for the nesting. Because I may need to compare more fields. This is only a simplified dataset). ######### not working def createResults(field1, field2, field3, field4): ??????? #check if field1 exists. ??????????????? if not results.has_key(field1): ?????????????????????? ? ??????????????????????? if results.has_key(field2): ??????????????????????????????? #check if field2 already exists ?????????????????????????? ? ??????????????????????????????? if results.has_key(field3): ??????????????????????????????????? #check if field3 already exists ??????????????????????????????????? #retrieve value field4 ??????????????????????????????????? existing_field4 = results[field2][F4] ??????????????????????????????????? #retrieve value existing field1 in dict ??????????????????????????????????? existing_field1 = results[field1] ?????????????????????????????????? ? ??????????????????????????????????? #perform highest value check ??????????????????????????????????? if int(existing_field4) < int(field4): ??????????????????????????????????????? #remove existing record from dict. ??????????????????????????????????????? del results[existing_field1] ??????????????????????????????????????? values = {} ??????????????????????????????????????? values['F2'] = field2 ??????????????????????????????????????? values['F3'] = field3 ??????????????????????????????????????? values['F4'] = field4 ??????????????????????????????????????? results[field1] = values ??????????????????????????????????? else: ??????????????????????????????????????? pass ??????????????????????????????? else: ??????????????????????????????????? pass ??????????????????????? else: ??????????????????????????? values = {} ??????????????????????????? values['F2'] = field2 ??????????????????????????? values['F3'] = field3 ??????????????????????????? values['F4'] = field4 ??????????????????????????? results[field1] = values ??????????????? else: ??????????????????? pass ?????????????? ? ?? ? ??????????????????????? ? for line in open("file.csv"): ??????? field1, field2, field3, field4 = line.split(',') ??????? createResults(field1, field2, field3, int(field4)) ?? ?#because this is quick and dirty I had to get rid of the \n in the csv for i in results.keys(): ??????? print i, '\t', results[i] ################ contents file.csv abc, def123, ghi123, 120 abc, def123, ghi123, 120 bcd, def123, jkl125, 154 efg, def123, jkl125, 175 hij, ghi345, jkl125, 175 -------------- next part -------------- An HTML attachment was scrubbed... URL: From Mike.Hansen at atmel.com Wed Feb 17 18:14:32 2010 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Wed, 17 Feb 2010 10:14:32 -0700 Subject: [Tutor] The Order of Imports and install order ofmodulesandother matters (XP vs W7, ...) In-Reply-To: References: <4B7622BF.9000408@sbcglobal.net><1c2a2c591002130706i6aa1b99boc019f7f37d2c8804@mail.gmail.com><7941B2693F32294AAF16C26B679A258D0ED7AA91@csomb01.corp.atmel.com><333efb451002161207w31a4f3f8l338661a6dd462c42@mail.gmail.com><7941B2693F32294AAF16C26B679A258D0ED7AABA@csomb01.corp.atmel.com> Message-ID: <7941B2693F32294AAF16C26B679A258D0ED7B1A2@csomb01.corp.atmel.com> > -----Original Message----- > [mailto:tutor-bounces+mike.hansen=atmel.com at python.org] On > Behalf Of Alan Gauld > Sent: Tuesday, February 16, 2010 5:58 PM > > "Hansen, Mike" wrote > > > I'm aware of Pep8. It's a good starting point. Anything > more in-depth > > than Pep8 and the Zen of Python? > > There is the generic book "Code Complete" which is excellent, but > definitely not short! > And it's not Python specific - in fact doesn't even mention > Python so far > as I recall. > But its advice is applicable to all languages. > > A bug fan, > > Alan g. Are you a bug fan of Code Complete? =) I need to revisit Code Complete. I read a huge amount of the first edition and about a 1/3 of the second edition. Although you can gather best practices from Pep8, the Zen of Python, The Python Cookbook, and other sources, it appears that a central resource for Python best practices doesn't exist. Mike From roadierich at googlemail.com Wed Feb 17 19:08:34 2010 From: roadierich at googlemail.com (Rich Lovely) Date: Wed, 17 Feb 2010 18:08:34 +0000 Subject: [Tutor] Find duplicates (using dictionaries) In-Reply-To: <886093.9811.qm@web44709.mail.sp1.yahoo.com> References: <886093.9811.qm@web44709.mail.sp1.yahoo.com> Message-ID: On 17 February 2010 16:31, Karjer Jdfjdf wrote: > I'm relatively new at Python and I'm trying to write a function that fills > a dictionary acording the following rules and (example) data: > > Rules: > * No duplicate values in field1 > * No duplicates values in field2 and field3 simultaneous (highest value in > field4 has to be preserved) > > > Rec.no field1, field2, field3, field4 > 1. abc, def123, ghi123, 120 <-- new, insert in dictionary > 2. abc, def123, ghi123, 120 <-- duplicate with 1. field4 same value. Do not > insert in dictionary > 3. bcd, def123, jkl125, 154 <-- new, insert in dictionary > 4. efg, def123, jkl125, 175 <-- duplicate with 3 in field 2 and 3, but > higher value in field4. Remove 3. from dict and replace with 4. > 5. hij, ghi345, jkl125, 175 <-- duplicate field3, but not in field4. New, > insert in dict. > > > The resulting dictionary should be: > > hij {'F2': ' ghi345', 'F3': ' jkl125', 'F4': 175} > abc {'F2': ' def123', 'F3': ' ghi123', 'F4': 120} > efg {'F2': ' def123', 'F3': ' jkl125', 'F4': 175} > > This is wat I came up with up to now, but there is something wrong with it. > The 'bcd' should have been removed. When I run it it says: > > bcd {'F2': ' def123', 'F3': ' jkl125', 'F4': 154} > hij {'F2': ' ghi345', 'F3': ' jkl125', 'F4': 175} > abc {'F2': ' def123', 'F3': ' ghi123', 'F4': 120} > efg {'F2': ' def123', 'F3': ' jkl125', 'F4': 175} > > Below is wat I brew (simplified). It took me some time to figure out that I > was looking at the wrong values the wrong dictionary. I started again, but > am ending up with a lot of dictionaries and for x in y-loops. I think there > is a simpler way to do this. > > Can somebody point me in the right direction and explain to me how to do > this? (and maybe have an alternative for the nesting. Because I may need to > compare more fields. This is only a simplified dataset). > > > ######### not working > def createResults(field1, field2, field3, field4): > #check if field1 exists. > if not results.has_key(field1): > > if results.has_key(field2): > #check if field2 already exists > > if results.has_key(field3): > #check if field3 already exists > #retrieve value field4 > existing_field4 = results[field2][F4] > #retrieve value existing field1 in dict > existing_field1 = results[field1] > > #perform highest value check > if int(existing_field4) < int(field4): > #remove existing record from dict. > del results[existing_field1] > values = {} > values['F2'] = field2 > values['F3'] = field3 > values['F4'] = field4 > results[field1] = values > else: > pass > else: > pass > else: > values = {} > values['F2'] = field2 > values['F3'] = field3 > values['F4'] = field4 > results[field1] = values > else: > pass > > > > > > for line in open("file.csv"): > field1, field2, field3, field4 = line.split(',') > createResults(field1, field2, field3, int(field4)) > #because this is quick and dirty I had to get rid of the \n in the csv > > for i in results.keys(): > print i, '\t', results[i] > ################ > > contents file.csv > > abc, def123, ghi123, 120 > abc, def123, ghi123, 120 > bcd, def123, jkl125, 154 > efg, def123, jkl125, 175 > hij, ghi345, jkl125, 175 > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > First observation: This strikes me as a poor use for dictionaries. You might be better using a list of tuples. If you will always have four fields in each line of data, then there is no need to check for the existence of the other elements, so you can cut out a lot of the checks. Whilst your requirements are not exactly clear to me, here is how I would do what it sounds like you need (using the same dict layout as you used previously): def add_record(field1, field2, field3, field4): if field1 in results: #duplicate in field1, do nothing return for key, item in results.iteritems(): if field2 == item['F2'] and field3 == item['F3'] #duplicate in both field2 and field3 if field4 > item['F4']: #new F4 is higher, remove old del results[key] break else: #old version of F4 is higher, do nothing return #if we get here, there are no important duplicates results[field1] = {'F2': field2, 'F3': field3, 'F4': field4} I think this might not be exactly what you want, but hopefully it will point you towards the solution. -- Rich "Roadie Rich" Lovely Just because you CAN do something, doesn't necessarily mean you SHOULD. In fact, more often than not, you probably SHOULDN'T. Especially if I suggested it. 10 re-discover BASIC 20 ??? 30 PRINT "Profit" 40 GOTO 10 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Wed Feb 17 19:26:45 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 17 Feb 2010 13:26:45 -0500 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 In-Reply-To: <4B7C0FC0.9080209@sbcglobal.net> References: <4B7C0FC0.9080209@sbcglobal.net> Message-ID: <004d01caaffe$c2b869a0$48293ce0$@rr.com> > -----Original Message----- > From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- > bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Wayne Watson > Sent: Wednesday, February 17, 2010 10:48 AM > To: *tutor python > Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 > > (This is the same msg as above, but I meant XP. I'm transitioning > from > XP to Win7, and am operating with two monitors and keyboards side by > side. I thought I had used W7, but nope. Corrected wrestling it > Subject.) > > I've finally decided to see if I could make an executable out of a > py > file. XP. Py2.5. I brought down the install file and proceeded with > the > install. I got two warning messages. Forgot the first. The second > said,"Could not set the key value." I again used OK. I think that > was > the only choice. It then issued a message in a larger dialog. I've > attached it here, but have had zero luck recently and in the past. > It > was about setting a key, and pointed me to a log. It mentions a > Removepy2exe -u > > Although it finished, I have no idea where the program is. It does > not > show up on the Start menu All Programs List nor my desktop. What's > up. > > I've had these messages (key) occur on other Python installs as I > transition to Win7. So far no problem. > > Hi Wayne, A few observations as I do this on Win 7 and it does work. The first thing you need to do is follow the tutorial that you should get at the web page found in the README file. If not, here it is: http://www.py2exe.org/index.cgi/Tutorial That will get you started. Now, if everything went reasonably well, you will find two folders in the folder where you ran py2exe called build and dist. Ignore build. In dist you will find the exe file and all the files necessary to run your program.....gasp.....sort of. There is a caveat. Sometimes you don't get all the necessary DLL's. If you are in that situation py2exe should have printed the files you still need to track down and include with your install. Now, I gave you all this information as background because we all know that really good programmers like mental and emotional pain. Well, perhaps some do. I like the easy but good way when available. Let me tell you what I use because it takes a lot of the drudgery out of the process. Go to http://code.google.com/p/gui2exe/ and download gui2exe. It will automate much of the process and it seems to do a great job of finding all the necessary files including the DLL's hidden from py2exe. I hope this helps. It is a good concept and good software. Robert Berman From dperlman at wisc.edu Wed Feb 17 19:44:02 2010 From: dperlman at wisc.edu (David Perlman) Date: Wed, 17 Feb 2010 12:44:02 -0600 Subject: [Tutor] datetime, time zones, and ISO time Message-ID: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> I have been really scratching my head over this, it seems like there *should* be a nice easy way to do what I want but I can't find it for the life of me. What I would like to do would be something like this: >>> datetime.datetime.now().isoformat() '2010-02-17T12:13:17.913260-06:00' But what actually happens is this: '2010-02-17T12:13:17.913260' I need to keep track of the time zone because I'm working with Google Calendar's query APIs, and it interprets all times as GMT unless you specify the time zone, which means my search results are wrong. Anyway, I was thinking I could get around it with something like: now=datetime.datetime.now() offset=datetime.datetime.utcoffset() [somehow add the offset info into the "now" datetime object] now.isoformat() But a) I don't know how to stick the offset info into a datetime object, and the documentation doesn't seem to say anything about this; and b) the offset line doesn't work anyway: >>> datetime.datetime.utcoffset() Traceback (most recent call last): File "", line 1, in TypeError: descriptor 'utcoffset' of 'datetime.datetime' object needs an argument I think there's a combination of problems here, involving me not understanding something fundamental about datetime objects, and also involving problems with the documentation (there are a whole lot of places where the optional arguments to the methods are left off of the syntax, for example.) Can anyone help sort me out here? In particular, is there a really straightforward way to do what I'm looking for? One more general kind of confusion that this has raised for me is that it seems that in the datetime documentation (and possibly other places as well) there is an unexplained distinction between methods which can be used to give you new information, and methods which only can tell you something about the instance they are invoked on. For example, this works the way I feel like it ought to: >>> datetime.datetime.now() datetime.datetime(2010, 2, 17, 12, 42, 30, 520792) But this doesn't work at all: >>> datetime.datetime.utcoffset() Traceback (most recent call last): File "", line 1, in TypeError: descriptor 'utcoffset' of 'datetime.datetime' object needs an argument And I haven't been able to find another method instead of utcoffset() that will give me what I want. Thanks very much to anyone who can illuminate my darkness on this matter. :) -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From kent37 at tds.net Wed Feb 17 19:54:41 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Feb 2010 13:54:41 -0500 Subject: [Tutor] Find duplicates (using dictionaries) In-Reply-To: <886093.9811.qm@web44709.mail.sp1.yahoo.com> References: <886093.9811.qm@web44709.mail.sp1.yahoo.com> Message-ID: <1c2a2c591002171054u19aa6a32g31345be2e412a1fa@mail.gmail.com> On Wed, Feb 17, 2010 at 11:31 AM, Karjer Jdfjdf wrote: > I'm relatively new at Python and I'm trying to write a function that fills > a dictionary acording the following rules and (example) data: > > Rules: > * No duplicate values in field1 > * No duplicates values in field2 and field3 simultaneous (highest value in > field4 has to be preserved) > > > Rec.no field1, field2, field3, field4 > 1. abc, def123, ghi123, 120 <-- new, insert in dictionary > 2. abc, def123, ghi123, 120 <-- duplicate with 1. field4 same value. Do not > insert in dictionary > 3. bcd, def123, jkl125, 154 <-- new, insert in dictionary > 4. efg, def123, jkl125, 175 <-- duplicate with 3 in field 2 and 3, but > higher value in field4. Remove 3. from dict and replace with 4. > 5. hij, ghi345, jkl125, 175 <-- duplicate field3, but not in field4. New, > insert in dict. > > > The resulting dictionary should be: > > hij {'F2': ' ghi345', 'F3': ' jkl125', 'F4': 175} > abc {'F2': ' def123', 'F3': ' ghi123', 'F4': 120} > efg {'F2': ' def123', 'F3': ' jkl125', 'F4': 175} I'm not sure I understand the rules. Something like if (f2, f3) in list: if associated f4 < new f4: delete old (f2, f3) entry add new entry (f1, f2, f3, f4) else if f1 not in list: add new entry (f1, f2, f3, f4) Is that right? If so, ISTM you need a table with two indexes, one by f1 and one by (f2, f3). This might be a good application for an in-memory sqlite database, which can maintain indexes for you. If the number of items is not too large, you could just implement this as a list of (f1, f2, f3, f4) tuples and repeated searches through the list, but that will get slow quickly as the number of items being added grows. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From yam at nerd.cx Wed Feb 17 20:42:29 2010 From: yam at nerd.cx (William Witteman) Date: Wed, 17 Feb 2010 14:42:29 -0500 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> Message-ID: <20100217194229.GA24329@yam.witteman.ca> On Wed, Feb 17, 2010 at 12:44:02PM -0600, David Perlman wrote: >I have been really scratching my head over this, it seems like there >*should* be a nice easy way to do what I want but I can't find it for >the life of me. ... >But a) I don't know how to stick the offset info into a datetime >object, and the documentation doesn't seem to say anything about >this; and b) the offset line doesn't work anyway: I think that you need to push in a tzinfo object, rather than a value: http://docs.python.org/library/datetime.html#datetime.tzinfo I get that from here: For applications requiring more, datetime and time objects have an optional time zone information member, tzinfo, that can contain an instance of a subclass of the abstract tzinfo class. These tzinfo objects capture information about the offset from UTC time, the time zone name, and whether Daylight Saving Time is in effect. Note that no concrete tzinfo classes are supplied by the datetime module. Supporting timezones at whatever level of detail is required is up to the application. The rules for time adjustment across the world are more political than rational, and there is no standard suitable for every application.[1] I suspect that it'll take some fooling around to see how it works though - use the interpreter or ipython to test things out. [1] http://docs.python.org/library/datetime.html -- yours, William From piotr-kam at o2.pl Wed Feb 17 20:57:44 2010 From: piotr-kam at o2.pl (pk) Date: Wed, 17 Feb 2010 20:57:44 +0100 Subject: [Tutor] command error In-Reply-To: <2b9003cf1002161541p4f89f055i54d7d9353ceaae70@mail.gmail.com> References: <2b9003cf1002161232w488adf7agbc2aee84f88ffa3e@mail.gmail.com> <2b9003cf1002161457p24e5f8fcp315f038e0ad60b54@mail.gmail.com> <2b9003cf1002161541p4f89f055i54d7d9353ceaae70@mail.gmail.com> Message-ID: Dnia 17-02-2010 o 00:41:21 Shurui Liu (Aaron Liu) napisa?(a): > But I have tried, it doesn't work on my workstation, i don't know why. I > run > it on my python software, python 3.0. The script is written in Python 2. Try rewriting it, mostly by changing the number formatting, function syntax and function names. Or simply install a Python 2.x interpreter. From dperlman at wisc.edu Wed Feb 17 21:12:42 2010 From: dperlman at wisc.edu (David Perlman) Date: Wed, 17 Feb 2010 14:12:42 -0600 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: <20100217194229.GA24329@yam.witteman.ca> References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> Message-ID: Yeah, I got this part. The thing that's hanging me up is that there doesn't seem to be any way to get a tzinfo instance that contains the current local time zone information. You can do time.timezone to get the seconds from UTC, but there doesn't seem to be any way to convert that into a tzinfo! I would be perfectly satisfied with this: tz=offset_to_tzinfo(time.timezone) # or whatever aware_now=datetime.datetime.now(tz) print aware_now.isoformat() I'm pretty sure that would give me what I want, but there doesn't seem to be any way to do step one without subclassing tzinfo. This makes me feel like I MUST be missing something obvious, because it shouldn't require so much coding just to find out what the current local time and timezone is! On Feb 17, 2010, at 1:42 PM, William Witteman wrote: > On Wed, Feb 17, 2010 at 12:44:02PM -0600, David Perlman wrote: >> I have been really scratching my head over this, it seems like there >> *should* be a nice easy way to do what I want but I can't find it for >> the life of me. > ... >> But a) I don't know how to stick the offset info into a datetime >> object, and the documentation doesn't seem to say anything about >> this; and b) the offset line doesn't work anyway: > > I think that you need to push in a tzinfo object, rather than a value: > > http://docs.python.org/library/datetime.html#datetime.tzinfo > > I get that from here: > > For applications requiring more, datetime and time objects have an > optional time zone information member, tzinfo, that can contain an > instance of a subclass of the abstract tzinfo class. These tzinfo > objects capture information about the offset from UTC time, the time > zone name, and whether Daylight Saving Time is in effect. Note that no > concrete tzinfo classes are supplied by the datetime module. > Supporting > timezones at whatever level of detail is required is up to the > application. The rules for time adjustment across the world are more > political than rational, and there is no standard suitable for every > application.[1] > > I suspect that it'll take some fooling around to see how it works > though > - use the interpreter or ipython to test things out. > > [1] http://docs.python.org/library/datetime.html > -- > > yours, > > William > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From kent37 at tds.net Wed Feb 17 21:26:03 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Feb 2010 15:26:03 -0500 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> Message-ID: <1c2a2c591002171226r736257bcs761046770d2d98e1@mail.gmail.com> On Wed, Feb 17, 2010 at 3:12 PM, David Perlman wrote: > Yeah, I got this part. ?The thing that's hanging me up is that there doesn't > seem to be any way to get a tzinfo instance that contains the current local > time zone information. ?You can do time.timezone to get the seconds from > UTC, but there doesn't seem to be any way to convert that into a tzinfo! ?I > would be perfectly satisfied with this: > > tz=offset_to_tzinfo(time.timezone) # or whatever > aware_now=datetime.datetime.now(tz) > print aware_now.isoformat() > > I'm pretty sure that would give me what I want, but there doesn't seem to be > any way to do step one without subclassing tzinfo. ?This makes me feel like > I MUST be missing something obvious, because it shouldn't require so much > coding just to find out what the current local time and timezone is! The docs make it clear that you do have to subclass tzinfo, that no implementations are provided. It sounds like you want the LocalTimezone class in the examples at the bottom of this section - "A class capturing the platform's idea of local time": http://docs.python.org/library/datetime.html#tzinfo-objects Kent From kent37 at tds.net Wed Feb 17 22:12:01 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Feb 2010 16:12:01 -0500 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: <4E5DE93E-B945-4A2B-8B64-47385D7128C4@wisc.edu> References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> <1c2a2c591002171226r736257bcs761046770d2d98e1@mail.gmail.com> <4E5DE93E-B945-4A2B-8B64-47385D7128C4@wisc.edu> Message-ID: <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> On Wed, Feb 17, 2010 at 3:48 PM, David Perlman wrote: > Surely there is a way to simply print out the local time, date and time zone > without needing to write your own class... ?I can't believe this is the only > way... > > Here's why I don't believe it. ?Both the datetime and time modules provide > both functions for returning the current local time, and the current utc > time. ?So, assuming that those functions are trustworthy, it *must* be true > that the OS always knows the current offset from utc time. ?So why is there > no straightforward way to get that offset in python? ?I mean, I can do this: time.timezone gives the offset for standard time. Kent > >>>> datetime.datetime.now()-datetime.datetime.utcnow() > datetime.timedelta(-1, 64799, 999987) > > But then, of course, it's off by a few fractions of a microsecond. ?This > works: > >>>> time.localtime()[3]-time.gmtime()[3] > -6 > > But doesn't that seem like a ridiculous hack, well outside of the spirit of > the zen of python? ?Shouldn't there be one obvious right way to do this? > > Yes, I know that as William sent, the documentation points out that the > rules the world over are complicated and irrational. ?Nonetheless, it is > implicit in the existing definitions that the system *knows* the current > offset, even if it doesn't know the whole set of rules... > > > On Feb 17, 2010, at 2:26 PM, Kent Johnson wrote: > >> On Wed, Feb 17, 2010 at 3:12 PM, David Perlman wrote: >>> >>> Yeah, I got this part. ?The thing that's hanging me up is that there >>> doesn't >>> seem to be any way to get a tzinfo instance that contains the current >>> local >>> time zone information. ?You can do time.timezone to get the seconds from >>> UTC, but there doesn't seem to be any way to convert that into a tzinfo! >>> ?I >>> would be perfectly satisfied with this: >>> >>> tz=offset_to_tzinfo(time.timezone) # or whatever >>> aware_now=datetime.datetime.now(tz) >>> print aware_now.isoformat() >>> >>> I'm pretty sure that would give me what I want, but there doesn't seem to >>> be >>> any way to do step one without subclassing tzinfo. ?This makes me feel >>> like >>> I MUST be missing something obvious, because it shouldn't require so much >>> coding just to find out what the current local time and timezone is! >> >> The docs make it clear that you do have to subclass tzinfo, that no >> implementations are provided. >> It sounds like you want the LocalTimezone class in the examples at the >> bottom of this section - "A class capturing the platform's idea of >> local time": >> http://docs.python.org/library/datetime.html#tzinfo-objects >> >> Kent > > -- > -dave---------------------------------------------------------------- > "Pseudo-colored pictures of a person's brain lighting up are > undoubtedly more persuasive than a pattern of squiggles produced by a > polygraph. ?That could be a big problem if the goal is to get to the > truth." ?-Dr. Steven Hyman, Harvard > > > > From dperlman at wisc.edu Wed Feb 17 22:24:26 2010 From: dperlman at wisc.edu (David Perlman) Date: Wed, 17 Feb 2010 15:24:26 -0600 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> <1c2a2c591002171226r736257bcs761046770d2d98e1@mail.gmail.com> <4E5DE93E-B945-4A2B-8B64-47385D7128C4@wisc.edu> <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> Message-ID: But this doesn't help, because then you still don't know whether it's dst or not. You then would have to jump through whatever convolutions to do that calculation. All I want to know is the *current* offset between local time and utc. I know the system has this information already; it doesn't require any kind of fancy calculations about global politics or anything. On Feb 17, 2010, at 3:12 PM, Kent Johnson wrote: > On Wed, Feb 17, 2010 at 3:48 PM, David Perlman > wrote: >> Surely there is a way to simply print out the local time, date and >> time zone >> without needing to write your own class... I can't believe this is >> the only >> way... >> >> Here's why I don't believe it. Both the datetime and time modules >> provide >> both functions for returning the current local time, and the >> current utc >> time. So, assuming that those functions are trustworthy, it *must* >> be true >> that the OS always knows the current offset from utc time. So why >> is there >> no straightforward way to get that offset in python? I mean, I can >> do this: > > time.timezone gives the offset for standard time. -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From dperlman at wisc.edu Wed Feb 17 22:37:56 2010 From: dperlman at wisc.edu (David Perlman) Date: Wed, 17 Feb 2010 15:37:56 -0600 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> <1c2a2c591002171226r736257bcs761046770d2d98e1@mail.gmail.com> <4E5DE93E-B945-4A2B-8B64-47385D7128C4@wisc.edu> <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> Message-ID: <4D27BAA2-C9AB-4599-8BA3-B02C1CD3B6F5@wisc.edu> OK, here's a function that does precisely what I want: def tzDelta(): """by whatever means necessary, return the current offset of the local time from utc.""" s=time.time() t,u=time.localtime(s),time.gmtime(s) osec=3600*(t[3]-u[3]) + 60*(t[4]-u[4]) + (t[5]-u[5]) return datetime.timedelta(seconds=osec) As far as I can tell, this should always work. So wouldn't it be nice if there were a less convoluted way to get this?? On Feb 17, 2010, at 3:12 PM, Kent Johnson wrote: > On Wed, Feb 17, 2010 at 3:48 PM, David Perlman > wrote: >> Surely there is a way to simply print out the local time, date and >> time zone >> without needing to write your own class... I can't believe this is >> the only >> way... >> >> Here's why I don't believe it. Both the datetime and time modules >> provide >> both functions for returning the current local time, and the >> current utc >> time. So, assuming that those functions are trustworthy, it *must* >> be true >> that the OS always knows the current offset from utc time. So why >> is there >> no straightforward way to get that offset in python? I mean, I can >> do this: > > time.timezone gives the offset for standard time. > > Kent > >> >>>>> datetime.datetime.now()-datetime.datetime.utcnow() >> datetime.timedelta(-1, 64799, 999987) >> >> But then, of course, it's off by a few fractions of a microsecond. >> This >> works: >> >>>>> time.localtime()[3]-time.gmtime()[3] >> -6 >> >> But doesn't that seem like a ridiculous hack, well outside of the >> spirit of >> the zen of python? Shouldn't there be one obvious right way to do >> this? >> >> Yes, I know that as William sent, the documentation points out that >> the >> rules the world over are complicated and irrational. Nonetheless, >> it is >> implicit in the existing definitions that the system *knows* the >> current >> offset, even if it doesn't know the whole set of rules... >> >> >> On Feb 17, 2010, at 2:26 PM, Kent Johnson wrote: >> >>> On Wed, Feb 17, 2010 at 3:12 PM, David Perlman >>> wrote: >>>> >>>> Yeah, I got this part. The thing that's hanging me up is that >>>> there >>>> doesn't >>>> seem to be any way to get a tzinfo instance that contains the >>>> current >>>> local >>>> time zone information. You can do time.timezone to get the >>>> seconds from >>>> UTC, but there doesn't seem to be any way to convert that into a >>>> tzinfo! >>>> I >>>> would be perfectly satisfied with this: >>>> >>>> tz=offset_to_tzinfo(time.timezone) # or whatever >>>> aware_now=datetime.datetime.now(tz) >>>> print aware_now.isoformat() >>>> >>>> I'm pretty sure that would give me what I want, but there doesn't >>>> seem to >>>> be >>>> any way to do step one without subclassing tzinfo. This makes me >>>> feel >>>> like >>>> I MUST be missing something obvious, because it shouldn't require >>>> so much >>>> coding just to find out what the current local time and timezone >>>> is! >>> >>> The docs make it clear that you do have to subclass tzinfo, that no >>> implementations are provided. >>> It sounds like you want the LocalTimezone class in the examples at >>> the >>> bottom of this section - "A class capturing the platform's idea of >>> local time": >>> http://docs.python.org/library/datetime.html#tzinfo-objects >>> >>> Kent >> >> -- >> -dave---------------------------------------------------------------- >> "Pseudo-colored pictures of a person's brain lighting up are >> undoubtedly more persuasive than a pattern of squiggles produced by a >> polygraph. That could be a big problem if the goal is to get to the >> truth." -Dr. Steven Hyman, Harvard >> >> >> >> -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From yam at nerd.cx Wed Feb 17 22:48:59 2010 From: yam at nerd.cx (William Witteman) Date: Wed, 17 Feb 2010 16:48:59 -0500 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> <1c2a2c591002171226r736257bcs761046770d2d98e1@mail.gmail.com> <4E5DE93E-B945-4A2B-8B64-47385D7128C4@wisc.edu> <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> Message-ID: <20100217214859.GA26279@yam.witteman.ca> On Wed, Feb 17, 2010 at 03:24:26PM -0600, David Perlman wrote: >But this doesn't help, because then you still don't know whether it's >dst or not. You then would have to jump through whatever >convolutions to do that calculation. > >All I want to know is the *current* offset between local time and >utc. I know the system has this information already; it doesn't >require any kind of fancy calculations about global politics or >anything. Well, does time.timezone help? It returns time offset from UTC in seconds. -- yours, William From kent37 at tds.net Wed Feb 17 23:10:07 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Feb 2010 17:10:07 -0500 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: <4D27BAA2-C9AB-4599-8BA3-B02C1CD3B6F5@wisc.edu> References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> <1c2a2c591002171226r736257bcs761046770d2d98e1@mail.gmail.com> <4E5DE93E-B945-4A2B-8B64-47385D7128C4@wisc.edu> <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> <4D27BAA2-C9AB-4599-8BA3-B02C1CD3B6F5@wisc.edu> Message-ID: <1c2a2c591002171410n1f53d369lff489e4bd6347c4f@mail.gmail.com> On Wed, Feb 17, 2010 at 4:37 PM, David Perlman wrote: > OK, here's a function that does precisely what I want: > > def tzDelta(): > ?"""by whatever means necessary, return the current offset of the local time > from utc.""" > ?s=time.time() > ?t,u=time.localtime(s),time.gmtime(s) > ?osec=3600*(t[3]-u[3]) + 60*(t[4]-u[4]) + (t[5]-u[5]) > ?return datetime.timedelta(seconds=osec) > > > As far as I can tell, this should always work. ?So wouldn't it be nice if > there were a less convoluted way to get this?? Here is a shorter version based on the LocalTimezone example, and it only gets the time once so there is no possible race condition: In [5]: from datetime import timedelta In [6]: import time In [15]: def utcoffset(): ....: if time.localtime().tm_isdst > 0: ....: return timedelta(seconds = -time.altzone) ....: return timedelta(seconds = -time.timezone) ....: In [16]: utcoffset() Out[16]: datetime.timedelta(-1, 68400) Kent From kent37 at tds.net Wed Feb 17 23:10:07 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 17 Feb 2010 17:10:07 -0500 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: <4D27BAA2-C9AB-4599-8BA3-B02C1CD3B6F5@wisc.edu> References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> <1c2a2c591002171226r736257bcs761046770d2d98e1@mail.gmail.com> <4E5DE93E-B945-4A2B-8B64-47385D7128C4@wisc.edu> <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> <4D27BAA2-C9AB-4599-8BA3-B02C1CD3B6F5@wisc.edu> Message-ID: <1c2a2c591002171410n1f53d369lff489e4bd6347c4f@mail.gmail.com> On Wed, Feb 17, 2010 at 4:37 PM, David Perlman wrote: > OK, here's a function that does precisely what I want: > > def tzDelta(): > ?"""by whatever means necessary, return the current offset of the local time > from utc.""" > ?s=time.time() > ?t,u=time.localtime(s),time.gmtime(s) > ?osec=3600*(t[3]-u[3]) + 60*(t[4]-u[4]) + (t[5]-u[5]) > ?return datetime.timedelta(seconds=osec) > > > As far as I can tell, this should always work. ?So wouldn't it be nice if > there were a less convoluted way to get this?? Here is a shorter version based on the LocalTimezone example, and it only gets the time once so there is no possible race condition: In [5]: from datetime import timedelta In [6]: import time In [15]: def utcoffset(): ....: if time.localtime().tm_isdst > 0: ....: return timedelta(seconds = -time.altzone) ....: return timedelta(seconds = -time.timezone) ....: In [16]: utcoffset() Out[16]: datetime.timedelta(-1, 68400) Kent From sander.sweers at gmail.com Wed Feb 17 23:17:08 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 17 Feb 2010 23:17:08 +0100 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: <4D27BAA2-C9AB-4599-8BA3-B02C1CD3B6F5@wisc.edu> References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> <1c2a2c591002171226r736257bcs761046770d2d98e1@mail.gmail.com> <4E5DE93E-B945-4A2B-8B64-47385D7128C4@wisc.edu> <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> <4D27BAA2-C9AB-4599-8BA3-B02C1CD3B6F5@wisc.edu> Message-ID: On 17 February 2010 22:37, David Perlman wrote: > As far as I can tell, this should always work. ?So wouldn't it be nice if > there were a less convoluted way to get this?? There is pytz [1] which should provide a simpler way to manage timezone info in python. Greets Sander [1] http://pytz.sourceforge.net/ From dperlman at wisc.edu Wed Feb 17 23:38:57 2010 From: dperlman at wisc.edu (David Perlman) Date: Wed, 17 Feb 2010 16:38:57 -0600 Subject: [Tutor] datetime, time zones, and ISO time In-Reply-To: References: <107BF439-AE8A-46B1-B332-1C39E61EDEC3@wisc.edu> <20100217194229.GA24329@yam.witteman.ca> <1c2a2c591002171226r736257bcs761046770d2d98e1@mail.gmail.com> <4E5DE93E-B945-4A2B-8B64-47385D7128C4@wisc.edu> <1c2a2c591002171312n677b9dc8mf301b97a04e3c1e7@mail.gmail.com> <4D27BAA2-C9AB-4599-8BA3-B02C1CD3B6F5@wisc.edu> Message-ID: <5ADF6372-B99B-4B13-B23D-5BA0E5D9ACD5@wisc.edu> On Feb 17, 2010, at 4:17 PM, Sander Sweers wrote: > On 17 February 2010 22:37, David Perlman wrote: >> As far as I can tell, this should always work. So wouldn't it be >> nice if >> there were a less convoluted way to get this?? > > There is pytz [1] which should provide a simpler way to manage > timezone info in python. Well, this is actually more complicated, not simpler. The description says: pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library Reference (datetime.tzinfo). I don't want to deal with any of that stuff, I just want to know the actual current offset between local time and UTC. I don't care what the offset is in Nepal; I don't care what the offset will be come summertime; I don't care about anything in the Olson tz database. I just want something to tell me the current offset, right here, right now, on my own computer. Anyway, I already wrote a function to calculate it, so it's a done deal. At this point I'm just really surprised that I had to... For completeness, here's what I came up with. The format function was necessary because Google calendar queries require the time zone to be represented in the string like: 2010-03-01T21:00:00.000-06:00 However the isoformat() methods in python instead give something like: 2010-03-01T21:00:00.000-0600 which gives a server error if you try to send it to Google. Unfortunately, and also bizarrely, even the strftime() doesn't provide any way to generate the format Google demands, so I had to also write a function to do the formatting. def tzDeltaForm(self, tzd=None): """return the tzdelta in the format Google wants it, such as -06:00""" if not tzd: tzd=self.tzDelta() if tzd < 0: sign = -1 tzd = -tzd else: sign = 1 h = sign * tzd // 3600 m = (tzd % 3600) // 60 form = '%+03d:%02d' % (h,m) return form def tzDelta(self): """by whatever means necessary, return the current offset of the local time from utc.""" s=time.time() t,u=time.localtime(s),time.gmtime(s) osec=3600*(t[3]-u[3]) + 60*(t[4]-u[4]) + (t[5]-u[5]) #return datetime.timedelta(seconds=osec) return osec OK, I hope that is helpful to someone else someday, because it has been an astonishing amount of pain to accomplish something seemingly so simple... Thanks to everyone for the input, every bit of it helped guide me along. :) -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From sierra_mtnview at sbcglobal.net Thu Feb 18 04:07:20 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 17 Feb 2010 19:07:20 -0800 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 Message-ID: <4B7CAEE8.7070303@sbcglobal.net> I'm following the tutorial and ran into a snag. Here is the console output.( Can I do this from IDLE?) C:\Sandia_Meteors\Sentinel_Development\Learn_Python>c:\python25\python setup.py Traceback (most recent call last): File "setup.py", line 2, in import py2exe ImportError: No module named py2exe Note the need to back pedal to c:\python25\ Perhaps I need some path variable set? -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From denis.spir at free.fr Thu Feb 18 10:13:33 2010 From: denis.spir at free.fr (spir) Date: Thu, 18 Feb 2010 10:13:33 +0100 Subject: [Tutor] pure symbol -- __subtype__ Message-ID: <20100218101333.7b052520@o> Hello, I was lately implementing a kind of "pure symbol" type. What I call pure symbols is these kinds of constants that refer to pure "idea", so that they have no real obvious value. We usually _arbitrarily_ give them as value an int, a string, a boolean, an empty object: BLACK, WHITE = False, True GUARD_FLAG = object() N,S,W,E = 1,2,3,4 READ,WRITE = 'r','w' ... Such symbols, especially the ones we give boolean values, often match the use of C preprocessor flags: #define GUARD_FLAG ... #ifdef GUARD_FLAG ... When there is a set of symbols, they match Pascal enumerations: var direction: (N, S, W, E); They are often used as func parameters. f = open("foo.txt", WRITE) The latter case is so common that numerous (built-in or third-party) libraries define a whole load of "pure symbol" constant values to be used as func arguments: pattern = re.compile(format, re.MULTILINE) This is very heavy, indeed. But alternatives I can imagine are worse: * Use literal (unnamed) values: illegible. * Use unprefixed names: pollutes global namespace. I cannot find any good solution for this issue. This is my first question. These pure symbol are, I guess, a very close notion to the one of "nominals" (see http://en.wikipedia.org/wiki/Nominal_number). And in fact pascal enums are nominal types. So, I wrote this for isolated symbols: class Nominal(object): count = 0 def __init__(self, value=None): self.type = self.__class__ self.type.count += 1 # no need to restrict user-provided value, if any, to natural integer self.value = value if value is not None else self.type.count def __str__(self): typeName = self.type.__name__ return "%s:(%s)" %(typeName,self.value) x,y,z = Nominal(),Nominal(),Nominal() print x,y,z # Nominal:(1) Nominal:(2) Nominal:(3) The type here can only be Nominal; and the value is not really needed, indeed, but it can be useful in some cases. Especially, this type can be the base of derived Nominal types, i.e. pascal-like enums. Like in Pascal, making the instances comparable can be very handy: def __lt__(self, other): assert(isinstance(other, Nominal)) return self.value < other.value class CardSuite(Nominal): pass club,diamond,heart,spade = CardSuite(),CardSuite(),CardSuite(),CardSuite() print club,diamond,heart,spade # CardSuite:(4) CardSuite:(5) CardSuite:(6) CardSuite:(7) print(diamond < heart) # True An issue is that a subtupe should start with count==0. I could not find any way to do that, so I ended up writing a subtype factory. But this goes against the language, for the user cannot use anymore the dedicated idiom "class CardSuite(Nominal)". Also, the type's name has to be *stupidly* passed as argument. So, the content of the method itself clearly shows how artificial this solution is: @classmethod def subtype(cls, name): class DummyName(cls): pass DummyName.count = 0 DummyName.__name__ = name return X CardSuite = Nominal.subtype("CardSuite") club,diamond,heart,spade = CardSuite(),CardSuite(),CardSuite(),CardSuite() print club,diamond,heart,spade # CardSuite:(1) CardSuite:(2) CardSuite:(3) CardSuite:(4) print(diamond < heart) # True Actually, what I need is a kind of __subtype__ magic method that acts for subtyping the same way __init__ does for instanciation. Then, I could write: @staticmethod def __subtype__(subtype): subtype.count = 0 (Note that here I do not need a classmethod, as staticmethod is enough.) So, do you see any other solution? (I have probably overlooked some) And, what do you think of __subtype__? Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Thu Feb 18 10:15:45 2010 From: denis.spir at free.fr (spir) Date: Thu, 18 Feb 2010 10:15:45 +0100 Subject: [Tutor] pure symbol -- __subtype__ In-Reply-To: <20100218101333.7b052520@o> References: <20100218101333.7b052520@o> Message-ID: <20100218101545.4f83af80@o> PS: see also on the topic: http://en.wikipedia.org/wiki/Enumerated_type On Thu, 18 Feb 2010 10:13:33 +0100 spir wrote: > Hello, > > I was lately implementing a kind of "pure symbol" type. What I call pure symbols is these kinds of constants that refer to pure "idea", so that they have no real obvious value. We usually _arbitrarily_ give them as value an int, a string, a boolean, an empty object: > BLACK, WHITE = False, True > GUARD_FLAG = object() > N,S,W,E = 1,2,3,4 > READ,WRITE = 'r','w' > ... > > Such symbols, especially the ones we give boolean values, often match the use of C preprocessor flags: > #define GUARD_FLAG > ... > #ifdef GUARD_FLAG ... > When there is a set of symbols, they match Pascal enumerations: > var > direction: (N, S, W, E); > They are often used as func parameters. > f = open("foo.txt", WRITE) > The latter case is so common that numerous (built-in or third-party) libraries define a whole load of "pure symbol" constant values to be used as func arguments: > pattern = re.compile(format, re.MULTILINE) > > This is very heavy, indeed. But alternatives I can imagine are worse: > * Use literal (unnamed) values: illegible. > * Use unprefixed names: pollutes global namespace. > I cannot find any good solution for this issue. This is my first question. > > These pure symbol are, I guess, a very close notion to the one of "nominals" (see http://en.wikipedia.org/wiki/Nominal_number). And in fact pascal enums are nominal types. So, I wrote this for isolated symbols: > class Nominal(object): > count = 0 > def __init__(self, value=None): > self.type = self.__class__ > self.type.count += 1 > # no need to restrict user-provided value, if any, to natural integer > self.value = value if value is not None else self.type.count > def __str__(self): > typeName = self.type.__name__ > return "%s:(%s)" %(typeName,self.value) > x,y,z = Nominal(),Nominal(),Nominal() > print x,y,z # Nominal:(1) Nominal:(2) Nominal:(3) > > The type here can only be Nominal; and the value is not really needed, indeed, but it can be useful in some cases. Especially, this type can be the base of derived Nominal types, i.e. pascal-like enums. Like in Pascal, making the instances comparable can be very handy: > def __lt__(self, other): > assert(isinstance(other, Nominal)) > return self.value < other.value > class CardSuite(Nominal): pass > club,diamond,heart,spade = CardSuite(),CardSuite(),CardSuite(),CardSuite() > print club,diamond,heart,spade # CardSuite:(4) CardSuite:(5) CardSuite:(6) CardSuite:(7) > print(diamond < heart) # True > > An issue is that a subtupe should start with count==0. I could not find any way to do that, so I ended up writing a subtype factory. But this goes against the language, for the user cannot use anymore the dedicated idiom "class CardSuite(Nominal)". Also, the type's name has to be *stupidly* passed as argument. So, the content of the method itself clearly shows how artificial this solution is: > @classmethod > def subtype(cls, name): > class DummyName(cls): pass > DummyName.count = 0 > DummyName.__name__ = name > return X > CardSuite = Nominal.subtype("CardSuite") > club,diamond,heart,spade = CardSuite(),CardSuite(),CardSuite(),CardSuite() > print club,diamond,heart,spade # CardSuite:(1) CardSuite:(2) CardSuite:(3) CardSuite:(4) > print(diamond < heart) # True > > Actually, what I need is a kind of __subtype__ magic method that acts for subtyping the same way __init__ does for instanciation. Then, I could write: > @staticmethod > def __subtype__(subtype): > subtype.count = 0 > (Note that here I do not need a classmethod, as staticmethod is enough.) > > So, do you see any other solution? (I have probably overlooked some) > And, what do you think of __subtype__? > > Denis > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ ________________________________ la vita e estrany http://spir.wikidot.com/ From zhuchunml at gmail.com Thu Feb 18 10:30:48 2010 From: zhuchunml at gmail.com (Joson) Date: Thu, 18 Feb 2010 17:30:48 +0800 Subject: [Tutor] How to delete the last line from a file efficiently? Message-ID: Hi all, Now I have a text file about 1MB. Sometimes I need to remove the last line. The current method I use is reading all content, finding the last sentence, remove it and write the new content to the file. So, it need to read a 1MB file and write a 1MB file. It's ineffictient, I think. Are there any other methods? -------------- next part -------------- An HTML attachment was scrubbed... URL: From c.t.matsumoto at gmail.com Thu Feb 18 10:59:34 2010 From: c.t.matsumoto at gmail.com (C.T. Matsumoto) Date: Thu, 18 Feb 2010 10:59:34 +0100 Subject: [Tutor] Python and algorithms Message-ID: <4B7D0F86.1070703@gmail.com> Hello Tutors, Can someone point me to any resources that can teach me about algorithms in python? I'm interested in learning how to analyze and make an algorithm. Oh, I have no background in math, but a sturdy knowledge of python, and I want to make more efficient code. Cheers, Todd From cwitts at compuscan.co.za Thu Feb 18 11:33:53 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 18 Feb 2010 12:33:53 +0200 Subject: [Tutor] Python and algorithms In-Reply-To: <4B7D0F86.1070703@gmail.com> References: <4B7D0F86.1070703@gmail.com> Message-ID: <4B7D1791.70602@compuscan.co.za> C.T. Matsumoto wrote: > Hello Tutors, > > Can someone point me to any resources that can teach me about > algorithms in python? > > I'm interested in learning how to analyze and make an algorithm. > > Oh, I have no background in math, but a sturdy knowledge of python, > and I want to > make more efficient code. > > Cheers, > > Todd > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > You can try this out: Data Structures and Algorithms with Object-Oriented Design Patterns in Python http://www.brpreiss.com/books/opus7/html/book.html -- Kind Regards, Christian Witts From c.t.matsumoto at gmail.com Thu Feb 18 11:39:36 2010 From: c.t.matsumoto at gmail.com (C.T. Matsumoto) Date: Thu, 18 Feb 2010 11:39:36 +0100 Subject: [Tutor] Python and algorithms In-Reply-To: <4B7D1791.70602@compuscan.co.za> References: <4B7D0F86.1070703@gmail.com> <4B7D1791.70602@compuscan.co.za> Message-ID: <4B7D18E8.2060700@gmail.com> Thanks Christian, I'd found that resource and at first glance it looks above my head. The book also has examples based on existing algorithms and analyzes them. When I said analyze I suppose I meant analyze a problem and make an algorithm out of that. Not to mention the math is out of my skill set (for now). I'm looking for the real basics. I'm not sure if I can get away with applying the subject directly into python, without first studying some math. On the other hand I've made it this far and I suppose there are other developers out there that didn't have the math background and worked out how to efficiently solve problems. Thanks, Todd Christian Witts wrote: > C.T. Matsumoto wrote: >> Hello Tutors, >> >> Can someone point me to any resources that can teach me about >> algorithms in python? >> >> I'm interested in learning how to analyze and make an algorithm. >> >> Oh, I have no background in math, but a sturdy knowledge of python, >> and I want to >> make more efficient code. >> >> Cheers, >> >> Todd >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > You can try this out: > Data Structures and Algorithms with Object-Oriented Design Patterns in > Python > http://www.brpreiss.com/books/opus7/html/book.html > From cwitts at compuscan.co.za Thu Feb 18 11:49:17 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 18 Feb 2010 12:49:17 +0200 Subject: [Tutor] How to delete the last line from a file efficiently? In-Reply-To: References: Message-ID: <4B7D1B2D.90807@compuscan.co.za> Joson wrote: > Hi all, > Now I have a text file about 1MB. Sometimes I need to remove the > last line. > The current method I use is reading all content, finding the last > sentence, remove it and write the new content to the file. > So, it need to read a 1MB file and write a 1MB file. It's > ineffictient, I think. Are there any other methods? > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Take a look at file.seek to move to a specific section of the file and file.truncate to truncate a file at a specific size, rough implementation would be something like. BUFFER = 2**10 # Set your buffer size f = open(filename, 'r') multiple = -1 found_it = False while not found_it: f.seek(BUFFER * multiple, os.SEEK_END) # Seeks from the file endpoint the specified by your buffer * 'iteration' of the app offset = f.tell() # gets the current position data = f.read(BUFFER) # read in your data and process it # perform operations to get your termination point offset if termination_point_not_found: multiple -= 1 else: # once you find your position to end the file on truncate the file and exit loop f.truncate(offset + termination_point_offset) found_it = True f.close() It's untested code, but it should work just fine. As for how fast it is by comparison, I unfortunately don't have time to benchmark it. -- Kind Regards, Christian Witts From steve at pearwood.info Thu Feb 18 12:08:22 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 18 Feb 2010 22:08:22 +1100 Subject: [Tutor] pure symbol -- __subtype__ In-Reply-To: <20100218101333.7b052520@o> References: <20100218101333.7b052520@o> Message-ID: <201002182208.22889.steve@pearwood.info> On Thu, 18 Feb 2010 08:13:33 pm spir wrote: > Hello, > > I was lately implementing a kind of "pure symbol" type. What I call > pure symbols is these kinds of constants that refer to pure "idea", > so that they have no real obvious value. We usually _arbitrarily_ > give them as value an int, a string, a boolean, an empty object: If you are interested in this, there are various modules on PyPI for them, such as: http://pypi.python.org/pypi/enum/ which probably does everything you want. Unfortunately any enum solution is going to be rather heavyweight compared to (say) Pascal, which can simply give each enum an integer value and have the compiler enforce separation of types. (In other words, all the heavy complexity is in the compiler rather than the runtime environment.) If you want a lightweight solution, just use constant strings or integers. > Actually, what I need is a kind of __subtype__ magic method that acts > for subtyping the same way __init__ does for instanciation. That's what metaclasses are for. -- Steven D'Aprano From cwitts at compuscan.co.za Thu Feb 18 12:21:06 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 18 Feb 2010 13:21:06 +0200 Subject: [Tutor] Python and algorithms In-Reply-To: <4B7D18E8.2060700@gmail.com> References: <4B7D0F86.1070703@gmail.com> <4B7D1791.70602@compuscan.co.za> <4B7D18E8.2060700@gmail.com> Message-ID: <4B7D22A2.5080304@compuscan.co.za> C.T. Matsumoto wrote: > Thanks Christian, > > I'd found that resource and at first glance it looks above my head. > The book also > has examples based on existing algorithms and analyzes them. When I > said analyze > I suppose I meant analyze a problem and make an algorithm out of that. > > Not to mention the math is out of my skill set (for now). > > I'm looking for the real basics. I'm not sure if I can get away with > applying the > subject directly into python, without first studying some math. On the > other > hand I've made it this far and I suppose there are other developers > out there > that didn't have the math background and worked out how to efficiently > solve > problems. > > Thanks, > > Todd > > Christian Witts wrote: >> C.T. Matsumoto wrote: >>> Hello Tutors, >>> >>> Can someone point me to any resources that can teach me about >>> algorithms in python? >>> >>> I'm interested in learning how to analyze and make an algorithm. >>> >>> Oh, I have no background in math, but a sturdy knowledge of python, >>> and I want to >>> make more efficient code. >>> >>> Cheers, >>> >>> Todd >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> You can try this out: >> Data Structures and Algorithms with Object-Oriented Design Patterns >> in Python >> http://www.brpreiss.com/books/opus7/html/book.html >> > > Hi Todd, Possibly look around to see if you can get a copy of Introduction to Data Structures and Algorithms in Python (http://www.cs.luther.edu/~bmiller/Papers/booktoc.pdf), not sure if it's something printed outside of the university but their ToC might be more in line with what you're looking for. Potentially: Design & Analysis of Algorithms (http://www.personal.kent.edu/~rmuhamma/Algorithms/algorithm.html) Algorithms Wikibook (http://en.wikibooks.org/wiki/Algorithms) Intro to Algorithms 3rd Edition (http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&tid=11866) I've never personally seen a resource with the intention of teaching you how to analyse a problem and create an algorithmic solution without first teaching you some of the fundamental mathematics and already existing algorithmic solutions. Hope some of that helps. -- Kind Regards, Christian Witts From kent37 at tds.net Thu Feb 18 13:05:42 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Feb 2010 07:05:42 -0500 Subject: [Tutor] Python and algorithms In-Reply-To: <4B7D0F86.1070703@gmail.com> References: <4B7D0F86.1070703@gmail.com> Message-ID: <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> On Thu, Feb 18, 2010 at 4:59 AM, C.T. Matsumoto wrote: > Hello Tutors, > > Can someone point me to any resources that can teach me about algorithms in > python? > > I'm interested in learning how to analyze and make an algorithm. I have been reading The Algorithm Design Manual http://www.algorist.com/ I find it more readable than Cormen, et al. But is that what you are asking for, or are you trying to sharpen your problem-solving skills? Many progamming problems are solved by simple loops and data structures without explicitly using any algorithms that you would find in a book such as this. Kent From krohit at mail.zeomega.com Thu Feb 18 11:05:36 2010 From: krohit at mail.zeomega.com (Rohit Kumar) Date: Thu, 18 Feb 2010 15:35:36 +0530 (IST) Subject: [Tutor] How to delete the last line from a file efficiently? In-Reply-To: Message-ID: <1906408122.6164.1266487535982.JavaMail.root@mail.zeomega.com> Here is the efficient code than your code: ==============CODE====================== lines = file('file1.txt', 'r').readlines() print lines del lines[-1] print lines file('file1.txt', 'w').writelines(lines) ============================================ Please let me know if any issues. Regards, Rohit Kumar ============== Software Developer - Trainee ZeOmega Infotech Private Limited RLP Building, Bangalore - 560047 Phone: 080-41666070 Ext: 126 krohit at zeomega.com www.zeomega.com Proven. Progressive. Partner. ******************************************************************************* CONFIDENTIALITY NOTICE: This message (including any attachments) may contain ZeOmega's confidential information, protected by law. Forwarding it to individuals, other than those with a need to know, without the permission of the sender, is prohibited. This message is intended for specific individual(s) or entity to whom it is intended even if addressed incorrectly. If you are not the intended recipient, you should delete this message and are hereby notified that any disclosure,copying, or distribution of this message or taking any action based upon it, is strictly prohibited. ******************************************************************************* ----- Original Message ----- From: "Joson" To: Tutor at python.org Sent: Thursday, February 18, 2010 3:00:48 PM Subject: [Tutor] How to delete the last line from a file efficiently? Hi all, Now I have a text file about 1MB. Sometimes I need to remove the last line. The current method I use is reading all content, finding the last sentence, remove it and write the new content to the file. So, it need to read a 1MB file and write a 1MB file. It's ineffictient, I think. Are there any other methods? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From c.t.matsumoto at gmail.com Thu Feb 18 14:17:12 2010 From: c.t.matsumoto at gmail.com (C.T. Matsumoto) Date: Thu, 18 Feb 2010 14:17:12 +0100 Subject: [Tutor] Python and algorithms In-Reply-To: <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> Message-ID: <4B7D3DD8.7050908@gmail.com> Kent Johnson wrote: > On Thu, Feb 18, 2010 at 4:59 AM, C.T. Matsumoto wrote: > >> Hello Tutors, >> >> Can someone point me to any resources that can teach me about algorithms in >> python? >> >> I'm interested in learning how to analyze and make an algorithm. >> > > I have been reading The Algorithm Design Manual > http://www.algorist.com/ > > I find it more readable than Cormen, et al. > > But is that what you are asking for, or are you trying to sharpen your > problem-solving skills? Many progamming problems are solved by simple > loops and data structures without explicitly using any algorithms that > you would find in a book such as this. > > Kent > > I'd say sharpening my problem solving skills. I thought that was often tied to building an algorithm. The example Walter Prins provided I thought fit what I was looking for. Cheers, T From anand.shashwat at gmail.com Thu Feb 18 14:47:10 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Thu, 18 Feb 2010 19:17:10 +0530 Subject: [Tutor] Python and algorithms In-Reply-To: <4B7D3DD8.7050908@gmail.com> References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com> Message-ID: One approach can be to go for CLRS and code the algorithms in python. However I am not too sure you can grasp it at your level. Also if you think your maths skills are not there yet, I suggest improve your math skills first. On Thu, Feb 18, 2010 at 6:47 PM, C.T. Matsumoto wrote: > Kent Johnson wrote: > >> On Thu, Feb 18, 2010 at 4:59 AM, C.T. Matsumoto >> wrote: >> >> >>> Hello Tutors, >>> >>> Can someone point me to any resources that can teach me about algorithms >>> in >>> python? >>> >>> I'm interested in learning how to analyze and make an algorithm. >>> >>> >> >> I have been reading The Algorithm Design Manual >> http://www.algorist.com/ >> >> I find it more readable than Cormen, et al. >> >> But is that what you are asking for, or are you trying to sharpen your >> problem-solving skills? Many progamming problems are solved by simple >> loops and data structures without explicitly using any algorithms that >> you would find in a book such as this. >> >> Kent >> >> >> > I'd say sharpening my problem solving skills. I thought that was often > tied to building an algorithm. The example Walter Prins provided I > thought fit what I was looking for. > > Cheers, > > > T > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Feb 18 15:11:22 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Feb 2010 09:11:22 -0500 Subject: [Tutor] Python and algorithms In-Reply-To: <4B7D3DD8.7050908@gmail.com> References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com> Message-ID: <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> On Thu, Feb 18, 2010 at 8:17 AM, C.T. Matsumoto wrote: > Kent Johnson wrote: >> But is that what you are asking for, or are you trying to sharpen your >> problem-solving skills? Many progamming problems are solved by simple >> loops and data structures without explicitly using any algorithms that >> you would find in a book such as this. > > I'd say sharpening my problem solving skills. I thought that was often > tied to building an algorithm. The example Walter Prins provided I > thought fit what I was looking for. I don't see Walter Prins' example. It's true that solving a problem often involves creating an algorithm in a broad sense. The formal study of algorithms studies specific techniques and algorithms that have proven to be useful to solve many hard problems. In my experience most programming problems do not require use of these formal algorithms, at least not explicitly. Some are used by Python under the hood, for example dicts are hash tables, heapq is a priority queue, etc. It is very useful to know when to apply these but you don't have to understand the details of how they work. Unfortunately I can't point you to a good resource, maybe that would be a good project for me... Kent From c.t.matsumoto at gmail.com Thu Feb 18 15:43:52 2010 From: c.t.matsumoto at gmail.com (C.T. Matsumoto) Date: Thu, 18 Feb 2010 15:43:52 +0100 Subject: [Tutor] Python and algorithms In-Reply-To: <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com> <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> Message-ID: <4B7D5228.9030507@gmail.com> Kent Johnson wrote: > On Thu, Feb 18, 2010 at 8:17 AM, C.T. Matsumoto wrote: > >> Kent Johnson wrote: >> > > >>> But is that what you are asking for, or are you trying to sharpen your >>> problem-solving skills? Many progamming problems are solved by simple >>> loops and data structures without explicitly using any algorithms that >>> you would find in a book such as this. >>> >> I'd say sharpening my problem solving skills. I thought that was often >> tied to building an algorithm. The example Walter Prins provided I >> thought fit what I was looking for. >> > > I don't see Walter Prins' example. > > It's true that solving a problem often involves creating an algorithm > in a broad sense. The formal study of algorithms studies specific > techniques and algorithms that have proven to be useful to solve many > hard problems. In my experience most programming problems do not > require use of these formal algorithms, at least not explicitly. Some > are used by Python under the hood, for example dicts are hash tables, > heapq is a priority queue, etc. It is very useful to know when to > apply these but you don't have to understand the details of how they > work. > > Unfortunately I can't point you to a good resource, maybe that would > be a good project for me... > > Kent > > Here is the example. "To keep this simple and practical, as a suggestion, consider the problem of sorting a list (a pack of cards, or a list of names or whatever you want) into order." Yes, there are many built-ins that wrap good algorithms, so I guess I'm leaning more toward problem solving. The above example must be solved without using sorted() or list.sort(). T From kent37 at tds.net Thu Feb 18 16:07:38 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 18 Feb 2010 10:07:38 -0500 Subject: [Tutor] Python and algorithms In-Reply-To: <4B7D5228.9030507@gmail.com> References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com> <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> <4B7D5228.9030507@gmail.com> Message-ID: <1c2a2c591002180707p2fe9af2eu94fd999bab963e84@mail.gmail.com> On Thu, Feb 18, 2010 at 9:43 AM, C.T. Matsumoto wrote: > Here is the example. > > "To keep this simple and practical, as a suggestion, consider the problem of > sorting a list (a pack of cards, or a list of names or whatever you want) > into order." > > Yes, there are many built-ins that wrap good algorithms, so I guess I'm > leaning more toward problem solving. The above example must be solved > without using sorted() or list.sort(). To solve this without using the built-in sort then you will be learning about sorting which is a major portion of the study of algorithms. So, if you want to learn about sorting algorithms, this is a good problem to ponder. If you want to learn to be a better Python programmer, I'm not sure it is helpful - the built-in sort is excellent and you should be learning how to use it effectively, for example, given a list of (first name, last name) print the list sorted by first name, then sorted by last name. Kent From c.t.matsumoto at gmail.com Thu Feb 18 16:16:00 2010 From: c.t.matsumoto at gmail.com (C.T. Matsumoto) Date: Thu, 18 Feb 2010 16:16:00 +0100 Subject: [Tutor] Python and algorithms In-Reply-To: <1c2a2c591002180707p2fe9af2eu94fd999bab963e84@mail.gmail.com> References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com> <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> <4B7D5228.9030507@gmail.com> <1c2a2c591002180707p2fe9af2eu94fd999bab963e84@mail.gmail.com> Message-ID: <4B7D59B0.9050502@gmail.com> Kent Johnson wrote: > On Thu, Feb 18, 2010 at 9:43 AM, C.T. Matsumoto wrote: > > >> Here is the example. >> >> "To keep this simple and practical, as a suggestion, consider the problem of >> sorting a list (a pack of cards, or a list of names or whatever you want) >> into order." >> >> Yes, there are many built-ins that wrap good algorithms, so I guess I'm >> leaning more toward problem solving. The above example must be solved >> without using sorted() or list.sort(). >> > > To solve this without using the built-in sort then you will be > learning about sorting which is a major portion of the study of > algorithms. > > So, if you want to learn about sorting algorithms, this is a good > problem to ponder. If you want to learn to be a better Python > programmer, I'm not sure it is helpful - the built-in sort is > excellent and you should be learning how to use it effectively, for > example, given a list of (first name, last name) print the list sorted > by first name, then sorted by last name. > > Kent > > Cheers Kent. I'll take your example too. As for the other example I'm already quite stuck. T From la.foma at gmail.com Thu Feb 18 17:23:42 2010 From: la.foma at gmail.com (Juli) Date: Thu, 18 Feb 2010 11:23:42 -0500 Subject: [Tutor] pyMVPA and OSError Message-ID: <790bcb671002180823p610e19d7rb25920bd84f478f1@mail.gmail.com> Dear All, I am very much new to python, therefore I am likely to feel stupid about asking this. I need pyMPVA module to play around with some fMRI data. I have installed Python2.6 on Mac OS X Leopard. When I input >>> import mvpa i get a deprecation warning, which is not a problem, however when I try the following: >>> >>> import mvpa.suite as mvpa i do not get a deprecating warning however I get a number of errors that are as follows: >>> import mvpa.suite as mvpa Traceback (most recent call last): File "", line 1, in import mvpa.suite as mvpa File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/suite.py", line 38, in from mvpa.algorithms.cvtranserror import * File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/algorithms/cvtranserror.py", line 15, in from mvpa.measures.base import DatasetMeasure File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/base.py", line 31, in from mvpa.clfs.stats import autoNullDist File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/stats.py", line 772, in if externals.exists('pylab'): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py", line 432, in exists exec _KNOWN[dep] File "", line 1, in File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py", line 249, in __check_pylab import pylab as P File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylab.py", line 1, in from matplotlib.pylab import * File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/pylab.py", line 206, in from matplotlib import mpl # pulls in most modules File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/mpl.py", line 2, in from matplotlib import axis File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/axis.py", line 10, in import matplotlib.font_manager as font_manager File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 1297, in _rebuild() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 1288, in _rebuild fontManager = FontManager() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 980, in __init__ self.ttffiles = findSystemFonts(paths) + findSystemFonts() File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 337, in findSystemFonts for f in get_fontconfig_fonts(fontext): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 298, in get_fontconfig_fonts pipe = subprocess.Popen(['fc-list', '', 'file'], stdout=subprocess.PIPE) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 621, in __init__ errread, errwrite) File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1126, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory ----- I am not sure what the problem is (I do not know enough to pinpoint it at a glance) and I would appreciate any feedback. And I do once again apologize for asking stupid questions. Kind Regards, J. From bermanrl at cfl.rr.com Thu Feb 18 17:25:23 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 18 Feb 2010 11:25:23 -0500 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 In-Reply-To: <4B7CAEE8.7070303@sbcglobal.net> References: <4B7CAEE8.7070303@sbcglobal.net> Message-ID: <000301cab0b6$f8df7150$ea9e53f0$@rr.com> > -----Original Message----- > From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- > bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Wayne Watson > Sent: Wednesday, February 17, 2010 10:07 PM > To: tutor at python.org > Subject: Re: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], > Py2.5 > > I'm following the tutorial and ran into a snag. Here is the console > output.( Can I do this from IDLE?) > > C:\Sandia_Meteors\Sentinel_Development\Learn_Python>c:\python25\pyth > on > setup.py > Traceback (most recent call last): > File "setup.py", line 2, in > import py2exe > ImportError: No module named py2exe > > Note the need to back pedal to c:\python25\ > Perhaps I need some path variable set? > > -- Wayne, When you install py2exe it should insure all the required modules are available to your standard python path. For example, I am running python 2.64 and the py2exe module is in the python path. I don't use IDLE. I use Ipython however I cannot see why IDLE would not work. To tell if you are OK do import py2exe. You should have no problem loading it. If you do, reinstall it. Robert From alan.gauld at btinternet.com Thu Feb 18 19:09:08 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Feb 2010 18:09:08 -0000 Subject: [Tutor] Python and algorithms References: <4B7D0F86.1070703@gmail.com> Message-ID: "C.T. Matsumoto" wrote > Can someone point me to any resources that can teach me about algorithms > in python? algorithm books tend to be fairly language neutral. Search for books by Donald Knuth, his books tend to be considered the canonical references on algorithms in computing. > I'm interested in learning how to analyze and make an algorithm. > > Oh, I have no background in math, but a sturdy knowledge of python In this instance a knowledge of math trumps knowledge of Python unfortunately. Translating math into Python is relatively easy but you probably need the math to develop efficient algorithms. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Feb 18 19:18:26 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Feb 2010 18:18:26 -0000 Subject: [Tutor] Python and algorithms References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com><1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> <4B7D5228.9030507@gmail.com> Message-ID: "C.T. Matsumoto" wrote >>> I'd say sharpening my problem solving skills. I thought that was often >>> tied to building an algorithm. The example Walter Prins provided I >>> thought fit what I was looking for. > "To keep this simple and practical, as a suggestion, consider the problem > of sorting a list (a pack of cards, or a list of names or whatever you > want) into order." > > Yes, there are many built-ins that wrap good algorithms, so I guess I'm > leaning more toward problem solving. The above example must be solved > without using sorted() or list.sort(). OK, having read more I think Knuth will be too deep. Try Programming Pearls by Jon Bentley. It covers more than just algoprithm development and is full of useful generic advice about writing programs (eg dangers of over optimisation etc) but includes quite a lot on algorithm development. And its easy and fun to read too. You can probably get the earlier 2 volumes (try the first as a taster - I see vol2 on Amazon.com for less than $5 and vol1 on Amazon.co.uk for less than ?1) secondhand or the more recent combined single volume. Alan G From anand.shashwat at gmail.com Thu Feb 18 22:34:05 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 19 Feb 2010 03:04:05 +0530 Subject: [Tutor] Python and algorithms In-Reply-To: References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com> <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> <4B7D5228.9030507@gmail.com> Message-ID: Solving problems on ACM UVA , SPOJ, Codechef helps too plus it is fun. On Thu, Feb 18, 2010 at 11:48 PM, Alan Gauld wrote: > > "C.T. Matsumoto" wrote > > I'd say sharpening my problem solving skills. I thought that was often >>>> tied to building an algorithm. The example Walter Prins provided I >>>> thought fit what I was looking for. >>>> >>> > "To keep this simple and practical, as a suggestion, consider the problem >> of sorting a list (a pack of cards, or a list of names or whatever you want) >> into order." >> >> Yes, there are many built-ins that wrap good algorithms, so I guess I'm >> leaning more toward problem solving. The above example must be solved >> without using sorted() or list.sort(). >> > > OK, having read more I think Knuth will be too deep. > > Try Programming Pearls by Jon Bentley. > It covers more than just algoprithm development and is full of useful > generic advice about writing programs (eg dangers of over optimisation > etc) but includes quite a lot on algorithm development. And its easy and > fun to read too. > > You can probably get the earlier 2 volumes (try the first as a taster - I > see vol2 on Amazon.com for less than $5 and vol1 on Amazon.co.uk > for less than ?1) secondhand or the more recent combined single > volume. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Feb 19 01:09:00 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 18 Feb 2010 16:09:00 -0800 Subject: [Tutor] "Sounding" Off, IDLE (Win7) In-Reply-To: <2B7AA81C577B0942A14C2B388867E2C70E054A@harry.shamirlens.co.uk> References: <4B7ADCBE.2090601@sbcglobal.net> <2B7AA81C577B0942A14C2B388867E2C70E054A@harry.shamirlens.co.uk> Message-ID: <4B7DD69C.8090803@sbcglobal.net> Nothing to do with Ctrl-G. Cmd Prompt not open. So if you have a syntax error, no bell rings? I don't want to disable all sounds. On 2/17/2010 2:48 AM, Michael M Mason wrote: > Wayne Watson wrote on 16 February 2010 at 17:58:- > > >> In Win7 IDLE, when I type in something with a syntax >> problem, a bell rings. How do I stop that? I've looked >> at Control Panel Sounds, but don't see anything of >> apparent use. >> > I don't get this on my Win7 machine. But anyway, the sound is > probably the same sound you get if you type CTRL-G at a command > prompt in a DOS box, in which case it isn't one of the sounds > you set in Control Panel. > > You can disable it using Device Manager. It's called 'System > Speaker' and it's under 'System devices'. Right-click and > choose 'Disable'. > > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From rabidpoobear at gmail.com Fri Feb 19 01:16:50 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 18 Feb 2010 18:16:50 -0600 Subject: [Tutor] "Sounding" Off, IDLE (Win7) In-Reply-To: <4B7DD69C.8090803@sbcglobal.net> References: <4B7ADCBE.2090601@sbcglobal.net> <2B7AA81C577B0942A14C2B388867E2C70E054A@harry.shamirlens.co.uk> <4B7DD69C.8090803@sbcglobal.net> Message-ID: System Speaker is just the driver for the builtin speaker in your computer (but it will redirect sound to your main speakers if you have some). You'll get sounds out of your regular speakers, you just won't get system beeps anymore, if you disable System Speaker. On Thu, Feb 18, 2010 at 6:09 PM, Wayne Watson wrote: > Nothing to do with Ctrl-G. Cmd Prompt not open. So if you have a syntax > error, no bell rings? I don't want to disable all sounds. > > > On 2/17/2010 2:48 AM, Michael M Mason wrote: > >> Wayne Watson wrote on 16 February 2010 at 17:58:- >> >> >> >>> In Win7 IDLE, when I type in something with a syntax >>> problem, a bell rings. How do I stop that? I've looked >>> at Control Panel Sounds, but don't see anything of >>> apparent use. >>> >>> >> I don't get this on my Win7 machine. But anyway, the sound is >> probably the same sound you get if you type CTRL-G at a command >> prompt in a DOS box, in which case it isn't one of the sounds >> you set in Control Panel. >> >> You can disable it using Device Manager. It's called 'System >> Speaker' and it's under 'System devices'. Right-click and >> choose 'Disable'. >> >> >> > > -- > "There is nothing so annoying as to have two people > talking when you're busy interrupting." -- Mark Twain > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Feb 19 01:30:28 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 18 Feb 2010 16:30:28 -0800 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 In-Reply-To: <000301cab0b6$f8df7150$ea9e53f0$@rr.com> References: <4B7CAEE8.7070303@sbcglobal.net> <000301cab0b6$f8df7150$ea9e53f0$@rr.com> Message-ID: <4B7DDBA4.5070104@sbcglobal.net> It imported setup fine from the IDLE cmd prompt. Win Cmd prompt is fine to operate it. Just curious about IDLE. I looked in setup.py and don't see what the complaint is. It sure thinks py2exe is not available. I'm now in IDLE's path browser. I see pkgs in ...\lib\site-packages like dateutil, numdisplay, numpy, but no py2exe. Doesn't seem right, since I can import it. I'm pretty sure that during the install that py2exe was headed to site On 2/18/2010 8:25 AM, Robert Berman wrote: >> -----Original Message----- >> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- >> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Wayne Watson >> Sent: Wednesday, February 17, 2010 10:07 PM >> To: tutor at python.org >> Subject: Re: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], >> Py2.5 >> >> I'm following the tutorial and ran into a snag. Here is the console >> output.( Can I do this from IDLE?) >> >> C:\Sandia_Meteors\Sentinel_Development\Learn_Python>c:\python25\pyth >> on >> setup.py >> Traceback (most recent call last): >> File "setup.py", line 2, in >> import py2exe >> ImportError: No module named py2exe >> >> Note the need to back pedal to c:\python25\ >> Perhaps I need some path variable set? >> >> -- >> > Wayne, > > When you install py2exe it should insure all the required modules are > available to your standard python path. For example, I am running python 2.64 > and the py2exe module is in the python path. > > I don't use IDLE. I use Ipython however I cannot see why IDLE would not work. > To tell if you are OK do import py2exe. You should have no problem loading it. > If you do, reinstall it. > > Robert > > > > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Fri Feb 19 01:48:24 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 18 Feb 2010 16:48:24 -0800 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 In-Reply-To: <4B7DDBA4.5070104@sbcglobal.net> References: <4B7CAEE8.7070303@sbcglobal.net> <000301cab0b6$f8df7150$ea9e53f0$@rr.com> <4B7DDBA4.5070104@sbcglobal.net> Message-ID: <4B7DDFD8.7020808@sbcglobal.net> Got it. Fooled myself. I'm converting to Win7 and have my XP keyboard and monitor side by side with the same for XP. I did the world program in XP and py2exe module in W7!! world compiled and ran successfully. Now for a bigger program with matplotlib and tkinter. Maybe I'll just settle for a small matplotlib program for the moment. VBG Thanks very much. On 2/18/2010 4:30 PM, Wayne Watson wrote: > It imported setup fine from the IDLE cmd prompt. Win Cmd prompt is > fine to operate it. Just curious about IDLE. I looked in setup.py and > don't see what the complaint is. It sure thinks py2exe is not available. > > I'm now in IDLE's path browser. I see pkgs in ...\lib\site-packages > like dateutil, numdisplay, numpy, but no py2exe. Doesn't seem right, > since I can import it. I'm pretty sure that during the install that > py2exe was headed to site > > On 2/18/2010 8:25 AM, Robert Berman wrote: >>> -----Original Message----- >>> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- >>> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Wayne Watson >>> Sent: Wednesday, February 17, 2010 10:07 PM >>> To: tutor at python.org >>> Subject: Re: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], >>> Py2.5 >>> >>> I'm following the tutorial and ran into a snag. Here is the console >>> output.( Can I do this from IDLE?) >>> >>> C:\Sandia_Meteors\Sentinel_Development\Learn_Python>c:\python25\pyth >>> on >>> setup.py >>> Traceback (most recent call last): >>> File "setup.py", line 2, in >>> import py2exe >>> ImportError: No module named py2exe >>> >>> Note the need to back pedal to c:\python25\ >>> Perhaps I need some path variable set? >>> >>> -- >> Wayne, >> >> When you install py2exe it should insure all the required modules are >> available to your standard python path. For example, I am running >> python 2.64 >> and the py2exe module is in the python path. >> >> I don't use IDLE. I use Ipython however I cannot see why IDLE would >> not work. >> To tell if you are OK do import py2exe. You should have no problem >> loading it. >> If you do, reinstall it. >> >> Robert >> >> >> > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Fri Feb 19 05:10:16 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 18 Feb 2010 20:10:16 -0800 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 In-Reply-To: <4B7DDFD8.7020808@sbcglobal.net> References: <4B7CAEE8.7070303@sbcglobal.net> <000301cab0b6$f8df7150$ea9e53f0$@rr.com> <4B7DDBA4.5070104@sbcglobal.net> <4B7DDFD8.7020808@sbcglobal.net> Message-ID: <4B7E0F28.6000704@sbcglobal.net> There's a bit of an anomaly. I've compiled 3 small programs now, and in cmd prompt a Dir does not find the file. It finds the py file, but not the completed file. Nevertheless, if I type in the prefix, the desired program executes. On 2/18/2010 4:48 PM, Wayne Watson wrote: > Got it. Fooled myself. I'm converting to Win7 and have my XP keyboard > and monitor side by side with the same for XP. I did the world program > in XP and py2exe module in W7!! > > world compiled and ran successfully. Now for a bigger program with > matplotlib and tkinter. Maybe I'll just settle for a small matplotlib > program for the moment. VBG > > Thanks very much. > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From c.t.matsumoto at gmail.com Fri Feb 19 08:11:27 2010 From: c.t.matsumoto at gmail.com (C.T. Matsumoto) Date: Fri, 19 Feb 2010 08:11:27 +0100 Subject: [Tutor] Python and algorithms In-Reply-To: References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com> <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> <4B7D5228.9030507@gmail.com> Message-ID: <4B7E399F.2070806@gmail.com> Shashwat Anand wrote: > Solving problems on ACM UVA , SPOJ > , Codechef helps too > plus it is fun. > > On Thu, Feb 18, 2010 at 11:48 PM, Alan Gauld > > wrote: > > > "C.T. Matsumoto" > wrote > > I'd say sharpening my problem solving skills. I > thought that was often > tied to building an algorithm. The example Walter > Prins provided I > thought fit what I was looking for. > > > "To keep this simple and practical, as a suggestion, consider > the problem of sorting a list (a pack of cards, or a list of > names or whatever you want) into order." > > Yes, there are many built-ins that wrap good algorithms, so I > guess I'm leaning more toward problem solving. The above > example must be solved without using sorted() or list.sort(). > > > OK, having read more I think Knuth will be too deep. > > Try Programming Pearls by Jon Bentley. > It covers more than just algoprithm development and is full of useful > generic advice about writing programs (eg dangers of over optimisation > etc) but includes quite a lot on algorithm development. And its > easy and > fun to read too. > > You can probably get the earlier 2 volumes (try the first as a > taster - I > see vol2 on Amazon.com for less than $5 and vol1 on Amazon.co.uk > > for less than ?1) secondhand or the more recent combined single > volume. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Okay I'll look into them all. Cheers, T From denis.spir at free.fr Fri Feb 19 12:25:24 2010 From: denis.spir at free.fr (spir) Date: Fri, 19 Feb 2010 12:25:24 +0100 Subject: [Tutor] Python and algorithms In-Reply-To: <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com> <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> Message-ID: <20100219122524.460c3ac1@o> On Thu, 18 Feb 2010 09:11:22 -0500 Kent Johnson wrote: > It's true that solving a problem often involves creating an algorithm > in a broad sense. The formal study of algorithms studies specific > techniques and algorithms that have proven to be useful to solve many > hard problems. In my experience most programming problems do not > require use of these formal algorithms, at least not explicitly. Hello, I would say that what is commonly called "algorithm" in computer science is a given class of possible algorithm that can (more easily) be formally expressed. Especially in mathematical terms. The reason why these are much more studied. But algorithmics can also be more generally understood as the "art & technique" of software design. Then, every programming task involves algorithmics. This may also be called "modelizing", a term than imo sensibly suggests how similar it is to the job of scientists. Modelizing is hard and hard to study because close to infinitely various and complex. Improving one's skills in this field is a whole life's yoga ;-) "I want to get a clearer mind"; "I want to become more lucid". An extremely big, difficult and rich book on the topic of thinking complexity is "la m?thode" by http://en.wikipedia.org/wiki/Edgar_Morin (I don't have references to the english version). Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From norman at smash-net.org Fri Feb 19 13:42:07 2010 From: norman at smash-net.org (=?ISO-8859-15?Q?Norman_Rie=DF?=) Date: Fri, 19 Feb 2010 13:42:07 +0100 Subject: [Tutor] Reading large bz2 Files Message-ID: <4B7E871F.10702@smash-net.org> Hello, i am trying to read a large bz2 file with this code: source_file = bz2.BZ2File(file, "r") for line in source_file: print line.strip() But after 4311 lines, it stoppes without a errormessage. The bz2 file is much bigger though. How can i read the whole file line by line? Thank you. Regards, Norman From bermanrl at cfl.rr.com Fri Feb 19 14:34:12 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Fri, 19 Feb 2010 08:34:12 -0500 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 In-Reply-To: <4B7E0F28.6000704@sbcglobal.net> References: <4B7CAEE8.7070303@sbcglobal.net> <000301cab0b6$f8df7150$ea9e53f0$@rr.com> <4B7DDBA4.5070104@sbcglobal.net> <4B7DDFD8.7020808@sbcglobal.net> <4B7E0F28.6000704@sbcglobal.net> Message-ID: <001101cab168$3954bbd0$abfe3370$@rr.com> Wayne, Somewhere in the tutorial should be a comment about py2exe creating two additional directories: build and dist. Forget about the build directory. If you look in the dist directory you will find the exe file and all supporting files. If you look back to an earlier email you will see a more detailed explanation I sent you. Robert Berman > -----Original Message----- > From: Wayne Watson [mailto:sierra_mtnview at sbcglobal.net] > Sent: Thursday, February 18, 2010 11:10 PM > To: Robert Berman > Cc: tutor at python.org > Subject: Re: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], > Py2.5 > > There's a bit of an anomaly. I've compiled 3 small programs now, and > in > cmd prompt a Dir does not find the file. It finds the py file, but > not > the completed file. Nevertheless, if I type in the prefix, the > desired > program executes. > > On 2/18/2010 4:48 PM, Wayne Watson wrote: > > Got it. Fooled myself. I'm converting to Win7 and have my XP > keyboard > > and monitor side by side with the same for XP. I did the world > program > > in XP and py2exe module in W7!! > > > > world compiled and ran successfully. Now for a bigger program with > > matplotlib and tkinter. Maybe I'll just settle for a small > matplotlib > > program for the moment. VBG > > > > Thanks very much. > > > > -- > "There is nothing so annoying as to have two people > talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Fri Feb 19 16:00:20 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 19 Feb 2010 07:00:20 -0800 Subject: [Tutor] The Disappearing Program (py2exe) Message-ID: <4B7EA784.5040608@sbcglobal.net> I've successfully compiled several small python programs on Win XP into executables using py2exe. A program goes from a name like snowball.py to snowball. A dir in the command prompt window finds snowball.py but not snowball. If I type in snowball, it executes. What's up with that? -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Fri Feb 19 16:38:41 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 19 Feb 2010 07:38:41 -0800 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 In-Reply-To: <001101cab168$3954bbd0$abfe3370$@rr.com> References: <4B7CAEE8.7070303@sbcglobal.net> <000301cab0b6$f8df7150$ea9e53f0$@rr.com> <4B7DDBA4.5070104@sbcglobal.net> <4B7DDFD8.7020808@sbcglobal.net> <4B7E0F28.6000704@sbcglobal.net> <001101cab168$3954bbd0$abfe3370$@rr.com> Message-ID: <4B7EB081.6060906@sbcglobal.net> Sneaky! :-) Yes, I now recall you mentioning it earlier. I'm looking at dist right now. I see a program I built in a folder above dist, pylab_scatter.exe. Interestingly, if I fire it up from the Win folder, a dos-window appears and it dies. A few lines appear too quickly to read. If I execute it from the command prompt, it works fine. Still the mystery to me is why I don't need to add exe in the cmd prompt to execute it. Further, how did it know to look in the dist folder? I checked with IDLE's path browser, and don't see it there. I'm not yet on board with the browser, but it looks like a starting point for finding py files I've run under IDLE. I looked for your post that had details, and I don't see it. I know you did post it. I had some trouble a few days ago trying to reply to one of your posts. It's not in my trash. Strange. The two directories are discussed just above section 4, right at the end of the a long output list. I missed that, since I thought the paragraph described the list, which I wasn't really interested in at the time. I would think that all the extras in dist are useful to other compiles of programs in my py folder? I have a comment about the tutorial. The command line shown a few lines into section 3. does not need python in the line in my case. setup.py py2exe works. I've glanced at section 5 and understand the basics. I'll be back to it later as needed. I didn't notice your reply in the queue this morning, and posted a msg about the disappearing file thinking there was a disconnect on the posts I had trouble with as above. I'll fix that post shortly. On 2/19/2010 5:34 AM, Robert Berman wrote: > Wayne, > > Somewhere in the tutorial should be a comment about py2exe creating two > additional directories: build and dist. Forget about the build directory. If > you look in the dist directory you will find the exe file and all supporting > files. If you look back to an earlier email you will see a more detailed > explanation I sent you. > > Robert Berman > > > > >> -----Original Message----- >> From: Wayne Watson [mailto:sierra_mtnview at sbcglobal.net] >> Sent: Thursday, February 18, 2010 11:10 PM >> To: Robert Berman >> Cc: tutor at python.org >> Subject: Re: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], >> Py2.5 >> >> There's a bit of an anomaly. I've compiled 3 small programs now, and >> in >> cmd prompt a Dir does not find the file. It finds the py file, but >> not >> the completed file. Nevertheless, if I type in the prefix, the >> desired >> program executes. >> >> On 2/18/2010 4:48 PM, Wayne Watson wrote: >> >>> Got it. Fooled myself. I'm converting to Win7 and have my XP >>> >> keyboard >> >>> and monitor side by side with the same for XP. I did the world >>> >> program >> >>> in XP and py2exe module in W7!! >>> >>> world compiled and ran successfully. Now for a bigger program with >>> matplotlib and tkinter. Maybe I'll just settle for a small >>> >> matplotlib >> >>> program for the moment. VBG >>> >>> Thanks very much. >>> >>> >> -- >> "There is nothing so annoying as to have two people >> talking when you're busy interrupting." -- Mark Twain >> > > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Fri Feb 19 16:41:58 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 19 Feb 2010 07:41:58 -0800 Subject: [Tutor] The Disappearing Program (py2exe) In-Reply-To: <4B7EA784.5040608@sbcglobal.net> References: <4B7EA784.5040608@sbcglobal.net> Message-ID: <4B7EB146.9000305@sbcglobal.net> The answer now appears in "Wrestling with ...". It's in a dist folder that py2exe produces. See Robert Berman post today, 2/19 early in morning. 5:34 am here. On 2/19/2010 7:00 AM, Wayne Watson wrote: > I've successfully compiled several small python programs on Win XP > into executables using py2exe. A program goes from a name like > snowball.py to snowball. A dir in the command prompt window finds > snowball.py but not snowball. If I type in snowball, it executes. > What's up with that? > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From steve at pearwood.info Fri Feb 19 17:04:31 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 20 Feb 2010 03:04:31 +1100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: <4B7E871F.10702@smash-net.org> References: <4B7E871F.10702@smash-net.org> Message-ID: <201002200304.31749.steve@pearwood.info> On Fri, 19 Feb 2010 11:42:07 pm Norman Rie? wrote: > Hello, > > i am trying to read a large bz2 file with this code: > > source_file = bz2.BZ2File(file, "r") > for line in source_file: > print line.strip() > > But after 4311 lines, it stoppes without a errormessage. The bz2 file > is much bigger though. > > How can i read the whole file line by line? "for line in file" works for me: >>> import bz2 >>> >>> writer = bz2.BZ2File('file.bz2', 'w') >>> for i in xrange(20000): ... # write some variable text to a line ... writer.write('abc'*(i % 5) + '\n') ... >>> writer.close() >>> reader = bz2.BZ2File('file.bz2', 'r') >>> i = 0 >>> for line in reader: ... i += 1 ... >>> reader.close() >>> i 20000 My guess is one of two things: (1) You are mistaken that the file is bigger than 4311 lines. (2) You are using Windows, and somehow there is a Ctrl-Z (0x26) character in the file, which Windows interprets as End Of File when reading files in text mode. Try changing the mode to "rb" and see if the behaviour goes away. -- Steven D'Aprano From stefan_ml at behnel.de Fri Feb 19 17:15:15 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 19 Feb 2010 17:15:15 +0100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: <4B7E871F.10702@smash-net.org> References: <4B7E871F.10702@smash-net.org> Message-ID: Norman Rie?, 19.02.2010 13:42: > i am trying to read a large bz2 file with this code: > > source_file = bz2.BZ2File(file, "r") > for line in source_file: > print line.strip() > > But after 4311 lines, it stoppes without a errormessage. What does "stops" mean here? Does it crash? Does it exit from the loop? Is the above code exactly what you used for testing? Are you passing a filename? What platform is this on? > The bz2 file is much bigger though. How many lines does it have? How did you count them? Did you make sure that you are reading from the right file? > How can i read the whole file line by line? Just as you do above, and it works for me. So the problem is likely elsewhere. Stefan From tmatsumoto at gmx.net Fri Feb 19 17:42:36 2010 From: tmatsumoto at gmx.net (C.T. Matsumoto) Date: Fri, 19 Feb 2010 17:42:36 +0100 Subject: [Tutor] Python and algorithms In-Reply-To: <20100219122524.460c3ac1@o> References: <4B7D0F86.1070703@gmail.com> <1c2a2c591002180405k7c054f3ev8c2e807f240a43e4@mail.gmail.com> <4B7D3DD8.7050908@gmail.com> <1c2a2c591002180611j92edaaaq6a7b44a932fcdd5a@mail.gmail.com> <20100219122524.460c3ac1@o> Message-ID: <4B7EBF7C.5050103@gmx.net> spir wrote: > On Thu, 18 Feb 2010 09:11:22 -0500 > Kent Johnson wrote: > > >> It's true that solving a problem often involves creating an algorithm >> in a broad sense. The formal study of algorithms studies specific >> techniques and algorithms that have proven to be useful to solve many >> hard problems. In my experience most programming problems do not >> require use of these formal algorithms, at least not explicitly. >> > > Hello, > > I would say that what is commonly called "algorithm" in computer science is a given class of possible algorithm that can (more easily) be formally expressed. Especially in mathematical terms. The reason why these are much more studied. > But algorithmics can also be more generally understood as the "art & technique" of software design. Then, every programming task involves algorithmics. This may also be called "modelizing", a term than imo sensibly suggests how similar it is to the job of scientists. > Modelizing is hard and hard to study because close to infinitely various and complex. Improving one's skills in this field is a whole life's yoga ;-) "I want to get a clearer mind"; "I want to become more lucid". An extremely big, difficult and rich book on the topic of thinking complexity is "la m?thode" by http://en.wikipedia.org/wiki/Edgar_Morin (I don't have references to the english version). > > Denis > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ > _______________________________________________ > Tutor maillist - > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks Denis, I'm realizing there is a problem with the definition of algorithm. Thanks for the link. T From bermanrl at cfl.rr.com Fri Feb 19 18:46:34 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Fri, 19 Feb 2010 12:46:34 -0500 Subject: [Tutor] The Disappearing Program (py2exe) In-Reply-To: <4B7EC618.30606@sbcglobal.net> References: <4B7EA784.5040608@sbcglobal.net> <000001cab175$56e41a80$04ac4f80$@rr.com> <4B7EC618.30606@sbcglobal.net> Message-ID: <001101cab18b$7a99c9f0$6fcd5dd0$@rr.com> Wayne, I am assuming you are using Win 7 and I'll answer with that unless you tell me you are using XP in which case I will walk over to my wife's desk and test what I am telling you on her XP driven machine. Assuming Windows 7. Looking at your directory you should be using Windows Explorer. Click on Organize then click on folder and search options. Then click on view. Make sure the check box that says 'hide extensions for known file types' is not clicked. Once that is done, all your file extensions (all of them) will be seen and shown. Robert > -----Original Message----- > From: Wayne Watson [mailto:sierra_mtnview at sbcglobal.net] > Sent: Friday, February 19, 2010 12:11 PM > To: Robert Berman > Subject: Re: [Tutor] The Disappearing Program (py2exe) > > I'm sure you are right. I'm not sure what you mean about view > params. > Properties? > > On 2/19/2010 7:08 AM, Robert Berman wrote: > > I think you will find that snowball is actually snowball.exe. You > might check > > the view parameters on how your extensions are being displayed. > > > > > >> -----Original Message----- > >> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- > >> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Wayne Watson > >> Sent: Friday, February 19, 2010 10:00 AM > >> To: tutor at python.org > >> Subject: [Tutor] The Disappearing Program (py2exe) > >> > >> I've successfully compiled several small python programs on Win > XP > >> into > >> executables using py2exe. A program goes from a name like > >> snowball.py to > >> snowball. A dir in the command prompt window finds snowball.py > but > >> not > >> snowball. If I type in snowball, it executes. What's up with > that? > >> > >> -- > >> "There is nothing so annoying as to have two people > >> talking when you're busy interrupting." -- Mark > Twain > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > -- > "There is nothing so annoying as to have two people > talking when you're busy interrupting." -- Mark Twain From norman at smash-net.org Fri Feb 19 19:48:34 2010 From: norman at smash-net.org (=?ISO-8859-1?Q?Norman_Rie=DF?=) Date: Fri, 19 Feb 2010 19:48:34 +0100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: <201002200304.31749.steve@pearwood.info> References: <4B7E871F.10702@smash-net.org> <201002200304.31749.steve@pearwood.info> Message-ID: <4B7EDD02.3020308@smash-net.org> Am 19.02.2010 17:04, schrieb Steven D'Aprano: > My guess is one of two things: > (1) You are mistaken that the file is bigger than 4311 lines. > > (2) You are using Windows, and somehow there is a Ctrl-Z (0x26) > character in the file, which Windows interprets as End Of File when > reading files in text mode. Try changing the mode to "rb" and see if > the behaviour goes away. > Am 19.02.2010 17:15, schrieb Stefan Behnel: > What does "stops" mean here? Does it crash? Does it exit from the loop? Is > the above code exactly what you used for testing? Are you passing a > filename? What platform is this on? > > > How many lines does it have? How did you count them? Did you make sure that > you are reading from the right file? > > Hello, i took the liberty and copied your mails together, so i do not have to repeat things. How big is the file and how did i count that: smash at loki ~/osm $ bzcat planet-100210.osm.bz2 | wc -l 1717362770 (this took a looong time ;-)) smash at loki ~/osm $ du -h planet-100210.osm.bz2 8,0G planet-100210.osm.bz2 So as you can see, the file really is bigger. I am not using Windows and the next character would be a period. smash at loki ~/osm/osmcut $ ./osmcut.py ../planet-100210.osm.bz2 [...] I did set the mode to "rb" with the same result. I also edited the code to see if the loop was exited or the program crashed. As you can see, there is no error, the loop just exits. This is the _exact_ code i use: source_file = bz2.BZ2File(osm_file, "r") for line in source_file: print line.strip() print "Exiting" print "I used file: " + osm_file As you can see above, the loop exits, the prints are executed and the right file is used. The content of the file is really distinctive, so there is no doubt, that it is the right file. Here is my platform information: Python 2.6.4 Linux 2.6.32.8 #1 SMP Fri Feb 12 13:29:10 CET 2010 x86_64 Intel(R) Core(TM)2 Duo CPU U9400 @ 1.40GHz GenuineIntel GNU/Linux Note: This symptome shows on another platform (SuSE 11.1) with different software versions as well. Is there a possibility, that the bz2 module reads only into a limited buffer and no further? If so, the same behaviour of the two independent systems would be explained and that it works in Stevens smaller example. How could i avoid that? Oh and the content of the file is free, so i do not get into legal issues exposing it. Thanks. Regards, Norman From jecarnell at saintfrancis.com Fri Feb 19 19:56:18 2010 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Fri, 19 Feb 2010 12:56:18 -0600 Subject: [Tutor] Is it possible for a Python Program to send commands to the Python Interpreter? Message-ID: I am trying to teach a computer program - to program. It builds grammars and procedural memories on dictionary networks. How do I get the program to be able to input to the interpreter/command line and read the results? I have done this a wee bit with making a dictionary of functions, but in a sense I am creating a script language on top of a script language so it seems really dumb to me especially since I have to recreate the grammar. I hope this doesn't get me flamed too much for asking... James -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Feb 19 20:33:04 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 Feb 2010 14:33:04 -0500 Subject: [Tutor] Is it possible for a Python Program to send commands to the Python Interpreter? In-Reply-To: References: Message-ID: <1c2a2c591002191133q37fb552o205787934c9958bb@mail.gmail.com> On Fri, Feb 19, 2010 at 1:56 PM, Carnell, James E wrote: > > I am trying to teach a computer program - to program. It builds grammars and > procedural memories on dictionary networks. How do I get the program to be > able to input to the interpreter/command line and read the results? I have > done this a wee bit with making a dictionary of functions, but in a sense I > am creating a script language on top of a script language so it seems really > dumb to me especially since I have to recreate the grammar. It sounds like you are looking for eval() (Standard warning - use eval() only on trusted data) Kent From alan.gauld at btinternet.com Fri Feb 19 20:37:41 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Feb 2010 19:37:41 -0000 Subject: [Tutor] Is it possible for a Python Program to send commands to thePython Interpreter? References: Message-ID: "Carnell, James E" wrote > I am trying to teach a computer program - to program. It builds grammars > and procedural memories on dictionary networks. How do I get the program > to be able to input to the interpreter/command line and read the > results? You probably don;t want to do that. I suspect you just want to execute a string that your program has created? If so you can use the exec or eval functions in Python. If you do want to create an interactive prompt for your users you might like to look at the cmd module which includes the tools for building a command prompt type environment similar to the pdb debugger. > I have done this a wee bit with making a dictionary of > functions, but in a sense I am creating a script language on top of a > script language so it seems really dumb to me especially since I have to > recreate the grammar. Not really sure I understand? Are you creating a new grammar or are you using Python syntax etc but just adding new features/commands? If the outputr is valid python syntax then you can use exec/eval but if you are creating your own dialect then you will need to buld a parser - using any of the excellent python parsing tools available? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Feb 19 20:44:35 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Feb 2010 19:44:35 -0000 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 References: <4B7CAEE8.7070303@sbcglobal.net> <000301cab0b6$f8df7150$ea9e53f0$@rr.com> <4B7DDBA4.5070104@sbcglobal.net><4B7DDFD8.7020808@sbcglobal.net> <4B7E0F28.6000704@sbcglobal.net><001101cab168$3954bbd0$abfe3370$@rr.com> <4B7EB081.6060906@sbcglobal.net> Message-ID: "Wayne Watson" wrote > pylab_scatter.exe. Interestingly, if I fire it up from the Win folder, a > dos-window appears and it dies. A few lines appear too quickly to read. > If I execute it from the command prompt, it works fine. Still the mystery > to me is why I don't need to add exe in the cmd prompt to execute it. DOS(*) automatically looks for executable file extensions (exe,com, bat etc) so you don't need to type them. You don't type cmd.exe to start a DOS shell do you? You only type cmd... I hope! (*)Actually the Windows command processor CMD.EXE > Further, how did it know to look in the dist folder? Thats more interesting! It presumably added dist to the PATH environment variable. Not the Python path the DOS one - after all the EXE is not a python program any more its an exe file running under DOS. > I have a comment about the tutorial. > The command line shown a few lines into section 3. does not need python > in the line in my case. setup.py py2exe works. That only works because you have the file asociation set to recognise .py files as associated with the interpreter. Using python explicitly removes that potential trip wire and so for a tutorial writer makes it a much safer option. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lie.1296 at gmail.com Fri Feb 19 21:42:28 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 20 Feb 2010 07:42:28 +1100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: <4B7E871F.10702@smash-net.org> References: <4B7E871F.10702@smash-net.org> Message-ID: On 02/19/10 23:42, Norman Rie? wrote: > Hello, > > i am trying to read a large bz2 file with this code: > > source_file = bz2.BZ2File(file, "r") > for line in source_file: > print line.strip() > > But after 4311 lines, it stoppes without a errormessage. The bz2 file is > much bigger though. > How can i read the whole file line by line? Is the bz2 file an archive[1]? [1] archive: contains more than one file From norman at smash-net.org Fri Feb 19 21:49:54 2010 From: norman at smash-net.org (=?ISO-8859-1?Q?Norman_Rie=DF?=) Date: Fri, 19 Feb 2010 21:49:54 +0100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: References: <4B7E871F.10702@smash-net.org> Message-ID: <4B7EF972.3040004@smash-net.org> Am 19.02.2010 21:42, schrieb Lie Ryan: > On 02/19/10 23:42, Norman Rie? wrote: > >> Hello, >> >> i am trying to read a large bz2 file with this code: >> >> source_file = bz2.BZ2File(file, "r") >> for line in source_file: >> print line.strip() >> >> But after 4311 lines, it stoppes without a errormessage. The bz2 file is >> much bigger though. >> How can i read the whole file line by line? >> > Is the bz2 file an archive[1]? > > [1] archive: contains more than one file > No it is a single file. But how could i check for sure? Its extracts to a single file... From kent37 at tds.net Fri Feb 19 22:03:43 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 Feb 2010 16:03:43 -0500 Subject: [Tutor] Reading large bz2 Files In-Reply-To: <4B7E871F.10702@smash-net.org> References: <4B7E871F.10702@smash-net.org> Message-ID: <1c2a2c591002191303raa3fc25n1a6acd7603d1b85a@mail.gmail.com> On Fri, Feb 19, 2010 at 7:42 AM, Norman Rie? wrote: > Hello, > > i am trying to read a large bz2 file with this code: > > source_file = bz2.BZ2File(file, "r") > for line in source_file: > ? ?print line.strip() > > But after 4311 lines, it stoppes without a errormessage. The bz2 file is > much bigger though. > How can i read the whole file line by line? I wonder if it is dying after reading 2^31 or 2^32 bytes? It sounds a bit like this (fixed) bug: http://bugs.python.org/issue1215928 Kent From lie.1296 at gmail.com Fri Feb 19 22:14:31 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 20 Feb 2010 08:14:31 +1100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: References: <4B7E871F.10702@smash-net.org> Message-ID: On 02/20/10 07:42, Lie Ryan wrote: > On 02/19/10 23:42, Norman Rie? wrote: >> Hello, >> >> i am trying to read a large bz2 file with this code: >> >> source_file = bz2.BZ2File(file, "r") >> for line in source_file: >> print line.strip() >> >> But after 4311 lines, it stoppes without a errormessage. The bz2 file is >> much bigger though. >> How can i read the whole file line by line? > > Is the bz2 file an archive[1]? > > [1] archive: contains more than one file Or more clearly, is the bz2 contains multiple file compressed using -c flag? The -c flag will do a simple concatenation of multiple compressed streams to stdout; it is only decompressible with bzip2 0.9.0 or later[1]. You cannot use bz2.BZ2File to open this, instead use the stream decompressor bz2.BZ2Decompressor. A better approach, is to use a real archiving format (e.g. tar). [1] http://www.bzip.org/1.0.3/html/description.html From lie.1296 at gmail.com Fri Feb 19 22:24:29 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 20 Feb 2010 08:24:29 +1100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: <4B7EF972.3040004@smash-net.org> References: <4B7E871F.10702@smash-net.org> <4B7EF972.3040004@smash-net.org> Message-ID: On 02/20/10 07:49, Norman Rie? wrote: > Am 19.02.2010 21:42, schrieb Lie Ryan: >> On 02/19/10 23:42, Norman Rie? wrote: >> >>> Hello, >>> >>> i am trying to read a large bz2 file with this code: >>> >>> source_file = bz2.BZ2File(file, "r") >>> for line in source_file: >>> print line.strip() >>> >>> But after 4311 lines, it stoppes without a errormessage. The bz2 file is >>> much bigger though. >>> How can i read the whole file line by line? >>> >> Is the bz2 file an archive[1]? >> >> [1] archive: contains more than one file >> > > No it is a single file. But how could i check for sure? Its extracts to > a single file... use "bzip2 -dc" or "bunzip2" instead of "bzcat" since bzcat concatenates its output file to a single file. From sierra_mtnview at sbcglobal.net Fri Feb 19 22:30:47 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 19 Feb 2010 13:30:47 -0800 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 In-Reply-To: References: <4B7CAEE8.7070303@sbcglobal.net> <000301cab0b6$f8df7150$ea9e53f0$@rr.com> <4B7DDBA4.5070104@sbcglobal.net><4B7DDFD8.7020808@sbcglobal.net> <4B7E0F28.6000704@sbcglobal.net><001101cab168$3954bbd0$abfe3370$@rr.com> <4B7EB081.6060906@sbcglobal.net> Message-ID: <4B7F0307.5070000@sbcglobal.net> I suppose I'm in an interesting situation with regard to Win cmd prompt. I did this work on XP. There the facility is a bit more constraining than Win7 on my new PC. On XP, I do not have name completion w/o setting something. I only recently started with cmd prompt again. In Win7, it's automatic. There are other differences. An oddity, to me at least, name completion in W7 does not halt at the first difference. It goes all the way to completion at the first file that it can find, I think. I have to back up and try again. I think today will end my use of Python on XP. I have all files on Win7 now. I'll likely test py3exe there today to see how it behaves. What you say about the path change makes sense, but it's unfortunate the producers of py2exe haven't given some insight into this and the misc files produced in the dist folder. Of course, I have not Googled much at all on any of this. I'm glad I finally worked my way to this facility. It should help a good deal on the distribution of my demos to non-python friends, and fellow project workers at far flung places from here. On 2/19/2010 11:44 AM, Alan Gauld wrote: > "Wayne Watson" wrote >> pylab_scatter.exe. Interestingly, if I fire it up from the Win >> folder, a dos-window appears and it dies. A few lines appear too >> quickly to read. If I execute it from the command prompt, it works >> fine. Still the mystery to me is why I don't need to add exe in the >> cmd prompt to execute it. > > DOS(*) automatically looks for executable file extensions (exe,com, > bat etc) > so you don't need to type them. You don't type cmd.exe to start a DOS > shell do you? You only type cmd... I hope! > > (*)Actually the Windows command processor CMD.EXE > >> Further, how did it know to look in the dist folder? > > Thats more interesting! > It presumably added dist to the PATH environment variable. Not > the Python path the DOS one - after all the EXE is not a python > program any more its an exe file running under DOS. > >> I have a comment about the tutorial. >> The command line shown a few lines into section 3. does not need >> python in the line in my case. setup.py py2exe works. > > That only works because you have the file asociation set to > recognise .py files as associated with the interpreter. Using python > explicitly removes that potential trip wire and so for a tutorial writer > makes it a much safer option. > > HTH, > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From jecarnell at saintfrancis.com Fri Feb 19 22:34:57 2010 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Fri, 19 Feb 2010 15:34:57 -0600 Subject: [Tutor] Is it possible for a Python Program to send commands to the Python Interpreter? In-Reply-To: Message-ID: Thanks Kent and Alan!! Problem solved, eval() will work great! From norman at smash-net.org Fri Feb 19 22:44:07 2010 From: norman at smash-net.org (=?ISO-8859-1?Q?Norman_Rie=DF?=) Date: Fri, 19 Feb 2010 22:44:07 +0100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: <1c2a2c591002191303raa3fc25n1a6acd7603d1b85a@mail.gmail.com> References: <4B7E871F.10702@smash-net.org> <1c2a2c591002191303raa3fc25n1a6acd7603d1b85a@mail.gmail.com> Message-ID: <4B7F0627.1070408@smash-net.org> Am 19.02.2010 22:03, schrieb Kent Johnson: > On Fri, Feb 19, 2010 at 7:42 AM, Norman Rie? wrote: > >> Hello, >> >> i am trying to read a large bz2 file with this code: >> >> source_file = bz2.BZ2File(file, "r") >> for line in source_file: >> print line.strip() >> >> But after 4311 lines, it stoppes without a errormessage. The bz2 file is >> much bigger though. >> How can i read the whole file line by line? >> > I wonder if it is dying after reading 2^31 or 2^32 bytes? It sounds a > bit like this (fixed) bug: > http://bugs.python.org/issue1215928 > > Kent > > ./osmcut.py ../planet-100210.osm.bz2 > test.txt smash at loki ~/osm/osmcut $ ls -lh test.txt -rw-r--r-- 1 871K 19. Feb 22:41 test.txt Seems like far from it. Norman From sierra_mtnview at sbcglobal.net Fri Feb 19 22:44:16 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 19 Feb 2010 13:44:16 -0800 Subject: [Tutor] Wrestling with the Py2exe Install, Win7[XP!], Py2.5 In-Reply-To: <4B7F0307.5070000@sbcglobal.net> References: <4B7CAEE8.7070303@sbcglobal.net> <000301cab0b6$f8df7150$ea9e53f0$@rr.com> <4B7DDBA4.5070104@sbcglobal.net><4B7DDFD8.7020808@sbcglobal.net> <4B7E0F28.6000704@sbcglobal.net><001101cab168$3954bbd0$abfe3370$@rr.com> <4B7EB081.6060906@sbcglobal.net> <4B7F0307.5070000@sbcglobal.net> Message-ID: <4B7F0630.8000705@sbcglobal.net> Things were not quite what the seem. I just tried to run a program that was not converted, and left off py. It worked. So maybe the only way to execute the compiled code is to to to dist? -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Fri Feb 19 23:15:52 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 19 Feb 2010 14:15:52 -0800 Subject: [Tutor] The Disappearing Program (py2exe) In-Reply-To: <001101cab18b$7a99c9f0$6fcd5dd0$@rr.com> References: <4B7EA784.5040608@sbcglobal.net> <000001cab175$56e41a80$04ac4f80$@rr.com> <4B7EC618.30606@sbcglobal.net> <001101cab18b$7a99c9f0$6fcd5dd0$@rr.com> Message-ID: <4B7F0D98.70201@sbcglobal.net> XP. Win 7, I hope, by the end of the day. Stuff is working under Win 7 from my transfer of it from a week or so ago. The only thing I left on XP was the py2exe stuff. I'm writing this from my Win 7 machine. There's a big twist in this. I've verified that when I typed the name w/o py, it really executed it anyway. I did that with a py file that was never setup by py2exe. I then went to dist and fired up the compiled exe file and got a complaint matplotlib. It couldn't find its data files. Certainly the step in section 4, test your executable, has been of no use. Maybe I need to go to step 5? Perhaps I need the msvcr71.dll file. Forget that.It's in dist. Time to read more of 5. On 2/19/2010 9:46 AM, Robert Berman wrote: > Wayne, > > I am assuming you are using Win 7 and I'll answer with that unless you tell me > you are using XP in which case I will walk over to my wife's desk and test > what I am telling you on her XP driven machine. > > Assuming Windows 7. > > Looking at your directory you should be using Windows Explorer. Click on > Organize then click on folder and search options. Then click on view. Make > sure the check box that says 'hide extensions for known file types' is not > clicked. Once that is done, all your file extensions (all of them) will be > seen and shown. > > > Robert > > >> -----Original Message----- >> From: Wayne Watson [mailto:sierra_mtnview at sbcglobal.net] >> Sent: Friday, February 19, 2010 12:11 PM >> To: Robert Berman >> Subject: Re: [Tutor] The Disappearing Program (py2exe) >> >> I'm sure you are right. I'm not sure what you mean about view >> params. >> Properties? >> >> On 2/19/2010 7:08 AM, Robert Berman wrote: >> >>> I think you will find that snowball is actually snowball.exe. You >>> >> might check >> >>> the view parameters on how your extensions are being displayed. >>> >>> >>> >>>> -----Original Message----- >>>> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- >>>> bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Wayne Watson >>>> Sent: Friday, February 19, 2010 10:00 AM >>>> To: tutor at python.org >>>> Subject: [Tutor] The Disappearing Program (py2exe) >>>> >>>> I've successfully compiled several small python programs on Win >>>> >> XP >> >>>> into >>>> executables using py2exe. A program goes from a name like >>>> snowball.py to >>>> snowball. A dir in the command prompt window finds snowball.py >>>> >> but >> >>>> not >>>> snowball. If I type in snowball, it executes. What's up with >>>> >> that? >> >>>> -- >>>> "There is nothing so annoying as to have two people >>>> talking when you're busy interrupting." -- Mark >>>> >> Twain >> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >>> >> -- >> "There is nothing so annoying as to have two people >> talking when you're busy interrupting." -- Mark Twain >> > > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From norman at smash-net.org Sat Feb 20 00:04:50 2010 From: norman at smash-net.org (=?ISO-8859-1?Q?Norman_Rie=DF?=) Date: Sat, 20 Feb 2010 00:04:50 +0100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: References: <4B7E871F.10702@smash-net.org> <4B7EF972.3040004@smash-net.org> Message-ID: <4B7F1912.9060707@smash-net.org> Am 19.02.2010 22:24, schrieb Lie Ryan: > On 02/20/10 07:49, Norman Rie? wrote: > >> Am 19.02.2010 21:42, schrieb Lie Ryan: >> >>> On 02/19/10 23:42, Norman Rie? wrote: >>> >>> >>>> Hello, >>>> >>>> i am trying to read a large bz2 file with this code: >>>> >>>> source_file = bz2.BZ2File(file, "r") >>>> for line in source_file: >>>> print line.strip() >>>> >>>> But after 4311 lines, it stoppes without a errormessage. The bz2 file is >>>> much bigger though. >>>> How can i read the whole file line by line? >>>> >>>> >>> Is the bz2 file an archive[1]? >>> >>> [1] archive: contains more than one file >>> >>> >> No it is a single file. But how could i check for sure? Its extracts to >> a single file... >> > use "bzip2 -dc" or "bunzip2" instead of "bzcat" since bzcat concatenates > its output file to a single file. > > > Yes, it is a single file. From steve at pearwood.info Sat Feb 20 01:07:26 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 20 Feb 2010 11:07:26 +1100 Subject: [Tutor] Is it possible for a Python Program to send commands to the Python Interpreter? In-Reply-To: <1c2a2c591002191133q37fb552o205787934c9958bb@mail.gmail.com> References: <1c2a2c591002191133q37fb552o205787934c9958bb@mail.gmail.com> Message-ID: <201002201107.27606.steve@pearwood.info> On Sat, 20 Feb 2010 06:33:04 am Kent Johnson wrote: > It sounds like you are looking for eval() > > (Standard warning - use eval() only on trusted data) This is the tutor list, aimed at beginners to Python, many of whom are also beginners to programming as well. Even experienced programmers often get security very, very, very badly wrong. Do you think that a glib eight-word one-line "standard warning" really is sufficient? James, if you are still reading, I should expand on Kent's warning. The eval function, like exec, can be very dangerous in the wrong hands. There is a whole class of very, very common security bugs caused by functions like eval: http://en.wikipedia.org/wiki/Code_injection The way the bug works is that the programmer writes a function that takes some data, and directly or indirectly applies eval to it: >>> def mylist(string): ... # Convert a string to a list. ... string = string.strip() ... if string.startswith('[') and string.endswith(']'): ... return eval(string) ... else: ... raise ValueError('not a list') ... >>> mylist(" [1, 2, 3] ") [1, 2, 3] This seems pretty innocuous, but it contains a deadly land-mine. This function then gets used in an application that uses strings produced by untrusted users. Say, it ends up in a web application, and the user types text into a field and the application ends up calling mylist on the contents of that field. Then, some malicious user types this into the input form: "[] or __import__('os').system('echo YOUR SYSTEM IS MINE') or [1,2,3]" (only imagine something much worse than an echo command) and your web application does this: >>> s = "[] or __import__('os').system('echo YOUR SYSTEM IS MINE') or [1,2,3]" >>> mylist(s) YOUR SYSTEM IS MINE [1, 2, 3] You have just had your web server compromised by a code injection bug. (A web application is only one example of how you can get untrusted data into your app. It is the biggest risk though.) Now, you might think that you can work around this by clever programming. Well, maybe, but sanitising strings so they are safe is a VERY difficult job. And naturally if you aren't aware they need to be sanitised, you won't do it. My advice to anyone thinking they need to use eval or exec is: (1) Don't do it. (2) If you think you need to use them, you probably don't. (3) If you really, really need to use them, then use the most restrictive environment possible. Instead of eval(s), use: eval(s, {'__builtins__': None}, {}) which gives you some protection against naive attackers. The really clever ones will still break it. (4) Sanitise your data. Don't use Javascript to sanitise it at the browser, because the Bad Guys know how to bypass your Javascript checks. If you're expecting (say) a list of integers, then there is no reason for the list to contain *any* alphabetic characters or underscores, and if there are any, reject the string and report an error: def sanitise(string): safe = "1234567890[], \n\t" for c in string: if c not in safe: raise ValueError('unsafe string') If your needs are more complicated, then sanitising the string becomes exponentially more difficult. It will probably be less work to write your own safe parser than to sanitise the input. Have I scared you about using eval? If so, good. Don't let eval or exec anywhere near data provided by untrusted users, and don't confuse authentication with trust. -- Steven D'Aprano From alan.gauld at btinternet.com Sat Feb 20 02:09:19 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 20 Feb 2010 01:09:19 +0000 (GMT) Subject: [Tutor] Is it possible for a Python Program to send commands to the Python Interpreter? In-Reply-To: References: Message-ID: <531059.2536.qm@web86705.mail.ird.yahoo.com> Looks like the eval() will work great. Thanks so much for telling me. > >We normally warn against using eval/exec because they form a security risk. But in your case you are in control of the code that they execute so its ok. That is the kind of usage where they are the best solution. Be very wary of cases where you read stored code from a file and execute it however. Its opssible a malicious user could add/change the code to do something bad. But provided you create the executing code yourself you should be fine. Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 20 03:23:46 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 19 Feb 2010 21:23:46 -0500 Subject: [Tutor] Is it possible for a Python Program to send commands to the Python Interpreter? In-Reply-To: <201002201107.27606.steve@pearwood.info> References: <1c2a2c591002191133q37fb552o205787934c9958bb@mail.gmail.com> <201002201107.27606.steve@pearwood.info> Message-ID: <1c2a2c591002191823o7ef9d7bfl1d1a5f616fb58418@mail.gmail.com> On Fri, Feb 19, 2010 at 7:07 PM, Steven D'Aprano wrote: > On Sat, 20 Feb 2010 06:33:04 am Kent Johnson wrote: > >> It sounds like you are looking for eval() >> >> (Standard warning - use eval() only on trusted data) > > > This is the tutor list, aimed at beginners to Python, many of whom are > also beginners to programming as well. Even experienced programmers > often get security very, very, very badly wrong. Do you think that a > glib eight-word one-line "standard warning" really is sufficient? No, but it is all I had time for, I figured James would ask for clarification or someone else would chime in :-) Kent From sierra_mtnview at sbcglobal.net Sat Feb 20 04:03:32 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 19 Feb 2010 19:03:32 -0800 Subject: [Tutor] The Disappearing Program (py2exe) In-Reply-To: <4B7F0D98.70201@sbcglobal.net> References: <4B7EA784.5040608@sbcglobal.net> <000001cab175$56e41a80$04ac4f80$@rr.com> <4B7EC618.30606@sbcglobal.net> <001101cab18b$7a99c9f0$6fcd5dd0$@rr.com> <4B7F0D98.70201@sbcglobal.net> Message-ID: <4B7F5104.1020802@sbcglobal.net> An HTML attachment was scrubbed... URL: From shurui91 at gmail.com Sat Feb 20 08:07:19 2010 From: shurui91 at gmail.com (Shurui Liu (Aaron Liu)) Date: Sat, 20 Feb 2010 02:07:19 -0500 Subject: [Tutor] ask Message-ID: <2b9003cf1002192307j3399e6cx792424f89d8a61fb@mail.gmail.com> How to describe a math formula: sphere=(4/3)*PI*R**3? -- Shurui Liu (Aaron Liu) Computer Science & Engineering Technology University of Toledo -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sat Feb 20 08:48:06 2010 From: andreengels at gmail.com (Andre Engels) Date: Sat, 20 Feb 2010 08:48:06 +0100 Subject: [Tutor] ask In-Reply-To: <2b9003cf1002192307j3399e6cx792424f89d8a61fb@mail.gmail.com> References: <2b9003cf1002192307j3399e6cx792424f89d8a61fb@mail.gmail.com> Message-ID: <6faf39c91002192348n4e5b3f8fh8f01e1d0e522dc7a@mail.gmail.com> On Sat, Feb 20, 2010 at 8:07 AM, Shurui Liu (Aaron Liu) wrote: > How to describe a math formula: sphere=(4/3)*PI*R**3? A function seems like the logical thing to do: import math def spherical_volume(radius): return (4.0/3)*math.pi*radius**3 -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Sat Feb 20 10:36:42 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Feb 2010 09:36:42 -0000 Subject: [Tutor] The Disappearing Program (py2exe) References: <4B7EA784.5040608@sbcglobal.net> <000001cab175$56e41a80$04ac4f80$@rr.com> <4B7EC618.30606@sbcglobal.net> <001101cab18b$7a99c9f0$6fcd5dd0$@rr.com><4B7F0D98.70201@sbcglobal.net> <4B7F5104.1020802@sbcglobal.net> Message-ID: "Wayne Watson" wrote > File "matplotlib\__init__.pyc", line 478, in _get_data_path > RuntimeError: Could not find the matplotlib data files > <-------------------What is this? > > C:\Users\Wayne\Sandia_Meteors\Sentinel_Development\Learn_Python\Py2exe_Test\dist> > ================================== > I Googled this py2exe message RuntimeError: Could not find the > matplotlib data files. > As of yet, it does not look like a solution ia available for matplotlib. Have you tried asking on the matplotlib groups? I notice on gmane that there are four matplotlib groups listed. One of them might be able to help? Alan G. From alan.gauld at btinternet.com Sat Feb 20 10:41:11 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Feb 2010 09:41:11 -0000 Subject: [Tutor] ask References: <2b9003cf1002192307j3399e6cx792424f89d8a61fb@mail.gmail.com> Message-ID: "Shurui Liu (Aaron Liu)" wrote > How to describe a math formula: sphere=(4/3)*PI*R**3? I'm not sure what you are asking? > Shurui Liu (Aaron Liu) > Computer Science & Engineering Technology > University of Toledo I assume from this that you have a basic knowledge of math so you understand about expressions and arithmetic operations etc? Are you asking how to express that in Python? Have you tried just entering it as written? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Sat Feb 20 12:21:10 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 20 Feb 2010 03:21:10 -0800 Subject: [Tutor] The Disappearing Program (py2exe) In-Reply-To: References: <4B7EA784.5040608@sbcglobal.net> <000001cab175$56e41a80$04ac4f80$@rr.com> <4B7EC618.30606@sbcglobal.net> <001101cab18b$7a99c9f0$6fcd5dd0$@rr.com><4B7F0D98.70201@sbcglobal.net> <4B7F5104.1020802@sbcglobal.net> Message-ID: <4B7FC5A6.60004@sbcglobal.net> Yes, I sent a message there last night. No responses yet. Strangely I don't see it posted yet. That was six hours ago. Well, I finish off my night's sleep in about 4 hours maybe it will have made it.py2exe seems a little less traveled subject than most. On 2/20/2010 1:36 AM, Alan Gauld wrote: > > "Wayne Watson" wrote > >> File "matplotlib\__init__.pyc", line 478, in _get_data_path >> RuntimeError: Could not find the matplotlib data files >> <-------------------What is this? >> >> C:\Users\Wayne\Sandia_Meteors\Sentinel_Development\Learn_Python\Py2exe_Test\dist> >> >> ================================== >> I Googled this py2exe message RuntimeError: Could not find the >> matplotlib data files. >> As of yet, it does not look like a solution ia available for matplotlib. > > Have you tried asking on the matplotlib groups? I notice on > gmane that there are four matplotlib groups listed. One of them > might be able to help? > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From yoh at pymvpa.org Sat Feb 20 03:48:40 2010 From: yoh at pymvpa.org (Yaroslav Halchenko) Date: Fri, 19 Feb 2010 21:48:40 -0500 Subject: [Tutor] pyMVPA and OSError In-Reply-To: <790bcb671002180823p610e19d7rb25920bd84f478f1@mail.gmail.com> Message-ID: <20100220024840.GA10782@onerussian.com> Hi Juli, why not to ask at our mailing list? ;) http://lists.alioth.debian.org/mailman/listinfo/pkg-exppsy-pymvpa usually we don't bite too hard ;) so, in your case, would you get similar crash when you simply import pylab ? try to upgrade your pylab installation, or otherwise disable it for now within PyMPVA so it doesn't even try to import it when you want to import a complete suite: echo -e '[externals]\nhave pylab = no\n' > ~/.pymvpa.cfg P.S. note for myself -- may be we should catch not only ImportError while checking external dependencies. -- .-. =------------------------------ /v\ ----------------------------= Keep in touch // \\ (yoh@|www.)onerussian.com Yaroslav Halchenko /( )\ ICQ#: 60653192 Linux User ^^-^^ [175555] From paul.whittaker20 at ntlworld.com Sat Feb 20 11:52:43 2010 From: paul.whittaker20 at ntlworld.com (Paul Whittaker) Date: Sat, 20 Feb 2010 10:52:43 -0000 Subject: [Tutor] Python 3.0 Message-ID: <005401cab21a$d7ced270$876c7750$@whittaker20@ntlworld.com> Using the following script, the (Windows 7) PC echoes the key presses but doesn't quit (ever!) import msvcrt print('Press SPACE to stop...') while True: k = msvcrt.getch() # Strangely, this echoes to the IDLE window if k == ' ': # Not recognized break -------------- next part -------------- An HTML attachment was scrubbed... URL: From computing.account at googlemail.com Sat Feb 20 13:43:14 2010 From: computing.account at googlemail.com (AG) Date: Sat, 20 Feb 2010 12:43:14 +0000 Subject: [Tutor] List append method: St Petersburg Game Message-ID: <4B7FD8E2.2070107@gmail.com> Hi Pythonistas I am having difficulty with applying the list.append(x) method to produce a list that will contain outputs which will become coordinates for a later call to Matplotlib. Perhaps someone here can help me figure this out? The basic program is below: # St Petersburg Game: v. 2: # Toss a coin. If it is heads, win $2, if not keep # tossing it until it falls heads. # Heads first toss = H = $2 # Heads third toss = TTH = $8 # Heads fifth toss = TTTTH = $32 # The game is to win more by not scoring Heads print """St Petersburg Game: win multiples of $2 the more you land Tails""" # Required libraries import random import matplotlib.pyplot as plt #Main function: def flipCoin(): coinToss = random.randrange(1, 3) return coinToss # Storage of output toss_list = [] # Get things going flipCoin() # Want to capture the coin lands heads (2) while flipCoin() != 2: toss_list.append("Tails") flipCoin() # Heads lands & show output print print "Heads" print toss_list # Interpret results & 'reward' print "You flipped %d tails before landing Heads" % len(toss_list) if toss_list == 0: print "You won $2" else: toss_list.append( "Tail" ) print "You won $%d" % 2 ** len(toss_list) The overall purpose of the game is, for this discussion, irrelevant, but some background info will be helpful I think. The above program will give one run only and produces the output I expect. When I take this to the next level of complexity I run into problems. 1. I have tried to make this program run a given number of times, and use the for repetition loop to do this, basically: for i in range( 0, 10 ): and then the above program is appropriately indented. 2. Collecting the number of coin "tosses" into a list appends these to a list just fine. However, what this does is adds the numbers together so that one ends up like this: [0, 1, 2, 4, 5, 6, 8, 10, 11, 15] With a corresponding increase in the values derived from multiplying the exponent, thus: [2, 4, 8, 32, 64, 128, 512, 2048, 4096, 65536] Both are correct applications of the method, but I am unable to get the list to not sum the values up in the first list, these are not accumulative values, but discrete. If I am understanding what is currently happening, the values are being accumulated, and I want to stop that from happening. If this isn't clear, please let me know how I can clarify my question to help shape the relevance of the responses. Thanks for any ideas. AG From bgailer at gmail.com Sat Feb 20 14:56:30 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 20 Feb 2010 08:56:30 -0500 Subject: [Tutor] Python 3.0 In-Reply-To: <005401cab21a$d7ced270$876c7750$@whittaker20@ntlworld.com> References: <005401cab21a$d7ced270$876c7750$@whittaker20@ntlworld.com> Message-ID: <4B7FEA0E.6000805@gmail.com> On 2/20/2010 5:52 AM, Paul Whittaker wrote: > > Using the following script, the (Windows 7) PC echoes the key presses > but doesn't quit (ever!) > > import msvcrt > > print('Press SPACE to stop...') > > while True: > > k = msvcrt.getch() # Strangely, this echoes to the IDLE window > > if k == ' ': # Not recognized > > break > According to the docs: "msvcrt.getch() - Read a keypress and return the resulting character....This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function." IOW - getch always returns 1 character. You are testing for a 0 length string. Will never happen. What keystroke do you want to break the loop? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Feb 20 15:49:43 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 20 Feb 2010 09:49:43 -0500 Subject: [Tutor] List append method: St Petersburg Game In-Reply-To: <4B7FD8E2.2070107@gmail.com> References: <4B7FD8E2.2070107@gmail.com> Message-ID: <4B7FF687.7000002@gmail.com> On 2/20/2010 7:43 AM, AG wrote: > Hi Pythonistas > > I am having difficulty with applying the list.append(x) method to > produce a list that will contain outputs which will become coordinates > for a later call to Matplotlib. Perhaps someone here can help me > figure this out? Please let me know how I can clarify my question 1 - You are giving way too much information. We do not need to know the rules of the game or all the code. Our time to read email is limited. The less you tell us that is not relevant the better. Also you don't show the code for the "next level of complexity". What you should show us is: > for i in range( 0, 10 ): some lists are initialized and appended to. What are they and how are they appended? > > #Main function: > def flipCoin(): > coinToss = random.randrange(1, 3) > return coinToss > > # Storage of output > toss_list = [] > > # Get things going > flipCoin() > > # Want to capture the coin lands heads (2) > while flipCoin() != 2: > toss_list.append("Tails") > flipCoin() 2 - The most obvious problem is here: flipCoin() while flipCoin() != 2: toss_list.append("Tails") flipCoin() The result of the first call to flipCoin is ignored. Each cycle of the loop results in 2 calls to flipCoin. The result of the 2nd call is ignored. > The overall purpose of the game is, for this discussion, irrelevant, > but some background info will be helpful I think. The above program > will give one run only and produces the output I expect. Then your expectation is misguided, given my comments regarding multiple calls to flipCoin! You don't actually know how many tosses were made! [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC From computing.account at googlemail.com Sat Feb 20 16:09:26 2010 From: computing.account at googlemail.com (AG) Date: Sat, 20 Feb 2010 15:09:26 +0000 Subject: [Tutor] List append method: St Petersburg Game In-Reply-To: <4B7FF687.7000002@gmail.com> References: <4B7FD8E2.2070107@gmail.com> <4B7FF687.7000002@gmail.com> Message-ID: <4B7FFB26.8050309@gmail.com> bob gailer wrote: > On 2/20/2010 7:43 AM, AG wrote: >> > > > Please let me know how I can clarify my question > > 1 - You are giving way too much information. We do not need to know > the rules of the game or all the code. Our time to read email is > limited. The less you tell us that is not relevant the better. Thanks Bob. > Also you don't show the code for the "next level of complexity". Here it is, then: import random import matplotlib.pyplot as plt import math def flipCoin(): coinToss = random.randrange(1, 3) return coinToss toss_list = [] tosscounts = [] winnings = [] for i in range(0, 10): while flipCoin() != 2: toss_list.append("Tails") flipCoin() print print "Heads" tosscounts.append( len(toss_list)) if toss_list == 0: print "You won $2" winnings += 2 else: toss_list.append( "Tail" ) winnings += [2 ** len( toss_list )] print print tosscounts print winnings print "Here's the graph: " for i in winnings: # Convert int to float for log i * 1.0 plt.plot( [tosscounts], [winnings] ) plt.ylabel( "how often" ) plt.xlabel( "how much" ) plt.show() > > The result of the first call to flipCoin is ignored. > Each cycle of the loop results in 2 calls to flipCoin. The result of > the 2nd call is ignored. > Aha! Thanks for spotting that. Now fixed in the code cited above, but still gives the same problem. Thanks for any further ideas. AG From xchimeras at gmail.com Sat Feb 20 16:15:07 2010 From: xchimeras at gmail.com (Tom Green) Date: Sat, 20 Feb 2010 10:15:07 -0500 Subject: [Tutor] Network Socket question Message-ID: Hello group, First, I love this forum as I find it to be a wealth of info on Python and programming in general. I have a general question about sockets, which is what I primarily use Python for. My environment is Windows and I am using Python 2.5. My sockets are working great but now I am running into a client that sends multiple sends and I have no EOF (end of file) marker. I have read up on Twistted and threads and was wondering if someone could share a Windows method for working with a non-blocking socket. I believe I have to use POLL or select to check for data. Right now my socket hangs on RECV. Sorry if I am not explaining this correctly. Maybe someone can share with me some papers on writing Windows sockets. Thank you, Tom Green. From sierra_mtnview at sbcglobal.net Sat Feb 20 16:18:26 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 20 Feb 2010 07:18:26 -0800 Subject: [Tutor] The Disappearing Program (py2exe) In-Reply-To: <4B7FC5A6.60004@sbcglobal.net> References: <4B7EA784.5040608@sbcglobal.net> <000001cab175$56e41a80$04ac4f80$@rr.com> <4B7EC618.30606@sbcglobal.net> <001101cab18b$7a99c9f0$6fcd5dd0$@rr.com><4B7F0D98.70201@sbcglobal.net> <4B7F5104.1020802@sbcglobal.net> <4B7FC5A6.60004@sbcglobal.net> Message-ID: <4B7FFD42.4060501@sbcglobal.net> This apparently not quite as easy as the py2exe suggests when MPL is involved. See . It looks like I have some reading and work to do. On 2/20/2010 3:21 AM, Wayne Watson wrote: > Yes, I sent a message there last night. No responses yet. Strangely I > don't see it posted yet. That was six hours ago. Well, I finish off > my night's sleep in about 4 hours maybe it will have made it.py2exe > seems a little less traveled subject than most. > > On 2/20/2010 1:36 AM, Alan Gauld wrote: >> >> "Wayne Watson" wrote >> >>> File "matplotlib\__init__.pyc", line 478, in _get_data_path >>> RuntimeError: Could not find the matplotlib data files >>> <-------------------What is this? >>> >>> C:\Users\Wayne\Sandia_Meteors\Sentinel_Development\Learn_Python\Py2exe_Test\dist> >>> >>> ================================== >>> I Googled this py2exe message RuntimeError: Could not find the >>> matplotlib data files. >>> As of yet, it does not look like a solution ia available for >>> matplotlib. >> >> Have you tried asking on the matplotlib groups? I notice on >> gmane that there are four matplotlib groups listed. One of them >> might be able to help? >> >> Alan G. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Sat Feb 20 16:26:47 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 20 Feb 2010 07:26:47 -0800 Subject: [Tutor] The Disappearing Program (py2exe) In-Reply-To: <4B7FC5A6.60004@sbcglobal.net> References: <4B7EA784.5040608@sbcglobal.net> <000001cab175$56e41a80$04ac4f80$@rr.com> <4B7EC618.30606@sbcglobal.net> <001101cab18b$7a99c9f0$6fcd5dd0$@rr.com><4B7F0D98.70201@sbcglobal.net> <4B7F5104.1020802@sbcglobal.net> <4B7FC5A6.60004@sbcglobal.net> Message-ID: <4B7FFF37.8090701@sbcglobal.net> (This might be slightly readable. Missed two words.) This apparently is not quite as easy as the py2exe tutorial suggests when MPL is involved. See . It looks like I have some reading and work to do. The link came from my post to the MPL list. I hadn't noticed it last night, since it got stuck in my server as spam. On 2/20/2010 3:21 AM, Wayne Watson wrote: > Yes, I sent a message there last night. No responses yet. Strangely I > don't see it posted yet. That was six hours ago. Well, I finish off > my night's sleep in about 4 hours maybe it will have made it.py2exe > seems a little less traveled subject than most. > > On 2/20/2010 1:36 AM, Alan Gauld wrote: >> >> "Wayne Watson" wrote >> >>> File "matplotlib\__init__.pyc", line 478, in _get_data_path >>> RuntimeError: Could not find the matplotlib data files >>> <-------------------What is this? >>> >>> C:\Users\Wayne\Sandia_Meteors\Sentinel_Development\Learn_Python\Py2exe_Test\dist> >>> >>> ================================== >>> I Googled this py2exe message RuntimeError: Could not find the >>> matplotlib data files. >>> As of yet, it does not look like a solution ia available for >>> matplotlib. >> >> Have you tried asking on the matplotlib groups? I notice on >> gmane that there are four matplotlib groups listed. One of them >> might be able to help? >> >> Alan G. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From alan.gauld at btinternet.com Sat Feb 20 16:51:37 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Feb 2010 15:51:37 -0000 Subject: [Tutor] Python 3.0 References: <29569.9380258613$1266668585@news.gmane.org> Message-ID: "Paul Whittaker" wrote > Using the following script, the (Windows 7) PC echoes the key presses but > doesn't quit (ever!) > > import msvcrt > print('Press SPACE to stop...') > while True: > k = msvcrt.getch() # Strangely, this echoes to the IDLE window You will need to run it in an OS command window not in IDLE. Idle does its own keystoke capturing since its a GUI. I'll need to add a note to my tutor page to emphasise that since its probably not intuitively obvious! :-) Alan G. From alan.gauld at btinternet.com Sat Feb 20 16:57:55 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Feb 2010 15:57:55 -0000 Subject: [Tutor] Python 3.0 References: <005401cab21a$d7ced270$876c7750$@whittaker20@ntlworld.com> <4B7FEA0E.6000805@gmail.com> Message-ID: "bob gailer" wrote >> k = msvcrt.getch() # Strangely, this echoes to the IDLE window >> if k == ' ': # Not recognized > IOW - getch always returns 1 character. > > You are testing for a 0 length string. Will never happen. No, he is testing for a space character. But he is running it in IDLE and msvcrt only works n the OS command window world. I've updated my tutorial page to point that out. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Sat Feb 20 18:07:05 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 20 Feb 2010 11:07:05 -0600 Subject: [Tutor] pyMVPA and OSError In-Reply-To: <790bcb671002180823p610e19d7rb25920bd84f478f1@mail.gmail.com> References: <790bcb671002180823p610e19d7rb25920bd84f478f1@mail.gmail.com> Message-ID: On Thu, Feb 18, 2010 at 10:23 AM, Juli wrote: > Dear All, > > I am very much new to python, therefore I am likely to feel stupid > about asking this. I need pyMPVA module to play around with some fMRI > data. I have installed Python2.6 on Mac OS X Leopard. When I input >>> > import mvpa i get a deprecation warning, which is not a problem, > however when I try the following: >>> >>> import mvpa.suite as mvpa i > do not get a deprecating warning however I get a number of errors that > are as follows: > >>> import mvpa.suite as mvpa > In addition to what Yaroslav mentioned, I may also suggest that it's probably not a great idea to import a sub-package as the base package's name. You may have problems later if you want to import from mvpa. I.E. it would be better to say import mvpa.suite as suite or from mvpa import suite Also I think you are supposed to use the syntax from mvpa import suite as foobar not import mvpa.suite as foobar but I'm not sure. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aharrisreid at googlemail.com Sat Feb 20 18:50:49 2010 From: aharrisreid at googlemail.com (Alan Harris-Reid) Date: Sat, 20 Feb 2010 17:50:49 +0000 Subject: [Tutor] Superclass call problem Message-ID: <4B8020F9.2050307@googlemail.com> Hi, I am having trouble understanding how superclass calls work. Here's some code... class ParentClass(): def __init__(self): do something here class ChildClass(ParentClass): def __init__(self): super().__init__(self) # call parentclass __init__ method do something else here When the super().__init__ line runs I get the error "__init__() takes exactly 1 positional argument (2 given)" Can anyone tell me where I have gone wrong? I thought the self parameter should be passed to all class methods. TIA Alan Harris-Reid From afith13 at gmail.com Sat Feb 20 17:22:19 2010 From: afith13 at gmail.com (Andrew Fithian) Date: Sat, 20 Feb 2010 08:22:19 -0800 Subject: [Tutor] fast sampling with replacement Message-ID: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> Hi tutor, I'm have a statistical bootstrapping script that is bottlenecking on a python function sample_with_replacement(). I wrote this function myself because I couldn't find a similar function in python's random library. This is the fastest version of the function I could come up with (I used cProfile.run() to time every version I wrote) but it's not fast enough, can you help me speed it up even more? import random def sample_with_replacement(list): l = len(list) # the sample needs to be as long as list r = xrange(l) _random = random.random return [list[int(_random()*l)] for i in r] # using list[int(_random()*l)] is faster than random.choice(list) FWIW, my bootstrapping script is spending roughly half of the run time in sample_with_replacement() much more than any other function or method. Thanks in advance for any advice you can give me. -Drew -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sat Feb 20 19:53:06 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 20 Feb 2010 12:53:06 -0600 Subject: [Tutor] Superclass call problem In-Reply-To: <4B8020F9.2050307@googlemail.com> References: <4B8020F9.2050307@googlemail.com> Message-ID: Your call to super is wrong. It should be super and you pass the class and instance, then call init. On 2/20/10, Alan Harris-Reid wrote: > Hi, > > I am having trouble understanding how superclass calls work. Here's > some code... > > class ParentClass(): > def __init__(self): > do something here > > class ChildClass(ParentClass): > def __init__(self): > super().__init__(self) # call parentclass > __init__ method > do something else here > > > When the super().__init__ line runs I get the error "__init__() takes > exactly 1 positional argument (2 given)" > > Can anyone tell me where I have gone wrong? I thought the self > parameter should be passed to all class methods. > > TIA > Alan Harris-Reid > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sent from my mobile device From rabidpoobear at gmail.com Sat Feb 20 19:58:26 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 20 Feb 2010 12:58:26 -0600 Subject: [Tutor] fast sampling with replacement In-Reply-To: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> References: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> Message-ID: Can you explain what your function is doing and also post some test code to profile it? On Sat, Feb 20, 2010 at 10:22 AM, Andrew Fithian wrote: > Hi tutor, > > I'm have a statistical bootstrapping script that is bottlenecking on a > python function sample_with_replacement(). I wrote this function myself > because I couldn't find a similar function in python's random library. This > is the fastest version of the function I could come up with (I used > cProfile.run() to time every version I wrote) but it's not fast enough, can > you help me speed it up even more? > > import random > def sample_with_replacement(list): > l = len(list) # the sample needs to be as long as list > r = xrange(l) > _random = random.random > return [list[int(_random()*l)] for i in r] # using > list[int(_random()*l)] is faster than random.choice(list) > > FWIW, my bootstrapping script is spending roughly half of the run time in > sample_with_replacement() much more than any other function or method. > Thanks in advance for any advice you can give me. > > -Drew > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 20 20:41:37 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 Feb 2010 14:41:37 -0500 Subject: [Tutor] Superclass call problem In-Reply-To: <4B8020F9.2050307@googlemail.com> References: <4B8020F9.2050307@googlemail.com> Message-ID: <1c2a2c591002201141k33f00f34v277402be5c1d7ad2@mail.gmail.com> On Sat, Feb 20, 2010 at 12:50 PM, Alan Harris-Reid wrote: > Hi, > > I am having trouble understanding how superclass calls work. ?Here's some > code... > > class ParentClass(): > ? def __init__(self): > ? ? ? do something here You should inherit object to use super(): class ParentClass(object): Kent From kent37 at tds.net Sat Feb 20 20:50:06 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 Feb 2010 14:50:06 -0500 Subject: [Tutor] fast sampling with replacement In-Reply-To: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> References: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> Message-ID: <1c2a2c591002201150n370e6ccdscd2fe1e87df1f7f6@mail.gmail.com> On Sat, Feb 20, 2010 at 11:22 AM, Andrew Fithian wrote: > can > you help me speed it up even more? > import random > def sample_with_replacement(list): > ?? ?l = len(list) # the sample needs to be as long as list > ?? ?r = xrange(l) > ?? ?_random = random.random > ?? ?return [list[int(_random()*l)] for i in r] You don't have to assign to r, just call xrange() in the list comp. You can cache int() as you do with random.random() Did you try random.randint(0, l) instead of int(_random()*i) ? You shouldn't call your parameter 'list', it hides the builtin list and makes the code confusing. You might want to ask this on comp.lang.python, many more optimization gurus there. Kent From aharrisreid at googlemail.com Sat Feb 20 20:53:57 2010 From: aharrisreid at googlemail.com (Alan Harris-Reid) Date: Sat, 20 Feb 2010 19:53:57 +0000 Subject: [Tutor] Superclass call problem In-Reply-To: <1c2a2c591002201141k33f00f34v277402be5c1d7ad2@mail.gmail.com> References: <4B8020F9.2050307@googlemail.com> <1c2a2c591002201141k33f00f34v277402be5c1d7ad2@mail.gmail.com> Message-ID: <4B803DD5.4080308@googlemail.com> Kent Johnson wrote: > On Sat, Feb 20, 2010 at 12:50 PM, Alan Harris-Reid > wrote: > >> Hi, >> >> I am having trouble understanding how superclass calls work. Here's some >> code... >> >> class ParentClass(): >> def __init__(self): >> do something here >> > > You should inherit object to use super(): > class ParentClass(object): > > Kent Hi Kent, thanks for the reply, Sorry, left out 'object' from my example. The actual code already reads class ParentClass(object): Alan -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sat Feb 20 20:55:13 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 20 Feb 2010 13:55:13 -0600 Subject: [Tutor] fast sampling with replacement In-Reply-To: <1c2a2c591002201150n370e6ccdscd2fe1e87df1f7f6@mail.gmail.com> References: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> <1c2a2c591002201150n370e6ccdscd2fe1e87df1f7f6@mail.gmail.com> Message-ID: On Sat, Feb 20, 2010 at 1:50 PM, Kent Johnson wrote: > On Sat, Feb 20, 2010 at 11:22 AM, Andrew Fithian > wrote: > > can > > you help me speed it up even more? > > import random > > def sample_with_replacement(list): > > l = len(list) # the sample needs to be as long as list > > r = xrange(l) > > _random = random.random > > return [list[int(_random()*l)] for i in r] > > You don't have to assign to r, just call xrange() in the list comp. > You can cache int() as you do with random.random() > Did you try random.randint(0, l) instead of int(_random()*i) ? > You shouldn't call your parameter 'list', it hides the builtin list > and makes the code confusing. > > You might want to ask this on comp.lang.python, many more optimization > gurus there. > > Also the function's rather short, it would help to just inline it (esp. with Kent's modifications, it would basically boil down to a list comprehension (unless you keep the local ref's to the functions), I hear the function call overhead is rather high (depending on your usage - if your lists are huge and you don't call the function that much it might not matter.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sat Feb 20 20:56:14 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 20 Feb 2010 13:56:14 -0600 Subject: [Tutor] Superclass call problem In-Reply-To: <4B803DD5.4080308@googlemail.com> References: <4B8020F9.2050307@googlemail.com> <1c2a2c591002201141k33f00f34v277402be5c1d7ad2@mail.gmail.com> <4B803DD5.4080308@googlemail.com> Message-ID: > > > Hi Kent, thanks for the reply, > > Sorry, left out 'object' from my example. The actual code already reads > class ParentClass(object): > > Did you figure it out from my previous e-mail? -------------- next part -------------- An HTML attachment was scrubbed... URL: From laomao1975 at googlemail.com Sat Feb 20 23:34:34 2010 From: laomao1975 at googlemail.com (Lao Mao) Date: Sat, 20 Feb 2010 22:34:34 +0000 Subject: [Tutor] Replacing part of a URL Message-ID: <9f92935c1002201434tf404dbbp28560afc3c8fa12a@mail.gmail.com> Hello, I need to be able to replace the last bit of a bunch of URLs. The urls look like this: www.somesite.com/some/path/to/something.html They may be of varying lengths, but they'll always end with .something_or_other.html I want to take the "something" and replace it with something else. My current plan is to simply do a string.split("/")[-1] and then another .split('.') to result in ['something', 'html'], and then replace sometihing, and join them together again. But - wouldn't it make more sense to do this with re.sub? In which case, how would I specify only the bit between the last / and the .html? Thanks, Laomao -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Sun Feb 21 00:15:12 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 21 Feb 2010 04:45:12 +0530 Subject: [Tutor] Replacing part of a URL In-Reply-To: <9f92935c1002201434tf404dbbp28560afc3c8fa12a@mail.gmail.com> References: <9f92935c1002201434tf404dbbp28560afc3c8fa12a@mail.gmail.com> Message-ID: >>> url = 'http://www.somesite.com/some/path/to/something.html' >>> var = 'anotherthing' >>> i = url.rfind('/') + 1 >>> j = url.rfind('.') >>> if i < j: ... newurl = url[:i] + var + url[j:] ... else: ... newurl = url[:i] + var >>> newurl 'http://www.somesite.com/some/path/to/anotherthing.html' Changing the url to 'http://www.somesite.com/some/path/to/something' we get newurl as 'http://www.somesite.com/some/path/to/anotherthing' However if you are absolutely sure the pattern is ' http://www.somesite.com/some/path/to/something.html' , then you can simply write one-liner as: >>> url[:url.rfind('/') + 1] + var + url[url.rfind('.'):] 'http://www.somesite.com/some/path/to/anotherthing.html' Literally the same stuff. I don't think you need regex for such simple string manipulation. ~l0nwlf On Sun, Feb 21, 2010 at 4:04 AM, Lao Mao wrote: > Hello, > > I need to be able to replace the last bit of a bunch of URLs. > > The urls look like this: > > www.somesite.com/some/path/to/something.html > > They may be of varying lengths, but they'll always end with > .something_or_other.html > > I want to take the "something" and replace it with something else. > > My current plan is to simply do a string.split("/")[-1] > > and then another .split('.') to result in ['something', 'html'], and then > replace sometihing, and join them together again. > > But - wouldn't it make more sense to do this with re.sub? > > In which case, how would I specify only the bit between the last / and the > .html? > > Thanks, > > Laomao > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Sun Feb 21 00:40:44 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 21 Feb 2010 05:10:44 +0530 Subject: [Tutor] Replacing part of a URL In-Reply-To: References: <9f92935c1002201434tf404dbbp28560afc3c8fa12a@mail.gmail.com> Message-ID: > > They may be of varying lengths, but they'll always end with > .something_or_other.html > Missed this point. You can use posixpath module too as an option. >>> url = 'http://www.somesite.com/some/path/to/something.html >>> var = 'anotherthing' >>> posixpath.dirname(url) 'http://www.somesite.com/some/path/to' >>> posixpath.dirname(url) + '/' + var + '.html' 'http://www.somesite.com/some/path/to/anotherthing.html' On Sun, Feb 21, 2010 at 4:45 AM, Shashwat Anand wrote: > >>> url = 'http://www.somesite.com/some/path/to/something.html' > >>> var = 'anotherthing' > >>> i = url.rfind('/') + 1 > >>> j = url.rfind('.') > >>> if i < j: > ... newurl = url[:i] + var + url[j:] > ... else: > ... newurl = url[:i] + var > >>> newurl > 'http://www.somesite.com/some/path/to/anotherthing.html' > > Changing the url to 'http://www.somesite.com/some/path/to/something' we > get newurl as 'http://www.somesite.com/some/path/to/anotherthing' > > However if you are absolutely sure the pattern is ' > http://www.somesite.com/some/path/to/something.html' , then you can simply > write one-liner as: > >>> url[:url.rfind('/') + 1] + var + url[url.rfind('.'):] > 'http://www.somesite.com/some/path/to/anotherthing.html' > > Literally the same stuff. I don't think you need regex for such simple > string manipulation. > > ~l0nwlf > > > On Sun, Feb 21, 2010 at 4:04 AM, Lao Mao wrote: > >> Hello, >> >> I need to be able to replace the last bit of a bunch of URLs. >> >> The urls look like this: >> >> www.somesite.com/some/path/to/something.html >> >> They may be of varying lengths, but they'll always end with >> .something_or_other.html >> >> I want to take the "something" and replace it with something else. >> >> My current plan is to simply do a string.split("/")[-1] >> >> and then another .split('.') to result in ['something', 'html'], and then >> replace sometihing, and join them together again. >> >> But - wouldn't it make more sense to do this with re.sub? >> >> In which case, how would I specify only the bit between the last / and the >> .html? >> >> Thanks, >> >> Laomao >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Feb 21 00:44:04 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 20 Feb 2010 18:44:04 -0500 Subject: [Tutor] Replacing part of a URL In-Reply-To: <9f92935c1002201434tf404dbbp28560afc3c8fa12a@mail.gmail.com> References: <9f92935c1002201434tf404dbbp28560afc3c8fa12a@mail.gmail.com> Message-ID: <1c2a2c591002201544l60eb5852gc768c46653f4fe8a@mail.gmail.com> On Sat, Feb 20, 2010 at 5:34 PM, Lao Mao wrote: > Hello, > I need to be able to replace the last bit of a bunch of URLs. > The urls look like this: > www.somesite.com/some/path/to/something.html > They may be of varying lengths, but they'll always end with > .something_or_other.html > I want to take the "something" and replace it with something else. > My current plan is to simply do a string.split("/")[-1] > and then another .split('.') to result in ['something', 'html'], and then > replace sometihing, and join them together again. > But - wouldn't it make more sense to do this with re.sub? > In which case, how would I specify only the bit between the last / and the > .html? In [11]: import re In [13]: re.sub(r'/[^/]+\.html', '/something_else.html', 'www.somesite.com/some/path/to/something.html') Out[13]: 'www.somesite.com/some/path/to/something_else.html' Kent From contactdayo at gmail.com Sun Feb 21 00:49:19 2010 From: contactdayo at gmail.com (Dayo Adewunmi) Date: Sun, 21 Feb 2010 00:49:19 +0100 Subject: [Tutor] os.path.basename() issue with path slashes Message-ID: <4B8074FF.2040107@gmail.com> Hi all, This script I'm working on, should take all the image files in the current directory and generate an HTML thumbnails. import os import urllib # Generate thumbnail gallery def genThumbs(): # Get current directory name absolutePath = os.getcwd() urlprefix = "http://kili.org/~dayo" currentdir = os.path.basename(absolutePath) for dirname, subdirname, filenames in os.walk(absolutePath): for filename in filenames: print "" %(currentdir,filename,currentdir,filename) # Generate thumbnail gallery genThumbs() However, this is the type of output I get: See how in the url in the src attribute of the img tag the slashes after "~dayo" are somehow turned into backslashes, instead of forwardslashes. How come? Best regards Dayo From aharrisreid at googlemail.com Sun Feb 21 00:55:18 2010 From: aharrisreid at googlemail.com (Alan Harris-Reid) Date: Sat, 20 Feb 2010 23:55:18 +0000 Subject: [Tutor] Superclass call problem In-Reply-To: References: <4B8020F9.2050307@googlemail.com> Message-ID: <4B807666.6040602@googlemail.com> Luke Paireepinart wrote: > Your call to super is wrong. It should be super and you pass the class > and instance, then call init. > > On 2/20/10, Alan Harris-Reid wrote: > >> Hi, >> >> I am having trouble understanding how superclass calls work. Here's >> some code... >> >> class ParentClass(): >> def __init__(self): >> do something here >> >> class ChildClass(ParentClass): >> def __init__(self): >> super().__init__(self) # call parentclass >> __init__ method >> do something else here >> >> >> When the super().__init__ line runs I get the error "__init__() takes >> exactly 1 positional argument (2 given)" >> >> Can anyone tell me where I have gone wrong? I thought the self >> parameter should be passed to all class methods. >> >> TIA >> Alan Harris-Reid >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor Hi Luke, thanks for the reply, In addition to your suggestion, looks like I can use class ChildClass(ParentClass): def __init__(self, arg): super(ParentClass, self).__init__(arg) or super().__init__(arg) # this only works in Python 3, I think I prefer the 2nd way, as it is more generic (ie. don't need to state parent-class). Regards, Alan From anand.shashwat at gmail.com Sun Feb 21 01:04:23 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 21 Feb 2010 05:34:23 +0530 Subject: [Tutor] os.path.basename() issue with path slashes In-Reply-To: <4B8074FF.2040107@gmail.com> References: <4B8074FF.2040107@gmail.com> Message-ID: > > for dirname, subdirname, filenames in os.walk(absolutePath): > for filename in filenames: > print "" > %(currentdir,filename,currentdir,filename) > > I see a small typo here. print "" %(currentdir,filename,currentdir,filename) should rather be print "" %(currentdir,filename,currentdir,filename) .. notice the slashes "%s/%s" in href tag and "%s\%s" in img tag. >>> filename = '1.jpg' >>> absolutePath = os.getcwd() >>> currentdir = os.path.basename(absolutePath) >>> print "" %(currentdir,filename,currentdir,filename) ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From contactdayo at gmail.com Sun Feb 21 01:11:47 2010 From: contactdayo at gmail.com (Dayo Adewunmi) Date: Sun, 21 Feb 2010 01:11:47 +0100 Subject: [Tutor] os.path.basename() issue with path slashes In-Reply-To: References: <4B8074FF.2040107@gmail.com> Message-ID: <4B807A43.10307@gmail.com> Shashwat Anand wrote: > > > > > > for dirname, subdirname, filenames in os.walk(absolutePath): > for filename in filenames: > print "" > %(currentdir,filename,currentdir,filename) > > > I see a small typo here. > print "" > %(currentdir,filename,currentdir,filename) should rather be print " href=\"%s/%s\">" > %(currentdir,filename,currentdir,filename) .. > notice the slashes "%s/%s" in href tag and "%s\%s" in img tag. > > >>> filename = '1.jpg' > >>> absolutePath = os.getcwd() > >>> currentdir = os.path.basename(absolutePath) > >>> print "" > %(currentdir,filename,currentdir,filename) > > > > ~l0nwlf Arrrgh. Didn't see that forwardslash I put in there. It's fixed and works now. Thanks! Dayo From steve at pearwood.info Sun Feb 21 01:19:32 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 21 Feb 2010 11:19:32 +1100 Subject: [Tutor] Superclass call problem In-Reply-To: <4B8020F9.2050307@googlemail.com> References: <4B8020F9.2050307@googlemail.com> Message-ID: <201002211119.32760.steve@pearwood.info> On Sun, 21 Feb 2010 04:50:49 am Alan Harris-Reid wrote: > Hi, > > I am having trouble understanding how superclass calls work. Here's > some code... What version of Python are you using? In Python 2.x, you MUST inherit from object to use super, and you MUST explicitly pass the class and self: class ParentClass(object): def __init__(self, a, b, c): do something here class ChildClass(ParentClass): def __init__(self, a, b, c): super(ChildClass, self).__init__(a, b, c) In Python 3.x, all classes inherit from object and you no longer need to explicitly say so, and super becomes a bit smarter about where it is called from: # Python 3 only class ParentClass: def __init__(self, a, b, c): do something here class ChildClass(ParentClass): def __init__(self, a, b, c): super().__init__(a, b, c) I assume you are using Python 3.0 or 3.1. (If you're 3.0, you should upgrade to 3.1: 3.0 is s-l-o-w and no longer supported.) Your mistake was to pass self as an explicit argument to __init__. This is not needed, because Python methods automatically get passed self: > def __init__(self): > super().__init__(self) That has the effect of passing self *twice*, when __init__ expects to get self *once*, hence the error message you see: > When the super().__init__ line runs I get the error "__init__() takes > exactly 1 positional argument (2 given)" -- Steven D'Aprano From steve at pearwood.info Sun Feb 21 01:25:31 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 21 Feb 2010 11:25:31 +1100 Subject: [Tutor] Replacing part of a URL In-Reply-To: <9f92935c1002201434tf404dbbp28560afc3c8fa12a@mail.gmail.com> References: <9f92935c1002201434tf404dbbp28560afc3c8fa12a@mail.gmail.com> Message-ID: <201002211125.31392.steve@pearwood.info> On Sun, 21 Feb 2010 09:34:34 am Lao Mao wrote: > Hello, > > I need to be able to replace the last bit of a bunch of URLs. > > The urls look like this: > > www.somesite.com/some/path/to/something.html > > They may be of varying lengths, but they'll always end with > .something_or_other.html > > I want to take the "something" and replace it with something else. > > My current plan is to simply do a string.split("/")[-1] > > and then another .split('.') to result in ['something', 'html'], and > then replace sometihing, and join them together again. > > But - wouldn't it make more sense to do this with re.sub? Heavens no! Why do you need a 80 pound sledgehammer to crack a peanut??? "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." -- Jamie Zawinski -- Steven D'Aprano From rabidpoobear at gmail.com Sun Feb 21 01:30:53 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 20 Feb 2010 18:30:53 -0600 Subject: [Tutor] os.path.basename() issue with path slashes In-Reply-To: <4B807A43.10307@gmail.com> References: <4B8074FF.2040107@gmail.com> <4B807A43.10307@gmail.com> Message-ID: On Sat, Feb 20, 2010 at 6:11 PM, Dayo Adewunmi wrote: > Shashwat Anand wrote: > >> >> >> >> >> for dirname, subdirname, filenames in os.walk(absolutePath): >> for filename in filenames: >> print "" >> %(currentdir,filename,currentdir,filename) >> >> >> I see a small typo here. >> print "" >> %(currentdir,filename,currentdir,filename) should rather be print "> href=\"%s/%s\">" >> %(currentdir,filename,currentdir,filename) .. >> notice the slashes "%s/%s" in href tag and "%s\%s" in img tag. >> >> >>> filename = '1.jpg' >> >>> absolutePath = os.getcwd() >> >>> currentdir = os.path.basename(absolutePath) >> >>> print "" >> %(currentdir,filename,currentdir,filename) >> >> >> >> ~l0nwlf >> > Arrrgh. Didn't see that forwardslash I put in there. It's fixed and works > now. > Thanks! > > > If you're using OS functions you should NOT bank on the slashes being forward-slashes. This is platform-specific behavior. You should use os.path.split() to get the elements of your path and do a "/".join() on them. Otherwise your code will break on Windows because the path will be denoted with backslashes. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Sun Feb 21 01:36:10 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 21 Feb 2010 06:06:10 +0530 Subject: [Tutor] os.path.basename() issue with path slashes In-Reply-To: References: <4B8074FF.2040107@gmail.com> <4B807A43.10307@gmail.com> Message-ID: > > > > If you're using OS functions you should NOT bank on the slashes being > forward-slashes. This is platform-specific behavior. You should use > os.path.split() to get the elements of your path and do a "/".join() on > them. Otherwise your code will break on Windows because the path will be > denoted with backslashes. > > What about replacing os.path with posixpath ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Sun Feb 21 03:28:17 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 20 Feb 2010 18:28:17 -0800 Subject: [Tutor] Python 3.0 References: <005401cab21a$d7ced270$876c7750$@whittaker20@ntlworld.com> <4B7FEA0E.6000805@gmail.com> Message-ID: "bob gailer" wrote in message news:4B7FEA0E.6000805 at gmail.com... > On 2/20/2010 5:52 AM, Paul Whittaker wrote: >> >> Using the following script, the (Windows 7) PC echoes the key presses >> but doesn't quit (ever!) >> >> import msvcrt >> >> print('Press SPACE to stop...') >> >> while True: >> >> k = msvcrt.getch() # Strangely, this echoes to the IDLE window >> >> if k == ' ': # Not recognized >> >> break >> > > > According to the docs: "msvcrt.getch() - Read a keypress and return the > resulting character....This call will block if a keypress is not already > available, but will not wait for Enter to be pressed. If the pressed key > was a special function key, this will return '\000' or '\xe0'; the next > call will return the keycode. The Control-C keypress cannot be read with > this function." > > IOW - getch always returns 1 character. > > You are testing for a 0 length string. Will never happen. > > What keystroke do you want to break the loop? To Bob: There is a space between the quotes. To the OP: Are you running from a console window? The code works fine for me from the console, but running under both IDLE and PythonWin msvcrt.getch() returns 255 immediately. Windows applications without a console usually don't play nice with C I/O calls. -Mark From steve at pearwood.info Sun Feb 21 05:04:57 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 21 Feb 2010 15:04:57 +1100 Subject: [Tutor] os.path.basename() issue with path slashes In-Reply-To: <4B8074FF.2040107@gmail.com> References: <4B8074FF.2040107@gmail.com> Message-ID: <201002211504.58009.steve@pearwood.info> On Sun, 21 Feb 2010 10:49:19 am Dayo Adewunmi wrote: > Hi all, > > This script I'm working on, should take all the image files in the > current directory and generate an HTML thumbnails. > > import os > import urllib You import urllib, but don't appear to use it anywhere. > > # Generate thumbnail gallery > def genThumbs(): > # Get current directory name > absolutePath = os.getcwd() > urlprefix = "http://kili.org/~dayo" > currentdir = os.path.basename(absolutePath) > for dirname, subdirname, filenames in os.walk(absolutePath): > for filename in filenames: > print "" > %(currentdir,filename,currentdir,filename) You don't need to escape quotes, just use the other quote. Instead of: print "" use: print '' Also, I'm not sure why sometimes you use / as a directory separator and sometimes \. I think you're trying to do too much in one line, leading to repeated code. # Untested. for dirname, subdirname, filenames in os.walk(absolutePath): for filename in filenames: fullpath = os.path.join(currentdir, filename) if os.name == 'nt': fullpath.replace('\\', '/') print '' % (fullpath, fullpath) Hope that helps. -- Steven D'Aprano From denis.spir at free.fr Sun Feb 21 08:45:40 2010 From: denis.spir at free.fr (spir) Date: Sun, 21 Feb 2010 08:45:40 +0100 Subject: [Tutor] Replacing part of a URL In-Reply-To: <201002211125.31392.steve@pearwood.info> References: <9f92935c1002201434tf404dbbp28560afc3c8fa12a@mail.gmail.com> <201002211125.31392.steve@pearwood.info> Message-ID: <20100221084540.739d2e66@o> On Sun, 21 Feb 2010 11:25:31 +1100 Steven D'Aprano wrote: > "Some people, when confronted with a problem, think 'I know, I'll use > regular expressions.' Now they have two problems." -- Jamie Zawinski ;-) ________________________________ la vita e estrany http://spir.wikidot.com/ From afith13 at gmail.com Sun Feb 21 05:47:29 2010 From: afith13 at gmail.com (Andrew Fithian) Date: Sat, 20 Feb 2010 20:47:29 -0800 Subject: [Tutor] fast sampling with replacement In-Reply-To: <64fb0beb1002202037p536403fcgebdfdf2325a56f6e@mail.gmail.com> References: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> <1c2a2c591002201150n370e6ccdscd2fe1e87df1f7f6@mail.gmail.com> <64fb0beb1002202037p536403fcgebdfdf2325a56f6e@mail.gmail.com> Message-ID: <64fb0beb1002202047k2be386a7s59eb3d75316531b1@mail.gmail.com> On Sat, Feb 20, 2010 at 11:55 AM, Luke Paireepinart wrote: > > > On Sat, Feb 20, 2010 at 1:50 PM, Kent Johnson wrote: > >> On Sat, Feb 20, 2010 at 11:22 AM, Andrew Fithian >> wrote: >> > can >> > you help me speed it up even more? >> > import random >> > def sample_with_replacement(list): >> > l = len(list) # the sample needs to be as long as list >> > r = xrange(l) >> > _random = random.random >> > return [list[int(_random()*l)] for i in r] >> >> You don't have to assign to r, just call xrange() in the list comp. >> You can cache int() as you do with random.random() >> Did you try random.randint(0, l) instead of int(_random()*i) ? >> You shouldn't call your parameter 'list', it hides the builtin list >> and makes the code confusing. >> >> You might want to ask this on comp.lang.python, many more optimization >> gurus there. >> >> Also the function's rather short, it would help to just inline it (esp. > with Kent's modifications, it would basically boil down to a list > comprehension (unless you keep the local ref's to the functions), I hear the > function call overhead is rather high (depending on your usage - if your > lists are huge and you don't call the function that much it might not > matter.) > > The code is taking a list of length n and randomly sampling n items with replacement from the list and then returning the sample. I'm going to try the suggestion to inline the code before I make any of the other (good) suggested changes to the implementation. This function is being called thousands of times per execution, if the "function call overhead" is as high as you say that sounds like the place to start optimizing. Thanks guys. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fubarninja at hotmail.com Sun Feb 21 14:44:05 2010 From: fubarninja at hotmail.com (jim serson) Date: Sun, 21 Feb 2010 08:44:05 -0500 Subject: [Tutor] Using and Message-ID: Can anyone tell me if I can have my program check to see if something is true the add to count For example something like if c_1 and c_2 and c_3 true: count + 1 or if I can use it after splitting an input the problem is the input is variable so I don't know if I can do such a thing without knowing the input ahead of time. if anyone can tell me if this is possible or if I should be doing something else that would be grate thanks. _________________________________________________________________ Introducing Windows? phone. http://go.microsoft.com/?linkid=9708122 -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sun Feb 21 14:53:43 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 21 Feb 2010 07:53:43 -0600 Subject: [Tutor] Using and In-Reply-To: References: Message-ID: <333efb451002210553y11ecbebk6777c8aaf2a96272@mail.gmail.com> On Sun, Feb 21, 2010 at 7:44 AM, jim serson wrote: > Can anyone tell me if I can have my program check to see if something is > true the add to count > > For example something like > > if c_1 and c_2 and c_3 true: > count + 1 > > or if I can use it after splitting an input the problem is the input is > variable so I don't know if I can do such a thing without knowing the input > ahead of time. if anyone can tell me if this is possible or if I should be > doing something else that would be grate thanks. > Your explanation is a little ambiguous. Try writing out some pseudo-code of what you want to do, i.e. get input, assign to c1 assign random number to c2 get another input, assign to c3 check if c1, c2, and c3 are all non-empty strings if yes, do something otherwise do something else If you can do that, someone can probably help you. Otherwise we're just shooting in the dark, and no one likes that. 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 transmogribenno at gmail.com Sun Feb 21 14:55:38 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Sun, 21 Feb 2010 22:55:38 +0900 Subject: [Tutor] Using and In-Reply-To: References: Message-ID: <9b00d1a91002210555w517944abh4e119c2710eac7d5@mail.gmail.com> On 21 February 2010 22:44, jim serson wrote: > Can anyone tell me if I can have my program check to see if something is > true the add to count > > For example something like > > if c_1 and c_2 and c_3 true: > ??????????? count + 1 Your code currently throws the result of the count + 1 expression away. You probably want this instead: count = count + 1 > or if I can use it after splitting an input the problem is the input is > variable so I don't know if I can do such a thing without knowing the input > ahead of time. I'm not really sure what you're trying to say here. HTH, benno From kent37 at tds.net Sun Feb 21 15:10:23 2010 From: kent37 at tds.net (Kent Johnson) Date: Sun, 21 Feb 2010 09:10:23 -0500 Subject: [Tutor] Using and In-Reply-To: References: Message-ID: <1c2a2c591002210610i63e7f152n712e7c9c5d0331e0@mail.gmail.com> On Sun, Feb 21, 2010 at 8:44 AM, jim serson wrote: > Can anyone tell me if I can have my program check to see if something is > true the add to count > > For example something like > > if c_1 and c_2 and c_3 true: > > ??????????? count + 1 This will almost work as written. Try if c_1 and c_2 and c_3: count = count + 1 # or count += 1 Kent From davea at ieee.org Sun Feb 21 15:51:47 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 21 Feb 2010 09:51:47 -0500 Subject: [Tutor] fast sampling with replacement In-Reply-To: References: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> Message-ID: <4B814883.20203@ieee.org> Luke Paireepinart wrote: > Can you explain what your function is doing and also post some test code to > profile it? > > On Sat, Feb 20, 2010 at 10:22 AM, Andrew Fithian wrote: > > >> Hi tutor, >> >> I'm have a statistical bootstrapping script that is bottlenecking on a >> python function sample_with_replacement(). I wrote this function myself >> because I couldn't find a similar function in python's random library. This >> is the fastest version of the function I could come up with (I used >> cProfile.run() to time every version I wrote) but it's not fast enough, can >> you help me speed it up even more? >> >> import random >> def sample_with_replacement(list): >> l = len(list) # the sample needs to be as long as list >> r = xrange(l) >> _random = random.random >> return [list[int(_random()*l)] for i in r] # using >> list[int(_random()*l)] is faster than random.choice(list) >> >> FWIW, my bootstrapping script is spending roughly half of the run time in >> sample_with_replacement() much more than any other function or method. >> Thanks in advance for any advice you can give me. >> >> -Drew >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> list and l are poor names for locals. The former because it's a built-in type, and the latter because it looks too much like a 1. You don't say how big these lists are, but I'll assume they're large enough that the extra time spent creating the 'l' and 'r' variables is irrelevant. I suspect you could gain some speed by using random.randrange instead of multiplying random.random by the length. And depending on how the caller is using the data, you might gain some by returning a generator expression instead of a list. Certainly you could reduce the memory footprint. I wonder why you assume the output list has to be the same size as the input list. Since you're sampling with replacement, you're not using the whole list anyway. So I'd have defined the function to take a second argument, the length of desired array. And if you could accept a generator instead of a list, you don't care how long it is, so let it be infinite. (untested) def sample(mylist): mylistlen = len(mylist) randrange = random.randrange while True: yield mylist[ randrange(0, mylistlen)] DaveA From anothernetfellow at gmail.com Sun Feb 21 17:00:32 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Sun, 21 Feb 2010 17:00:32 +0100 Subject: [Tutor] Functions returning multiple values Message-ID: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> Hi, do you know if there is a way so that i can get multiple values from a function? For example: def count(a,b): c = a + b d = a - b How can I return the value of C and D? Then, i have another question: i've read, some time ago, this guide http://hetland.org/writing/instant-python.html, skipping the object-related part. Now i've started reading it, and have found something strange: just go where it says "Of course, now you know there is a better way. And why don?t we give it the default value of [] in the first place? Because of the way Python works, this would give all the Baskets the same empty list as default contents.". Can you please help me understanding this part? Thankyou Giorgio -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Feb 21 17:46:41 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Feb 2010 03:46:41 +1100 Subject: [Tutor] Functions returning multiple values In-Reply-To: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> Message-ID: <201002220346.42100.steve@pearwood.info> On Mon, 22 Feb 2010 03:00:32 am Giorgio wrote: > Hi, > > do you know if there is a way so that i can get multiple values from > a function? > > For example: > > def count(a,b): > c = a + b > d = a - b > > How can I return the value of C and D? Return a tuple of c and d: >>> def count(a, b): ... c = a + b ... d = a - b ... return c, d ... >>> t = count(15, 11) >>> t (26, 4) You can also unpack the tuple immediately: >>> x, y = count(15, 11) >>> x 26 >>> y 4 > Then, i have another question: i've read, some time ago, this guide > http://hetland.org/writing/instant-python.html, skipping the > object-related part. Now i've started reading it, and have found > something strange: just go where it says "Of course, now you know > there is a better way. And why don?t we give it the default value of > [] in the first place? Because of the way Python works, this would > give all the Baskets the same empty list as default contents.". Can > you please help me understanding this part? When you declare a default value in a function like this: def f(a, b, c=SOMETHING): the expression SOMETHING is calculated once, when the function is defined, and *not* each time you call the function. So if I do this: x = 1 y = 2 def f(a, b, c=x+y): return a+b+c the default value for c is calculated once, and stored inside the function: >>> f(0, 0) 3 Even if I change x or y: >>> x = 9999 >>> f(0, 0) 3 So if I use a list as a default value (or a dict), the default is calculated once and stored in the function. You can see it by looking at the function's defaults: >>> def f(alist=[]): ... alist.append(1) ... return alist >>> >>> f.func_defaults[0] [] Now, call the function without an argument: >>> f() [1] >>> f() [1, 1] >>> f() [1, 1, 1] >>> f.func_defaults[0] [1, 1, 1] How is this happening? Because every time you call the function, it appends 1 to the argument. If you don't supply an argument, it appends 1 to the default, changing it in place. Why doesn't the same thing happen here? >>> def g(x=0): ... x += 1 ... return x ... >>> g.func_defaults[0] 0 >>> g() 1 >>> g() 1 >>> g.func_defaults[0] 0 The answer is that ints are immutable: you can't change their value. When you do x+=1, it doesn't modify the int 0 in place, turning it into 1. It leaves 0 as zero, and gives you a new int equal to one. So the default value stored in the function never changes. The difference boils down to immutable objects, which can't be changed in place, and mutable objects, which can. Immutable: ints, floats, strings, tuples, frozensets Mutable: lists, dicts, sets, most custom classes -- Steven D'Aprano From marcodrompre at gmail.com Sun Feb 21 18:06:14 2010 From: marcodrompre at gmail.com (=?ISO-8859-1?Q?Marco_Rompr=E9?=) Date: Sun, 21 Feb 2010 12:06:14 -0500 Subject: [Tutor] Using Python with a Mac Message-ID: <4bdcec5e1002210906q40e5632fw4585a528c1a52e15@mail.gmail.com> Hi everyone, I would like to know how to use python with a mac. For now, I go to spotlight, open terminal then type IDLE and a window pops up but its like the window that opens when you run your programs already saved and I'm not able to open another window to write a script from scratch. Could someone help me please please???? I have the latest Macbook Pro so 2,88ghz 15 inches screen. Thank you in advance Marchoes -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Sun Feb 21 18:19:15 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 21 Feb 2010 22:49:15 +0530 Subject: [Tutor] Using Python with a Mac In-Reply-To: <4bdcec5e1002210906q40e5632fw4585a528c1a52e15@mail.gmail.com> References: <4bdcec5e1002210906q40e5632fw4585a528c1a52e15@mail.gmail.com> Message-ID: mac have python 2.5 and 2.6 installed by default. If you use Vi then you are up for it. If you want IDE then pydev plugin with eclipse can be tried. I had heard good things about it. Also you can try bpython(python fancy interpretor), install it via macports. ~l0nwlf On Sun, Feb 21, 2010 at 10:36 PM, Marco Rompr? wrote: > Hi everyone, I would like to know how to use python with a mac. > > For now, I go to spotlight, open terminal then type IDLE and a window pops > up but its like the window that opens when you run your programs already > saved and I'm not able to open another window to write a script from > scratch. > > Could someone help me please please???? > > I have the latest Macbook Pro so 2,88ghz 15 inches screen. > > Thank you in advance > > Marchoes > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From contactdayo at gmail.com Sun Feb 21 18:23:04 2010 From: contactdayo at gmail.com (Dayo Adewunmi) Date: Sun, 21 Feb 2010 18:23:04 +0100 Subject: [Tutor] Regex to find files ending with one of a given set of extensions Message-ID: <4B816BF8.5000308@gmail.com> Hi all I'm trying use regex to match image formats: import re def findImageFiles(): imageRx = re.compile('\.jpe?g$|\.png$|\.gif$|\.tiff?$', re.I) someFiles = ["sdfinsf.png","dsiasd.dgf","wecn.GIF","iewijiefi.jPg","iasjasd.py"] findImages = imageRx(someFiles) print "START: %s" %(findImages.start()) print "GROUP: %s" %(findImages.group()) def main(): findImageFiles() if __name__ == "__main__": main() here's the traceback: $ python test.py Traceback (most recent call last): File "test.py", line 25, in main() File "test.py", line 21, in main findImageFiles() File "test.py", line 14, in findImageFiles findImages = imageRx(someFiles) TypeError: '_sre.SRE_Pattern' object is not callable i'm new with regexing, please help. Thanks Dayo From steve at pearwood.info Sun Feb 21 18:34:19 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Feb 2010 04:34:19 +1100 Subject: [Tutor] fast sampling with replacement In-Reply-To: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> References: <64fb0beb1002200822nb414ea4qe3da89a2f29979c1@mail.gmail.com> Message-ID: <201002220434.20040.steve@pearwood.info> On Sun, 21 Feb 2010 03:22:19 am Andrew Fithian wrote: > Hi tutor, > > I'm have a statistical bootstrapping script that is bottlenecking on > a python function sample_with_replacement(). I wrote this function > myself because I couldn't find a similar function in python's random > library. random.choice(list) does sample with replacement. If you need more than one sample, call it in a loop or a list comprehension: >>> mylist = [1, 2, 4, 8, 16, 32, 64, 128] >>> choice = random.choice >>> values = [choice(mylist) for _ in xrange(4)] >>> values [64, 32, 4, 4] > This is the fastest version of the function I could come up > with (I used cProfile.run() to time every version I wrote) but it's > not fast enough, can you help me speed it up even more? Profiling doesn't tell you how *fast* something is, but how much time it is using. If something takes a long time to run, perhaps that's because you are calling it lots of times. If that's the case, you should try to find a way to call it less often. E.g. instead of taking a million samples, can you get by with only a thousand? Do you need to prepare all the samples ahead of time, or do them only when needed? > import random > def sample_with_replacement(list): > l = len(list) # the sample needs to be as long as list > r = xrange(l) > _random = random.random > return [list[int(_random()*l)] for i in r] # using > list[int(_random()*l)] is faster than random.choice(list) Well, maybe... it's a near thing. I won't bother showing my timing code (hint: use the timeit module) unless you ask, but in my tests, I don't get a clear consistent winner between random.choice and your version. Your version is a little bit faster about 2 out of 3 trials, but slower 1 out of 3. This isn't surprising if you look at the random.choice function: def choice(self, seq): return seq[int(self.random() * len(seq))] It is essentially identical to your version, the major difference being you use the same algorithm directly in a list comprehension instead of calling it as a function. So I would expect any difference to be small. I would say that you aren't going to speed up the sampling algorithm in pure Python. This leaves you with some options: (1) Live with the speed as it is. Are you sure it's too slow? (2) Re-write the random number generator in C. (3) Find a way to use fewer samples. (4) Use a lower-quality random number generator which is faster. > FWIW, my bootstrapping script is spending roughly half of the run > time in sample_with_replacement() much more than any other function > or method. Thanks in advance for any advice you can give me. You don't tell us whether that actually matters. Is it taking 3 hours in a 6 hour run time? If so, then it is worth spending time and effort to cut that down by a few hours. Or is it taking 0.2 seconds out of 0.4 seconds? If that's the case, then who cares? :) -- Steven D'Aprano From steve at pearwood.info Sun Feb 21 18:46:40 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Feb 2010 04:46:40 +1100 Subject: [Tutor] Regex to find files ending with one of a given set of extensions In-Reply-To: <4B816BF8.5000308@gmail.com> References: <4B816BF8.5000308@gmail.com> Message-ID: <201002220446.40746.steve@pearwood.info> On Mon, 22 Feb 2010 04:23:04 am Dayo Adewunmi wrote: > Hi all > > I'm trying use regex to match image formats: Perhaps you should use a simpler way. def isimagefile(filename): ext = os.path.splitext(filename)[1] return (ext.lower() in ('.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff')) def findImageFiles(): someFiles = [ "sdfinsf.png","dsiasd.dgf","wecn.GIF","iewijiefi.jPg","iasjasd.py"] return filter(isimagefile, someFiles) > $ python test.py > Traceback (most recent call last): > File "test.py", line 25, in > main() > File "test.py", line 21, in main > findImageFiles() > File "test.py", line 14, in findImageFiles > findImages = imageRx(someFiles) > TypeError: '_sre.SRE_Pattern' object is not callable The error is the line findImages = imageRx(someFiles) You don't call regexes, you have to use the match or search methods. And you can't call it on a list of file names, you have to call it on each file name separately. # untested for filename in someFiles: mo = imageRx.search(filename) if mo is None: # no match pass else: print filename -- Steven D'Aprano From zebra05 at gmail.com Sun Feb 21 19:22:10 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Sun, 21 Feb 2010 20:22:10 +0200 Subject: [Tutor] Python file escaping issue? Message-ID: Hi all, I'm trying to read a file (Python 2.5.2, Windows XP) as follows: assignment_file = open('C:\Documents and Settings\coderoid\My Documents\Downloads\code_sample.txt', 'r+').readlines() new_file = open(new_file.txt, 'w+') for line in assignment_file: new_file.write(line) new_file.close() assignment_file.close() When the code runs, the file path has the slashes converted to double slashes. When try to escape them, i just seemto add more slashes. What am i missing? -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From memilanuk at gmail.com Sun Feb 21 19:22:53 2010 From: memilanuk at gmail.com (Monte Milanuk) Date: Sun, 21 Feb 2010 10:22:53 -0800 Subject: [Tutor] Using Python with a Mac In-Reply-To: References: <4bdcec5e1002210906q40e5632fw4585a528c1a52e15@mail.gmail.com> Message-ID: <6f26596c1002211022u5aeb8100k9086ca080749c44d@mail.gmail.com> On Sun, Feb 21, 2010 at 10:36 PM, Marco Rompr? wrote: > Hi everyone, I would like to know how to use python with a mac. > > For now, I go to spotlight, open terminal then type IDLE and a window pops > up but its like the window that opens when you run your programs already > saved and I'm not able to open another window to write a script from > scratch. > By default IDLE seems to open up a python interpreter window (regardless of platform). If you hit Apple-N to open a 'New' window, or select the equivalent command from the menu, it will open a new window for entering a script; from there you can perform various actions (save, run, debug, etc.) If you click on 'Python' to the left of 'File' and select 'Preferences' and then pick the 'General' tab you can opt to have IDLE open up with an editor window instead of an interpreter window the next time you start. HTH, Monte -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sun Feb 21 19:41:07 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 21 Feb 2010 12:41:07 -0600 Subject: [Tutor] Python file escaping issue? In-Reply-To: References: Message-ID: <333efb451002211041k5c27ff44ub324cf33f3555470@mail.gmail.com> On Sun, Feb 21, 2010 at 12:22 PM, Sithembewena Lloyd Dube wrote: > Hi all, > > I'm trying to read a file (Python 2.5.2, Windows XP) as follows: > > assignment_file = open('C:\Documents and Settings\coderoid\My > Documents\Downloads\code_sample.txt', 'r+').readlines() > new_file = open(new_file.txt, 'w+') > for line in assignment_file: > new_file.write(line) > > new_file.close() > assignment_file.close() > > When the code runs, the file path has the slashes converted to double > slashes. When try to escape them, i just seemto add more slashes. What am i > missing? try using the r to declare it as a raw string: >>> filename = r'C:\Documents and Settings\coderoid\otherstuff' >>> filename 'C:\\Documents and Settings\\coderoid\\otherstuff' that should work. 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 zebra05 at gmail.com Sun Feb 21 20:25:06 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Sun, 21 Feb 2010 21:25:06 +0200 Subject: [Tutor] Python file escaping issue? In-Reply-To: References: <333efb451002211041k5c27ff44ub324cf33f3555470@mail.gmail.com> Message-ID: @Wayne, sorry to have replied to you directly.. On Sun, Feb 21, 2010 at 9:23 PM, Sithembewena Lloyd Dube wrote: > Solved by moving the file just under C:\ > > Must be an issue with directory name spaces. > > By the way, my code was riddled with bugs. readlines() returns a list > object, which does not have a close method - and i had not placed quotes > around the new_file argument. > > > > > On Sun, Feb 21, 2010 at 9:01 PM, Sithembewena Lloyd Dube < > zebra05 at gmail.com> wrote: > >> Hi Wayne, >> >> Thank you for responding. I did try declaring it as a raw string, and what >> i get is pretty much the same result (slashes in the path become double >> slashes, so naturally the file is not found). >> >> I did try googling around for how to handle/ escape file paths, but i >> cannot seem to dig up anything useful. >> >> Regards, >> Sithembewena >> >> >> On Sun, Feb 21, 2010 at 8:41 PM, Wayne Werner wrote: >> >>> On Sun, Feb 21, 2010 at 12:22 PM, Sithembewena Lloyd Dube < >>> zebra05 at gmail.com> wrote: >>> >>>> Hi all, >>>> >>>> I'm trying to read a file (Python 2.5.2, Windows XP) as follows: >>>> >>>> assignment_file = open('C:\Documents and Settings\coderoid\My >>>> Documents\Downloads\code_sample.txt', 'r+').readlines() >>>> new_file = open(new_file.txt, 'w+') >>>> for line in assignment_file: >>>> new_file.write(line) >>>> >>>> new_file.close() >>>> assignment_file.close() >>>> >>>> When the code runs, the file path has the slashes converted to double >>>> slashes. When try to escape them, i just seemto add more slashes. What am i >>>> missing? >>> >>> >>> try using the r to declare it as a raw string: >>> >>> filename = r'C:\Documents and Settings\coderoid\otherstuff' >>> >>> filename >>> 'C:\\Documents and Settings\\coderoid\\otherstuff' >>> >>> that should work. >>> >>> 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 >>> >> >> >> >> -- >> Regards, >> Sithembewena Lloyd Dube >> http://www.lloyddube.com >> > > > > -- > Regards, > Sithembewena Lloyd Dube > http://www.lloyddube.com > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rick at niof.net Sun Feb 21 20:53:54 2010 From: rick at niof.net (Rick Pasotto) Date: Sun, 21 Feb 2010 14:53:54 -0500 Subject: [Tutor] working with email module Message-ID: <20100221195354.GT18786@niof.net> I subscribe to an email list that distributes image files. I'd like to automate the process of saving the images to individual files. I've got it mostly figured out with two exceptions. 1) Sometimes msg.filename returns 'None' even though msg.get_content_type returns 'image/jpeg' and the actual message (looking at it with a file viewer) *does* have a filename parameter. When I use the 'v' command in 'mutt' the filename shows so why does python fail to find it? 2) Is it possible to 'detach' a single subpart of a message? The docs show msg.attach() to create an email but I can't find anything that would allow deleting an attachment. I know how to delete an entire message from a mailbox. -- "There is no medicine like hope, no incentive so great, and no tonic so powerful as expectation of something tomorrow." -- Orison Marden Rick Pasotto rick at niof.net http://www.niof.net From aharrisreid at googlemail.com Sun Feb 21 22:07:07 2010 From: aharrisreid at googlemail.com (Alan Harris-Reid) Date: Sun, 21 Feb 2010 21:07:07 +0000 Subject: [Tutor] Superclass call problem In-Reply-To: References: Message-ID: <4B81A07B.4050908@googlemail.com> >> Hi, >> >> I am having trouble understanding how superclass calls work. Here's >> some code... >> > > What version of Python are you using? > > In Python 2.x, you MUST inherit from object to use super, and you MUST > explicitly pass the class and self: > > class ParentClass(object): > def __init__(self, a, b, c): > do something here > > class ChildClass(ParentClass): > def __init__(self, a, b, c): > super(ChildClass, self).__init__(a, b, c) > > In Python 3.x, all classes inherit from object and you no longer need to > explicitly say so, and super becomes a bit smarter about where it is > called from: > > # Python 3 only > class ParentClass: > def __init__(self, a, b, c): > do something here > > class ChildClass(ParentClass): > def __init__(self, a, b, c): > super().__init__(a, b, c) > > > I assume you are using Python 3.0 or 3.1. (If you're 3.0, you should > upgrade to 3.1: 3.0 is s-l-o-w and no longer supported.) > > > Your mistake was to pass self as an explicit argument to __init__. This > is not needed, because Python methods automatically get passed self: > > >> def __init__(self): >> super().__init__(self) >> > > That has the effect of passing self *twice*, when __init__ expects to > get self *once*, hence the error message you see: > > >> When the super().__init__ line runs I get the error "__init__() takes >> exactly 1 positional argument (2 given)" >> Hi Steven, thanks for the reply. Fortunately I am using Python 3.1, so I can use the super().__init__(a, b, c) syntax. Regards, Alan -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Feb 22 00:01:06 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Feb 2010 10:01:06 +1100 Subject: [Tutor] Python file escaping issue? In-Reply-To: References: Message-ID: <201002221001.06549.steve@pearwood.info> On Mon, 22 Feb 2010 05:22:10 am Sithembewena Lloyd Dube wrote: > Hi all, > > I'm trying to read a file (Python 2.5.2, Windows XP) as follows: > > assignment_file = open('C:\Documents and Settings\coderoid\My > Documents\Downloads\code_sample.txt', 'r+').readlines() > new_file = open(new_file.txt, 'w+') > for line in assignment_file: > new_file.write(line) > > new_file.close() > assignment_file.close() > > When the code runs, the file path has the slashes converted to double > slashes. When try to escape them, i just seemto add more slashes. > What am i missing? An understanding of how backslash escapes work in Python. Backslashes in string literals (but not in text you read from a file, say) are used to inject special characters into the string, just like C and other languages do. These backslash escapes include: \t tab \n newline \f formfeed \\ backslash and many others. Any other non-special backslash is left alone. So when you write a string literal including backslashes and a special character, you get this: >>> s = 'abc\tz' # tab >>> print s abc z >>> print repr(s) 'abc\tz' >>> len(s) 5 But if the escape is not a special character: >>> s = 'abc\dz' # nothing special >>> print s abc\dz >>> print repr(s) 'abc\\dz' >>> len(s) 6 The double backslash is part of the *display* of the string, like the quotation marks, and not part of the string itself. The string itself only has a single backslash and no quote marks. So if you write a pathname like this: >>> path = 'C:\datafile.txt' >>> print path C:\datafile.txt >>> len(path) 15 It *seems* to work, because \d is left as backlash-d. But then you do this, and wonder why you can't open the file: >>> path = 'C:\textfile.txt' >>> print path C: extfile.txt >>> len(path) 14 Some people recommend using raw strings. Raw strings turn off backslash processing, so you can do this: >>> path = r'C:\textfile.txt' >>> print path C:\textfile.txt But raw strings were invented for the regular expression module, not for Windows pathnames, and they have a major limitation: you can't end a raw string with a backslash. >>> path = r'C:\directory\' File "", line 1 path = r'C:\directory\' ^ SyntaxError: EOL while scanning single-quoted string The best advice is to remember that Windows allows both forward and backwards slashes as the path separator, and just write all your paths using the forward slash: 'C:/directory/' 'C:textfile.txt' -- Steven D'Aprano From sierra_mtnview at sbcglobal.net Mon Feb 22 04:29:38 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 21 Feb 2010 19:29:38 -0800 Subject: [Tutor] "Two" Card Monty with File Operations--Reading from Wrong Folder (W7?) Message-ID: <4B81FA22.4020009@sbcglobal.net> I have a program called TrackStudy.py and another called ReportTool.py Track runs above an Events folder that contains txt files that it examines.Report runs in an Events folder on the same txt files. Neither is operated when the other is operating. Both only read the same files. I've been operating Report in another Events folder at another folder level. Both work fine that way. I decided to copy Report into the Event folder below Track. If I run Track, it sees every txt file in Events. However, if I run Track, it refers back to the other Events folder, and works fine even though on the wrong set of files. I've pretty much assumed by observation, that these programs read the txt files in alphabetical order. It still seems the case. There is one difference in Track on this. It uses: paths = glob.glob(final_string) to locate files. They always occur in the proper low to high sequence. Report produces the wrong files in alpha order. The question is why does Report see the folder in the wrong folder? Although I think I've verified matters, I could be off. Is there a way to ensure I'm really getting to the right folder? There may be a Win7 problem here. See below. Here's a diagram that might help. Cap names means folder. BINGO EVENTS a1.txt a2.txt report.py CARDS track.py EVENTS b1.txt b2.txt b3.txt Now copy report.py to CARDS BINGO EVENTS a1.txt a2.txt report.py CARDS track.py EVENTS b1.txt b2.txt b3.txt report.py While working on this problem, I came up with a Win7 puzzler. It amounts to this. If I search for files in EVENTS of CARDS for "b", it only finds one of the b-files. I had a long 1 hour talk with HP tech support. They had no answer, but will take it up with MS. It may be related to the first problem. Probably not, but curious. I suspect that Win7's new folder search has somehow used a filter. I had no idea of any filter use until I accidentally found it in W7 Help. Perhaps the filter was some how set. Not by me. Here's a stab in the dark. Maybe the copied report.py really is a pointer to the other one? -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From laomao1975 at googlemail.com Mon Feb 22 07:06:40 2010 From: laomao1975 at googlemail.com (Lao Mao) Date: Mon, 22 Feb 2010 06:06:40 +0000 Subject: [Tutor] Extracting comments from a file Message-ID: <9f92935c1002212206g11adf59fl2e09e27723d5a906@mail.gmail.com> Hi, I have an html file, with xml style comments in: I'd like to extract only the comments. My sense of smell suggests that there's probably a library (maybe an xml library) that does this already. Otherwise, my current alogorithm looks a bit like this: * Iterate over file * If current line contains - Toggle 'is_comment' to no This feels crude, but is it effective, or ok? Thanks, Laomao -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Mon Feb 22 08:37:21 2010 From: denis.spir at free.fr (spir) Date: Mon, 22 Feb 2010 08:37:21 +0100 Subject: [Tutor] Python file escaping issue? In-Reply-To: <201002221001.06549.steve@pearwood.info> References: <201002221001.06549.steve@pearwood.info> Message-ID: <20100222083721.32bb957f@o> Just a little complement to Steven's excellent explanation: On Mon, 22 Feb 2010 10:01:06 +1100 Steven D'Aprano wrote: [...] > So if you write a pathname like this: > > >>> path = 'C:\datafile.txt' > >>> print path > C:\datafile.txt > >>> len(path) > 15 > > It *seems* to work, because \d is left as backlash-d. But then you do > this, and wonder why you can't open the file: I consider this misleading, since it can only confuse newcomers. Maybe "lonely" single backslashes (not forming a "code" with following character(s)) should be invalid. Meaning literal backslashes would always be doubled (in plain, non-raw, strings). What do you think? > But if the escape is not a special character: > > >>> s = 'abc\dz' # nothing special > >>> print s > abc\dz > >>> print repr(s) > 'abc\\dz' > >>> len(s) > 6 > > The double backslash is part of the *display* of the string, like the > quotation marks, and not part of the string itself. The string itself > only has a single backslash and no quote marks. This "display" is commonly called "representation", thus the name of the function repr(). It is a string representation *for the programmer* only, both on input and output: * to allow one writing, in code itself, string literal constants containing special characters, in a practical manner (eg file pathes/names) * to allow one checking the actual content of string values, at testing time The so-called interactive interpreter outputs representations by default. An extreme case: >>> s = "\\" >>> s '\\' >>> print s, len(s) \ 1 >>> print repr(s), len(repr(s)) '\\' 4 >>> The string holds 1 char; its representation (also a string, indeed) holds 4. > The best advice is to remember that Windows allows both forward and > backwards slashes as the path separator, and just write all your paths > using the forward slash: > > 'C:/directory/' > 'C:textfile.txt' Another solution is to take the habit to always escape '\' by doubling it. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From contactdayo at gmail.com Mon Feb 22 10:44:31 2010 From: contactdayo at gmail.com (Dayo Adewunmi) Date: Mon, 22 Feb 2010 10:44:31 +0100 Subject: [Tutor] Regex to find files ending with one of a given set of extensions In-Reply-To: <201002220446.40746.steve@pearwood.info> References: <4B816BF8.5000308@gmail.com> <201002220446.40746.steve@pearwood.info> Message-ID: <4B8251FF.6030803@gmail.com> Steven D'Aprano wrote: > On Mon, 22 Feb 2010 04:23:04 am Dayo Adewunmi wrote: > >> Hi all >> >> I'm trying use regex to match image formats: >> > > Perhaps you should use a simpler way. > > def isimagefile(filename): > ext = os.path.splitext(filename)[1] > return (ext.lower() in > ('.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff')) > > > def findImageFiles(): > someFiles = [ > "sdfinsf.png","dsiasd.dgf","wecn.GIF","iewijiefi.jPg","iasjasd.py"] > return filter(isimagefile, someFiles) > > > >> $ python test.py >> Traceback (most recent call last): >> File "test.py", line 25, in >> main() >> File "test.py", line 21, in main >> findImageFiles() >> File "test.py", line 14, in findImageFiles >> findImages = imageRx(someFiles) >> TypeError: '_sre.SRE_Pattern' object is not callable >> > > The error is the line > > findImages = imageRx(someFiles) > > > You don't call regexes, you have to use the match or search methods. And > you can't call it on a list of file names, you have to call it on each > file name separately. > > # untested > for filename in someFiles: > mo = imageRx.search(filename) > if mo is None: > # no match > pass > else: > print filename > > > > > I incorporated this into my code: def isimagefile(filename): ext = os.path.splitext(filename)[1] return (ext.lower() in ('.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff')) And it's working fine now. Thanks! :-) Dayo From femilangy at yahoo.co.uk Mon Feb 22 02:49:51 2010 From: femilangy at yahoo.co.uk (Olufemi Onanuga) Date: Mon, 22 Feb 2010 01:49:51 +0000 (GMT) Subject: [Tutor] Drawing faces Message-ID: <169753.28451.qm@web27102.mail.ukl.yahoo.com> Hello, I am trying to write and test a function to meet the following specifications ? drawFace(center,size,win),center is a point,size is an int,and win is a GraphWin.Draws a simple face of the given size in win. ? I want the function to be able to draw three differnet faces in a single window,when i invoke drawFace(center,size,win) into def main(). ? thanks kola -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Feb 22 13:39:48 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Feb 2010 07:39:48 -0500 Subject: [Tutor] Extracting comments from a file In-Reply-To: <9f92935c1002212206g11adf59fl2e09e27723d5a906@mail.gmail.com> References: <9f92935c1002212206g11adf59fl2e09e27723d5a906@mail.gmail.com> Message-ID: <1c2a2c591002220439t645acc2cib2d182edb1653e6f@mail.gmail.com> On Mon, Feb 22, 2010 at 1:06 AM, Lao Mao wrote: > Hi, > > I have an html file, with xml style comments in: > > > > I'd like to extract only the comments.? My sense of smell suggests that > there's probably a library (maybe an xml library) that does this already. Take a look at BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/documentation.html Your code will look something like this (untested): from BeautifulSoup import BeautifulSoup, Comment data = open('myfile.html').read() soup = BeautifulSoup(data) current = soup while current: if isinstance(current, Comment): print current.string current = current.next > Otherwise, my current alogorithm looks a bit like this: > > * Iterate over file > * If current line contains > ? - Toggle 'is_comment' to no > > This feels crude, but is it effective, or ok? It will break on comments like It will print too much if the comment doesn't start and end at the start and end of the line. Kent > > Thanks, > > Laomao > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From steve at pearwood.info Mon Feb 22 13:43:56 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Feb 2010 23:43:56 +1100 Subject: [Tutor] Drawing faces In-Reply-To: <169753.28451.qm@web27102.mail.ukl.yahoo.com> References: <169753.28451.qm@web27102.mail.ukl.yahoo.com> Message-ID: <201002222343.56877.steve@pearwood.info> On Mon, 22 Feb 2010 12:49:51 pm Olufemi Onanuga wrote: > Hello, > I am trying to write and test a function to meet the following > specifications > drawFace(center,size,win),center is a point,size is an int,and win is > a GraphWin.Draws a simple face of the given size in win. > I want the function to be able to draw three differnet faces in a > single window,when i invoke drawFace(center,size,win) into def > main(). > thanks > kola Do you actually have a question? Please show the code you have already written, and tell us what doesn't work. -- Steven D'Aprano From steve at pearwood.info Mon Feb 22 13:52:12 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Feb 2010 23:52:12 +1100 Subject: [Tutor] Python file escaping issue? In-Reply-To: <20100222083721.32bb957f@o> References: <201002221001.06549.steve@pearwood.info> <20100222083721.32bb957f@o> Message-ID: <201002222352.13100.steve@pearwood.info> On Mon, 22 Feb 2010 06:37:21 pm spir wrote: > > It *seems* to work, because \d is left as backlash-d. But then you > > do this, and wonder why you can't open the file: > > I consider this misleading, since it can only confuse newcomers. > Maybe "lonely" single backslashes (not forming a "code" with > following character(s)) should be invalid. Meaning literal > backslashes would always be doubled (in plain, non-raw, strings). > What do you think? Certainly it can lead to confusion for beginners, but it follows the convention of languages like bash and (I think) C++. There are three main ways to deal with an unrecognised escape sequence: * raise an error * ignore the backslash, e.g. \d -> d * keep the backslash, e.g. \d -> \d There are good arguments for all three, so I don't think you'll get consensus for any change. -- Steven D'Aprano From anothernetfellow at gmail.com Mon Feb 22 15:13:30 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Mon, 22 Feb 2010 15:13:30 +0100 Subject: [Tutor] Functions returning multiple values In-Reply-To: <201002220346.42100.steve@pearwood.info> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> Message-ID: <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> Ok, thankyou. So, in other words, i must pay attention to what i set as default value in a function. I should NEVER set empty lists as default values. The guide i've linked says "To learn more about this, you should read the documentation and look for the difference between *identity* and *equality*. ". Can you please help me also with that? Where can i read what is the difference? And, i have some difficulties understanding the other "strange" example in that howto. Just scroll down to: "However, the *point* is that the value of x is picked up from the *environment* at the time when the function is defined. How is this useful? Let?s take an example ? a function which composes two other functions." He is working on a function that compose other 2 functions. This is the final solution def compose(fun1, fun2): def inner(x, fun1=fun1, fun2=fun2): return fun1(fun2(x)) return inner But also tries to explain why this example: # Wrong version def compose(fun1, fun2): def inner(x): return fun1(fun2(x)) return inner def fun1(x): return x + " world!" def fun2(x): return "Hello," sincos = compose(sin,cos) # Using the wrong version x = sincos(3) Won't work. Now, the problem is that the "inner" function gets fun1 and fun2 from other 2 functions. My question is: why? inner is a sub-function of compose, where fun1 and fun2 are defined. Giorgio 2010/2/21 Steven D'Aprano > On Mon, 22 Feb 2010 03:00:32 am Giorgio wrote: > > Hi, > > > > do you know if there is a way so that i can get multiple values from > > a function? > > > > For example: > > > > def count(a,b): > > c = a + b > > d = a - b > > > > How can I return the value of C and D? > > Return a tuple of c and d: > > >>> def count(a, b): > ... c = a + b > ... d = a - b > ... return c, d > ... > >>> t = count(15, 11) > >>> t > (26, 4) > > You can also unpack the tuple immediately: > > >>> x, y = count(15, 11) > >>> x > 26 > >>> y > 4 > > > > > Then, i have another question: i've read, some time ago, this guide > > http://hetland.org/writing/instant-python.html, skipping the > > object-related part. Now i've started reading it, and have found > > something strange: just go where it says "Of course, now you know > > there is a better way. And why don?t we give it the default value of > > [] in the first place? Because of the way Python works, this would > > give all the Baskets the same empty list as default contents.". Can > > you please help me understanding this part? > > When you declare a default value in a function like this: > > def f(a, b, c=SOMETHING): > > the expression SOMETHING is calculated once, when the function is > defined, and *not* each time you call the function. > > So if I do this: > > x = 1 > y = 2 > > def f(a, b, c=x+y): > return a+b+c > > the default value for c is calculated once, and stored inside the > function: > > >>> f(0, 0) > 3 > > Even if I change x or y: > > >>> x = 9999 > >>> f(0, 0) > 3 > > So if I use a list as a default value (or a dict), the default is > calculated once and stored in the function. You can see it by looking > at the function's defaults: > > >>> def f(alist=[]): > ... alist.append(1) > ... return alist > >>> > >>> f.func_defaults[0] > [] > > Now, call the function without an argument: > > >>> f() > [1] > >>> f() > [1, 1] > >>> f() > [1, 1, 1] > >>> f.func_defaults[0] > [1, 1, 1] > > How is this happening? Because every time you call the function, it > appends 1 to the argument. If you don't supply an argument, it appends > 1 to the default, changing it in place. > > Why doesn't the same thing happen here? > > >>> def g(x=0): > ... x += 1 > ... return x > ... > >>> g.func_defaults[0] > 0 > >>> g() > 1 > >>> g() > 1 > >>> g.func_defaults[0] > 0 > > The answer is that ints are immutable: you can't change their value. > When you do x+=1, it doesn't modify the int 0 in place, turning it into > 1. It leaves 0 as zero, and gives you a new int equal to one. So the > default value stored in the function never changes. > > The difference boils down to immutable objects, which can't be changed > in place, and mutable objects, which can. > > Immutable: > ints, floats, strings, tuples, frozensets > > Mutable: > lists, dicts, sets, most custom classes > > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Feb 22 15:29:28 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 22 Feb 2010 09:29:28 -0500 Subject: [Tutor] Functions returning multiple values In-Reply-To: <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> Message-ID: <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> On Mon, Feb 22, 2010 at 9:13 AM, Giorgio wrote: > And, i have some difficulties understanding the other "strange" example in > that howto. Just scroll down to: "However, the?point?is that the value > of?x?is picked up from the?environment?at the time when the function is > defined. How is this useful? Let?s take an example ? a function which > composes two other functions." > He is working on a function that compose other 2 functions. This is the > final solution > def compose(fun1, fun2): > ?? ?def inner(x, fun1=fun1, fun2=fun2): > ?? ? ? ?return fun1(fun2(x)) > ?? ?return inner > But also tries to explain why this example: > # Wrong version > def compose(fun1, fun2): > ?? ?def inner(x): > ?? ? ? ?return fun1(fun2(x)) > ?? ?return inner > def fun1(x): > ?? ?return x + " world!" > def fun2(x): > ?? ?return "Hello," > sincos = compose(sin,cos) ?# Using the wrong version > x = sincos(3) > Won't work. Now, the problem is that the "inner" function gets fun1 and fun2 > from other 2 functions. > My question is: why? inner is a sub-function of compose, where fun1 and fun2 > are defined. It does work: In [6]: def compose(fun1, fun2): ...: def inner(x): ...: return fun1(fun2(x)) ...: return inner ...: In [7]: def fun1(x): ...: return x + " world!" ...: In [8]: def fun2(x): ...: return "Hello," ...: In [9]: from math import sin, cos In [10]: sincos = compose(sin,cos) # Using the wrong version In [11]: In [12]: x = sincos(3) In [13]: In [14]: x Out[14]: -0.8360218615377305 That is a very old example, from python 2.1 or before where nested scopes were not supported. See the note "A Note About Python 2.1 and Nested Scopes" - that is now the default behaviour. Kent From anothernetfellow at gmail.com Mon Feb 22 15:36:44 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Mon, 22 Feb 2010 15:36:44 +0100 Subject: [Tutor] Functions returning multiple values In-Reply-To: <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> Message-ID: <23ce85921002220636s6d363cagc1ba786a2271d523@mail.gmail.com> Ahah Kent this is amazing. I was reading the ITALIAN http://www.python.it/doc/articoli/instpy-0.html version of that guide that is not updated. But, when i decided to post there i've posted the link of the guide in english, but actually that's not what i've readen. Ok, so in the new python version it works. Tha manual also states that: "The features recognized by Python 2.6 are unicode_literals, print_function, absolute_import, division, generators, nested_scopes andwith_statement. generators, with_statement, nested_scopes are redundant in Python version 2.6 and above because they are always enabled." Kent, as i'm learning py, can you please spend some words on nested scopes? What are them? And why are supported anymore? And, if i'm not asking you too much: can you plase post an example on how that function can return HEllo World in py 2.6? Thankyou! Giorgio 2010/2/22 Kent Johnson > On Mon, Feb 22, 2010 at 9:13 AM, Giorgio > wrote: > > > And, i have some difficulties understanding the other "strange" example > in > > that howto. Just scroll down to: "However, the point is that the value > > of x is picked up from the environment at the time when the function is > > defined. How is this useful? Let?s take an example ? a function which > > composes two other functions." > > He is working on a function that compose other 2 functions. This is the > > final solution > > def compose(fun1, fun2): > > def inner(x, fun1=fun1, fun2=fun2): > > return fun1(fun2(x)) > > return inner > > But also tries to explain why this example: > > # Wrong version > > def compose(fun1, fun2): > > def inner(x): > > return fun1(fun2(x)) > > return inner > > def fun1(x): > > return x + " world!" > > def fun2(x): > > return "Hello," > > sincos = compose(sin,cos) # Using the wrong version > > x = sincos(3) > > Won't work. Now, the problem is that the "inner" function gets fun1 and > fun2 > > from other 2 functions. > > My question is: why? inner is a sub-function of compose, where fun1 and > fun2 > > are defined. > > It does work: > In [6]: def compose(fun1, fun2): > ...: def inner(x): > ...: return fun1(fun2(x)) > ...: return inner > ...: > > In [7]: def fun1(x): > ...: return x + " world!" > ...: > > In [8]: def fun2(x): > ...: return "Hello," > ...: > > In [9]: from math import sin, cos > > In [10]: sincos = compose(sin,cos) # Using the wrong version > > In [11]: > > In [12]: x = sincos(3) > > In [13]: > > In [14]: x > Out[14]: -0.8360218615377305 > > That is a very old example, from python 2.1 or before where nested > scopes were not supported. See the note "A Note About Python 2.1 and > Nested Scopes" - that is now the default behaviour. > > Kent > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Feb 22 16:12:38 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 22 Feb 2010 07:12:38 -0800 Subject: [Tutor] "Two" Card Monty with File Operations--Reading from Wrong Folder (W7?) !!! In-Reply-To: <4B81FA22.4020009@sbcglobal.net> References: <4B81FA22.4020009@sbcglobal.net> Message-ID: <4B829EE6.2080206@sbcglobal.net> Well, it looks very much like my stab in the dark is very much correct ( see end of msg below). I changed the name of the file in the folder from which I copied the file to place elsewhere. When I tried to open the file, it started searching for the file.Properties clearly shows it pointing to the wrong file. Good grief. What has Win7 brought? On 2/21/2010 7:29 PM, Wayne Watson wrote: > ... > > The question is why does Report see the folder in the wrong folder? > Although I think I've verified matters, I could be off. Is there a > way to ensure I'm really getting to the right folder? There may be a > Win7 problem here. See below. > > Here's a diagram that might help. Cap names means folder. > > BINGO > EVENTS > a1.txt > a2.txt > report.py > > CARDS > track.py > EVENTS > b1.txt > b2.txt > b3.txt > > Now copy report.py to CARDS > > BINGO > EVENTS > a1.txt > a2.txt > report.py > > CARDS > track.py > EVENTS > b1.txt > b2.txt > b3.txt > report.py > > While working on this problem, I came up with a Win7 puzzler. It > amounts to this. If I search for files in EVENTS of CARDS for "b", it > only finds one of the b-files. I had a long 1 hour talk with HP tech > support. They had no answer, but will take it up with MS. It may be > related to the first problem. Probably not, but curious. I suspect > that Win7's new folder search has somehow used a filter. I had no idea > of any filter use until I accidentally found it in W7 Help. Perhaps > the filter was some how set. Not by me. > > Here's a stab in the dark. Maybe the copied report.py really is a > pointer to the other one? > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From jojo.mwebaze at gmail.com Mon Feb 22 16:57:37 2010 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Mon, 22 Feb 2010 16:57:37 +0100 Subject: [Tutor] generating coordinates between two pairs Message-ID: <3124be321002220757g709d5648u9a399d34a8de4090@mail.gmail.com> Hello There, I got two pairs of coordinates say (4,5) and (7,9) from these two pairs i would like to generate two lists [4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7] and [5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9] i am actually generating all coordinates that fall within (4,5) and (7,9) Any help cheers Johnson -------------- next part -------------- An HTML attachment was scrubbed... URL: From jojo.mwebaze at gmail.com Mon Feb 22 17:03:20 2010 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Mon, 22 Feb 2010 17:03:20 +0100 Subject: [Tutor] generating coordinates between two pairs In-Reply-To: <3124be321002220757g709d5648u9a399d34a8de4090@mail.gmail.com> References: <3124be321002220757g709d5648u9a399d34a8de4090@mail.gmail.com> Message-ID: <3124be321002220803y2621c8aey7fed88d61b6ee834@mail.gmail.com> sorry guys, i found a solution, ignore the post cheers Johnson On Mon, Feb 22, 2010 at 4:57 PM, Jojo Mwebaze wrote: > Hello There, > > I got two pairs of coordinates say (4,5) and (7,9) from these two pairs i > would like to generate two lists > > [4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7] > > and > > [5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9] > > i am actually generating all coordinates that fall within (4,5) and (7,9) > > Any help > > cheers > > Johnson > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Mon Feb 22 17:07:13 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 22 Feb 2010 21:37:13 +0530 Subject: [Tutor] generating coordinates between two pairs In-Reply-To: <3124be321002220803y2621c8aey7fed88d61b6ee834@mail.gmail.com> References: <3124be321002220757g709d5648u9a399d34a8de4090@mail.gmail.com> <3124be321002220803y2621c8aey7fed88d61b6ee834@mail.gmail.com> Message-ID: >>> [(i,j) for i in range(4, 5+1) for j in range(7, 9+1)] [(4, 7), (4, 8), (4, 9), (5, 7), (5, 8), (5, 9)] On Mon, Feb 22, 2010 at 9:33 PM, Jojo Mwebaze wrote: > sorry guys, i found a solution, ignore the post > > cheers > > Johnson > > > On Mon, Feb 22, 2010 at 4:57 PM, Jojo Mwebaze wrote: > >> Hello There, >> >> I got two pairs of coordinates say (4,5) and (7,9) from these two pairs i >> would like to generate two lists >> >> [4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7] >> >> and >> >> [5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9] >> >> i am actually generating all coordinates that fall within (4,5) and (7,9) >> >> Any help >> >> cheers >> >> Johnson >> >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Feb 22 18:25:34 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 22 Feb 2010 18:25:34 +0100 Subject: [Tutor] Reading large bz2 Files In-Reply-To: <4B7E871F.10702@smash-net.org> References: <4B7E871F.10702@smash-net.org> Message-ID: Norman Rie?, 19.02.2010 13:42: > i am trying to read a large bz2 file with this code: > > source_file = bz2.BZ2File(file, "r") > for line in source_file: > print line.strip() > > But after 4311 lines, it stoppes without a errormessage. The bz2 file is > much bigger though. Could you send in a copy of the unpacked bytes around the position where it stops? I.e. a couple of lines before and after that position? Note that bzip2 is a block compressor, so, depending on your data, you may have to send enough lines to fill the block size. Does it also stop if you parse only those lines from a bzip2 file, or is it required that the file has at least the current amount of data before those lines? Based on this, could you please do a bit of poking around yourself to figure out if it is a) the byte position, b) the data content or c) the length of the file that induces this behaviour? I assume it's rather unpractical to share the entire file, so you will have to share hints and information instead if you want this resolved. Stefan From zebra05 at gmail.com Mon Feb 22 20:30:40 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Mon, 22 Feb 2010 21:30:40 +0200 Subject: [Tutor] Python file escaping issue? In-Reply-To: <201002221001.06549.steve@pearwood.info> References: <201002221001.06549.steve@pearwood.info> Message-ID: Wow, thank you Steve. This certainly answers a few questions i've had simmering for a while. On Mon, Feb 22, 2010 at 1:01 AM, Steven D'Aprano wrote: > On Mon, 22 Feb 2010 05:22:10 am Sithembewena Lloyd Dube wrote: > > Hi all, > > > > I'm trying to read a file (Python 2.5.2, Windows XP) as follows: > > > > assignment_file = open('C:\Documents and Settings\coderoid\My > > Documents\Downloads\code_sample.txt', 'r+').readlines() > > new_file = open(new_file.txt, 'w+') > > for line in assignment_file: > > new_file.write(line) > > > > new_file.close() > > assignment_file.close() > > > > When the code runs, the file path has the slashes converted to double > > slashes. When try to escape them, i just seemto add more slashes. > > What am i missing? > > An understanding of how backslash escapes work in Python. > > Backslashes in string literals (but not in text you read from a file, > say) are used to inject special characters into the string, just like C > and other languages do. These backslash escapes include: > > \t tab > \n newline > \f formfeed > \\ backslash > > and many others. Any other non-special backslash is left alone. > > So when you write a string literal including backslashes and a special > character, you get this: > > >>> s = 'abc\tz' # tab > >>> print s > abc z > >>> print repr(s) > 'abc\tz' > >>> len(s) > 5 > > But if the escape is not a special character: > > >>> s = 'abc\dz' # nothing special > >>> print s > abc\dz > >>> print repr(s) > 'abc\\dz' > >>> len(s) > 6 > > The double backslash is part of the *display* of the string, like the > quotation marks, and not part of the string itself. The string itself > only has a single backslash and no quote marks. > > So if you write a pathname like this: > > >>> path = 'C:\datafile.txt' > >>> print path > C:\datafile.txt > >>> len(path) > 15 > > It *seems* to work, because \d is left as backlash-d. But then you do > this, and wonder why you can't open the file: > > >>> path = 'C:\textfile.txt' > >>> print path > C: extfile.txt > >>> len(path) > 14 > > > Some people recommend using raw strings. Raw strings turn off backslash > processing, so you can do this: > > >>> path = r'C:\textfile.txt' > >>> print path > C:\textfile.txt > > But raw strings were invented for the regular expression module, not for > Windows pathnames, and they have a major limitation: you can't end a > raw string with a backslash. > > >>> path = r'C:\directory\' > File "", line 1 > path = r'C:\directory\' > ^ > SyntaxError: EOL while scanning single-quoted string > > > The best advice is to remember that Windows allows both forward and > backwards slashes as the path separator, and just write all your paths > using the forward slash: > > 'C:/directory/' > 'C:textfile.txt' > > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Mon Feb 22 20:35:00 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Mon, 22 Feb 2010 21:35:00 +0200 Subject: [Tutor] Python file escaping issue? In-Reply-To: <20100222083721.32bb957f@o> References: <201002221001.06549.steve@pearwood.info> <20100222083721.32bb957f@o> Message-ID: @spr, thanks for the explanation, especially on representations of strings. To think that i freely used repr(variable_x) without fully understanding the meaning and the power of that function.. On Mon, Feb 22, 2010 at 9:37 AM, spir wrote: > Just a little complement to Steven's excellent explanation: > > On Mon, 22 Feb 2010 10:01:06 +1100 > Steven D'Aprano wrote: > > [...] > > > So if you write a pathname like this: > > > > >>> path = 'C:\datafile.txt' > > >>> print path > > C:\datafile.txt > > >>> len(path) > > 15 > > > > It *seems* to work, because \d is left as backlash-d. But then you do > > this, and wonder why you can't open the file: > > I consider this misleading, since it can only confuse newcomers. Maybe > "lonely" single backslashes (not forming a "code" with following > character(s)) should be invalid. Meaning literal backslashes would always be > doubled (in plain, non-raw, strings). What do you think? > > > But if the escape is not a special character: > > > > >>> s = 'abc\dz' # nothing special > > >>> print s > > abc\dz > > >>> print repr(s) > > 'abc\\dz' > > >>> len(s) > > 6 > > > > The double backslash is part of the *display* of the string, like the > > quotation marks, and not part of the string itself. The string itself > > only has a single backslash and no quote marks. > > This "display" is commonly called "representation", thus the name of the > function repr(). It is a string representation *for the programmer* only, > both on input and output: > * to allow one writing, in code itself, string literal constants containing > special characters, in a practical manner (eg file pathes/names) > * to allow one checking the actual content of string values, at testing > time > > The so-called interactive interpreter outputs representations by default. > An extreme case: > >>> s = "\\" > >>> s > '\\' > >>> print s, len(s) > \ 1 > >>> print repr(s), len(repr(s)) > '\\' 4 > >>> > The string holds 1 char; its representation (also a string, indeed) holds > 4. > > > The best advice is to remember that Windows allows both forward and > > backwards slashes as the path separator, and just write all your paths > > using the forward slash: > > > > 'C:/directory/' > > 'C:textfile.txt' > > Another solution is to take the habit to always escape '\' by doubling it. > > > Denis > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Mon Feb 22 20:36:18 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Mon, 22 Feb 2010 21:36:18 +0200 Subject: [Tutor] Python file escaping issue? In-Reply-To: References: <201002221001.06549.steve@pearwood.info> <20100222083721.32bb957f@o> Message-ID: I believe i encountered repr()in the Python tutorial, but i had not kept the relevance of it in my memory.. On Mon, Feb 22, 2010 at 9:35 PM, Sithembewena Lloyd Dube wrote: > @spr, thanks for the explanation, especially on representations of strings. > To think that i freely used repr(variable_x) without fully understanding the > meaning and the power of that function.. > > > > > On Mon, Feb 22, 2010 at 9:37 AM, spir wrote: > >> Just a little complement to Steven's excellent explanation: >> >> On Mon, 22 Feb 2010 10:01:06 +1100 >> Steven D'Aprano wrote: >> >> [...] >> >> > So if you write a pathname like this: >> > >> > >>> path = 'C:\datafile.txt' >> > >>> print path >> > C:\datafile.txt >> > >>> len(path) >> > 15 >> > >> > It *seems* to work, because \d is left as backlash-d. But then you do >> > this, and wonder why you can't open the file: >> >> I consider this misleading, since it can only confuse newcomers. Maybe >> "lonely" single backslashes (not forming a "code" with following >> character(s)) should be invalid. Meaning literal backslashes would always be >> doubled (in plain, non-raw, strings). What do you think? >> >> > But if the escape is not a special character: >> > >> > >>> s = 'abc\dz' # nothing special >> > >>> print s >> > abc\dz >> > >>> print repr(s) >> > 'abc\\dz' >> > >>> len(s) >> > 6 >> > >> > The double backslash is part of the *display* of the string, like the >> > quotation marks, and not part of the string itself. The string itself >> > only has a single backslash and no quote marks. >> >> This "display" is commonly called "representation", thus the name of the >> function repr(). It is a string representation *for the programmer* only, >> both on input and output: >> * to allow one writing, in code itself, string literal constants >> containing special characters, in a practical manner (eg file pathes/names) >> * to allow one checking the actual content of string values, at testing >> time >> >> The so-called interactive interpreter outputs representations by default. >> An extreme case: >> >>> s = "\\" >> >>> s >> '\\' >> >>> print s, len(s) >> \ 1 >> >>> print repr(s), len(repr(s)) >> '\\' 4 >> >>> >> The string holds 1 char; its representation (also a string, indeed) holds >> 4. >> >> > The best advice is to remember that Windows allows both forward and >> > backwards slashes as the path separator, and just write all your paths >> > using the forward slash: >> > >> > 'C:/directory/' >> > 'C:textfile.txt' >> >> Another solution is to take the habit to always escape '\' by doubling it. >> >> >> Denis >> ________________________________ >> >> la vita e estrany >> >> http://spir.wikidot.com/ >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Regards, > Sithembewena Lloyd Dube > http://www.lloyddube.com > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From anto.buzzelli at gmail.com Mon Feb 22 21:50:12 2010 From: anto.buzzelli at gmail.com (Antonio Buzzelli) Date: Mon, 22 Feb 2010 21:50:12 +0100 Subject: [Tutor] Encryption Message-ID: <38a6772e1002221250m6ea18551o1d562efc98407d64@mail.gmail.com> Hi everyone! I need a simple way to encrypt and decrypt some strings with a key someone can help me?? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Feb 22 22:00:03 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 22 Feb 2010 15:00:03 -0600 Subject: [Tutor] Encryption In-Reply-To: <38a6772e1002221250m6ea18551o1d562efc98407d64@mail.gmail.com> References: <38a6772e1002221250m6ea18551o1d562efc98407d64@mail.gmail.com> Message-ID: <333efb451002221300u728f0c62sbdc0f67f1d402929@mail.gmail.com> On Mon, Feb 22, 2010 at 2:50 PM, Antonio Buzzelli wrote: > Hi everyone! > I need a simple way to encrypt and decrypt some strings with a key > > someone can help me?? I'm sure someone can. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Mon Feb 22 22:22:04 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Tue, 23 Feb 2010 02:52:04 +0530 Subject: [Tutor] Encryption In-Reply-To: <333efb451002221300u728f0c62sbdc0f67f1d402929@mail.gmail.com> References: <38a6772e1002221250m6ea18551o1d562efc98407d64@mail.gmail.com> <333efb451002221300u728f0c62sbdc0f67f1d402929@mail.gmail.com> Message-ID: how about using base64? base64.encodestring(s) will do. On Tue, Feb 23, 2010 at 2:30 AM, Wayne Werner wrote: > On Mon, Feb 22, 2010 at 2:50 PM, Antonio Buzzelli > wrote: > >> Hi everyone! >> I need a simple way to encrypt and decrypt some strings with a key >> >> someone can help me?? > > > I'm sure someone can. > > -Wayne > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From la.foma at gmail.com Mon Feb 22 22:48:11 2010 From: la.foma at gmail.com (J) Date: Mon, 22 Feb 2010 16:48:11 -0500 Subject: [Tutor] Searchlight/MVPA/ValueError Message-ID: <7e1994871002221348mdf0090o4ed920256efc5409@mail.gmail.com> Dear all, I am trying to run a very simple searchlight on fMRI data via PyLab (on Mac Leopard). My code is as follows: from mvpa.suite import * import os from matplotlib.pyplot import figure, show from mvpa.misc.io.base import SampleAttributes from mvpa.datasets.nifti import NiftiDataset if __debug__: debug.active += ["SLC"] attr = SampleAttributes(os.path.join(pymvpa_dataroot, 'attributes_test.txt')) dataset = NiftiDataset(samples=os.path.join(pymvpa_dataroot, 'time_series_original_run_all.nii.gz'), labels=attr.labels, chunks=attr.chunks, mask=os.path.join(pymvpa_dataroot, 'anatomy_mask.nii.gz')) detrend(dataset, perchunk=True, model='linear') zscore(dataset, perchunk=True, baselinelabels=[1], targetdtype='float32') # choose classifier clf = LinearCSVMC() # setup measure to be computed by Searchlight # cross-validated mean transfer using an Odd-Even dataset splitter cv = CrossValidatedTransferError(TransferError(clf), OddEvenSplitter()) cv = CrossValidatedTransferError( transfer_error=TransferError(LinearCSVMC(), splitter=OddEvenSplitter()) s1 = Searchlight(cv, radius=5) s1_map = s1(dataset) dataset.map2Nifti(s1_map).save('searchlight_5mm.nii.gz') --- this runs fine for a while and then it crashes and gives me the following errors which I am not sure what they mean. optimization finished, #iter = 59 nu = 0.775000 obj = -0.000003, rho = -0.999986 nSV = 67, nBSV = 57 Total nSV = 414 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/ in () /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/base.pyc in __call__(self, dataset) 103 container applying transformer if such is defined 104 """ --> 105 result = self._call(dataset) 106 result = self._postcall(dataset, result) 107 return result /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/searchlight.pyc in _call(self, dataset) 106 107 # compute the datameasure and store in results --> 108 measure = self.__datameasure(sphere) 109 results.append(measure) 110 /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/base.pyc in __call__(self, dataset) 103 container applying transformer if such is defined 104 """ --> 105 result = self._call(dataset) 106 result = self._postcall(dataset, result) 107 return result /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/algorithms/cvtranserror.pyc in _call(self, dataset) 171 172 # run the beast --> 173 result = transerror(split[1], split[0]) 174 175 # unbind the testdataset from the classifier /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/transerror.pyc in __call__(self, testdataset, trainingdataset) 1300 Returns a scalar value of the transfer error. 1301 """ -> 1302 self._precall(testdataset, trainingdataset) 1303 error = self._call(testdataset, trainingdataset) 1304 self._postcall(testdataset, trainingdataset, error) /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/transerror.pyc in _precall(self, testdataset, trainingdataset) 1256 self.__clf.states._changeTemporarily( 1257 enable_states=['training_confusion']) -> 1258 self.__clf.train(trainingdataset) 1259 if self.states.isEnabled('training_confusion'): 1260 self.training_confusion = self.__clf.training_confusion /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/base.pyc in train(self, dataset) 366 367 if dataset.nfeatures > 0: --> 368 result = self._train(dataset) 369 else: 370 warning("Trying to train on dataset with no features present") /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/libsvmc/svm.pyc in _train(self, dataset) 185 libsvm_param._setParameter('weight', weight) 186 --> 187 self.__model = svm.SVMModel(svmprob, libsvm_param) 188 189 /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/libsvmc/_svm.pyc in __init__(self, arg1, arg2) 267 msg = svmc.svm_check_parameter(prob.prob, param.param) 268 if msg: --> 269 raise ValueError, msg 270 self.model = svmc.svm_train(prob.prob, param.param) 271 ValueError: C <= 0 ------- Your input would be greatly appreciated. Thanks a lot, J -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 22 23:22:08 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Feb 2010 22:22:08 -0000 Subject: [Tutor] Drawing faces References: <169753.28451.qm@web27102.mail.ukl.yahoo.com> Message-ID: "Olufemi Onanuga" wrote > I am trying to write and test a function to meet the following > specifications > > drawFace(center,size,win),center is a point,size is an int, > and win is a GraphWin.Draws a simple face of the given size in win. > > I want the function to be able to draw three differnet faces in a single > window,when i invoke drawFace(center,size,win) into def main(). Good for you. It sounds like an excellent practice exercise in using a GUI toolkit. (Or even ASCII art in curses!) BTW Which GUI toolkit are you using? And which widget within it? Is it the Canvas in Tkinter? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From cmcaine at googlemail.com Mon Feb 22 23:10:15 2010 From: cmcaine at googlemail.com (C M Caine) Date: Mon, 22 Feb 2010 22:10:15 +0000 Subject: [Tutor] Strange list behaviour in classes Message-ID: Or possibly strange list of object behaviour IDLE 2.6.2 >>> class Player(): hand = [] >>> Colin = Player() >>> Alex = Player() >>> >>> Players = [Colin, Alex] >>> >>> def hands(): for player in Players: player.hand.append("A") >>> hands() >>> >>> Colin.hand ['A', 'A'] >>> Alex.hand ['A', 'A'] I would have expected hand for each object to be simply ['A']. Why does this not occur and how would I implement the behaviour I expected/want? Thanks in advance for your help, Colin Caine From modulok at gmail.com Mon Feb 22 23:34:37 2010 From: modulok at gmail.com (Modulok) Date: Mon, 22 Feb 2010 15:34:37 -0700 Subject: [Tutor] Encryption In-Reply-To: References: <38a6772e1002221250m6ea18551o1d562efc98407d64@mail.gmail.com> <333efb451002221300u728f0c62sbdc0f67f1d402929@mail.gmail.com> Message-ID: <64c038661002221434i4d0ad8cbp7cc097ec64105077@mail.gmail.com> >> I need a simple way to encrypt and decrypt some strings with a key. Did you have any other requirements? Any specific algorithms or key lengths? If you need real encryption, you might check out a 3rd party module named 'PyCrypto'. It offers an implementation of the AES algorithm. A less eloquent approach - you could also wrap the Unix command 'openssl' with a python process. Whether you can get these libraries will depend on where you live. Strong encryption is still strictly controlled in some regions. There are code examples in the 'README' file of pycrypto. There are probably other AES implementations out there as well. However, the only FIPS certified library I know of is openssl. -Modulok- On 2/22/10, Shashwat Anand wrote: > how about using base64? base64.encodestring(s) will do. > > > > On Tue, Feb 23, 2010 at 2:30 AM, Wayne Werner wrote: > >> On Mon, Feb 22, 2010 at 2:50 PM, Antonio Buzzelli > > wrote: >> >>> Hi everyone! >>> I need a simple way to encrypt and decrypt some strings with a key >>> >>> someone can help me?? >> >> >> I'm sure someone can. >> >> -Wayne >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > From steve at pearwood.info Tue Feb 23 00:10:31 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 23 Feb 2010 10:10:31 +1100 Subject: [Tutor] Encryption In-Reply-To: <38a6772e1002221250m6ea18551o1d562efc98407d64@mail.gmail.com> References: <38a6772e1002221250m6ea18551o1d562efc98407d64@mail.gmail.com> Message-ID: <201002231010.32224.steve@pearwood.info> On Tue, 23 Feb 2010 07:50:12 am Antonio Buzzelli wrote: > Hi everyone! > I need a simple way to encrypt and decrypt some strings with a key > > someone can help me?? > > Thanks. I am the author of this package which might be enough for you: http://pypi.python.org/pypi/obfuscate/ If all you want is to "hide" some text from casual snoopers (say, to hide strings in a game so that people can't just open the game in a hex editor and read the game messages) then obfuscate may be enough. I can't emphasis this enough: the encryption algorithms in obfuscate are not up to modern standards and are NOT cryptographically secure. Do not use this where serious security is required. Otherwise, google for "python encryption". You might also like to ask on the Python newsgroup comp.lang.python for advice. -- Steven D'Aprano From transmogribenno at gmail.com Tue Feb 23 00:16:16 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Tue, 23 Feb 2010 08:16:16 +0900 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: References: Message-ID: <9b00d1a91002221516u65ff738ck606b93592ba19831@mail.gmail.com> On 23 February 2010 07:10, C M Caine wrote: > Or possibly strange list of object behaviour > > IDLE 2.6.2 >>>> class Player(): > ? ? ? ?hand = [] > > >>>> Colin = Player() >>>> Alex = Player() >>>> >>>> Players = [Colin, Alex] >>>> >>>> def hands(): > ? ? ? ?for player in Players: > ? ? ? ? ? ? ? ?player.hand.append("A") > >>>> hands() >>>> >>>> Colin.hand > ['A', 'A'] >>>> Alex.hand > ['A', 'A'] > > I would have expected hand for each object to be simply ['A']. Why > does this not occur and how would I implement the behaviour I > expected/want? What you're accessing via Colin.hand and Alex.hand is actually Player.hand, which is a class attribute. You want to set up attributes on your instance objects instead; the standard way to do this is by adding an __init__ method to your class: class Hand: def __init__(self): self.hand = [] For more information, I suggest: http://docs.python.org/tutorial/classes.html HTH, benno From transmogribenno at gmail.com Tue Feb 23 00:18:07 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Tue, 23 Feb 2010 08:18:07 +0900 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: <9b00d1a91002221516u65ff738ck606b93592ba19831@mail.gmail.com> References: <9b00d1a91002221516u65ff738ck606b93592ba19831@mail.gmail.com> Message-ID: <9b00d1a91002221518q7189002rb8f2ef29c538bed0@mail.gmail.com> On 23 February 2010 08:16, Benno Lang wrote: > class Hand: > ? ?def __init__(self): > ? ? ? ?self.hand = [] Of course, I meant "class Player" From waynejwerner at gmail.com Tue Feb 23 00:28:28 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 22 Feb 2010 17:28:28 -0600 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: References: Message-ID: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> On Mon, Feb 22, 2010 at 4:10 PM, C M Caine wrote: > Or possibly strange list of object behaviour > > IDLE 2.6.2 > >>> class Player(): > hand = [] > > > >>> Colin = Player() > >>> Alex = Player() > >>> > >>> Players = [Colin, Alex] > >>> > >>> def hands(): > for player in Players: > player.hand.append("A") > > >>> hands() > >>> > >>> Colin.hand > ['A', 'A'] > >>> Alex.hand > ['A', 'A'] > > I would have expected hand for each object to be simply ['A']. Why > does this not occur and how would I implement the behaviour I > expected/want? > > Thanks in advance for your help, > Colin Caine This comes from the nature of the list object. Python lists are pass/shared as reference objects. In your case, both Colin and Alex are pointing to the Player object's copy of hands - they both get a reference to the same object. If you want to create different hand lists you could do something like this: class Player: def __init__(self, hand=None): if isinstance(hand, list): self.hand = hand else: print "Player needs a list object for its hand!" ex: In [11]: Alan = Player() Player needs a list object for its hand! In [12]: Alan = Player([]) In [13]: Jim = Player([]) In [14]: Alan.hand.append(3) In [15]: Jim.hand Out[15]: [] HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at vincentdavis.net Tue Feb 23 05:50:07 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Mon, 22 Feb 2010 21:50:07 -0700 Subject: [Tutor] list to numpy record array Message-ID: <77e831101002222050xf2d90cfm16ef27160a2639ea@mail.gmail.com> I must be missing something simple. I have a list of lists data = "[[' 0', ' 0', '234.0', '24.0', ' 25'], [' 1', ' 0', '22428.0', '2378.1', ' 25'],......" and what to make a record array from it but it gets screwed up or I don't get it, maybe both. Notice that at this stage the items are strings, not numbers, and there is whitespace not sure this matters. Here is what is happening adata = numpy.array(data,numpy.float64) >>> adata array([[ 0.00000000e+00, 0.00000000e+00, 2.34000000e+02, 2.40000000e+01, 2.50000000e+01], ..., [ 4.77000000e+02, 4.77000000e+02, 2.07000000e+02, 4.58000000e+01, 2.50000000e+01]]) This is what I would expect except it is not a record array. This is not what I expect. I think I have tried every iteration including using numpy dtaypes numpy.int32 or bdata = numpy.array(data, dtype = [('x', int),('y', int),('mean',float),('stdv',float),('npixcels',int)]) What am I missing? bdata = numpy.array(data, [('x', int),('y', int),('mean',float),('stdv',float),('npixcels',int)]) >>> bdata array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), (206933603122, 0, 0.0, 0.0, 0), (808334386, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)], [(3219488, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), (13561617777439282, 0, 0.0, 0.0, 0), (54074581398322, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)], [(3285024, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), (206933931058, 0, 0.0, 0.0, 0), (925775666, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)], ..., [(3487540, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0), (206933602866, 0, 0.0, 0.0, 0), (908996661, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)], [(3553076, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0), (13561596370041137, 0, 0.0, 0.0, 0), (62870573495603, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)], [(3618612, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0), (206933798962, 0, 0.0, 0.0, 0), (942552372, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)]], dtype=[('x', ' | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From anothernetfellow at gmail.com Tue Feb 23 13:13:07 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Tue, 23 Feb 2010 13:13:07 +0100 Subject: [Tutor] Functions returning multiple values In-Reply-To: <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> Message-ID: <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> I have an update: I can easily undertand why this example doesn't work: def nochange(x): x = 0 y = 1 nochange(y) print y # Prints out 1 X is a local variable, and only gets modified in the function, that doesn't return any value. But it's very difficult for me to understand WHY this works: def change(some_list): some_list[1] = 4 x = [1,2,3] change(x) print x # Prints out [1,4,3] some_list is a "local" list, isn't it? Maybe i can't have lists that are only existing in a function? Thankyou all 2010/2/22 Kent Johnson > On Mon, Feb 22, 2010 at 9:13 AM, Giorgio > wrote: > > > And, i have some difficulties understanding the other "strange" example > in > > that howto. Just scroll down to: "However, the point is that the value > > of x is picked up from the environment at the time when the function is > > defined. How is this useful? Let?s take an example ? a function which > > composes two other functions." > > He is working on a function that compose other 2 functions. This is the > > final solution > > def compose(fun1, fun2): > > def inner(x, fun1=fun1, fun2=fun2): > > return fun1(fun2(x)) > > return inner > > But also tries to explain why this example: > > # Wrong version > > def compose(fun1, fun2): > > def inner(x): > > return fun1(fun2(x)) > > return inner > > def fun1(x): > > return x + " world!" > > def fun2(x): > > return "Hello," > > sincos = compose(sin,cos) # Using the wrong version > > x = sincos(3) > > Won't work. Now, the problem is that the "inner" function gets fun1 and > fun2 > > from other 2 functions. > > My question is: why? inner is a sub-function of compose, where fun1 and > fun2 > > are defined. > > It does work: > In [6]: def compose(fun1, fun2): > ...: def inner(x): > ...: return fun1(fun2(x)) > ...: return inner > ...: > > In [7]: def fun1(x): > ...: return x + " world!" > ...: > > In [8]: def fun2(x): > ...: return "Hello," > ...: > > In [9]: from math import sin, cos > > In [10]: sincos = compose(sin,cos) # Using the wrong version > > In [11]: > > In [12]: x = sincos(3) > > In [13]: > > In [14]: x > Out[14]: -0.8360218615377305 > > That is a very old example, from python 2.1 or before where nested > scopes were not supported. See the note "A Note About Python 2.1 and > Nested Scopes" - that is now the default behaviour. > > Kent > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Feb 23 13:30:32 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 23 Feb 2010 14:30:32 +0200 Subject: [Tutor] Functions returning multiple values In-Reply-To: <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> Message-ID: <4B83CA68.1020505@compuscan.co.za> Giorgio wrote: > I have an update: > > I can easily undertand why this example doesn't work: > > def nochange(x): > x = 0 > > y = 1 > nochange(y) > print y # Prints out 1 > > X is a local variable, and only gets modified in the function, that > doesn't return any value. > > But it's very difficult for me to understand WHY this works: > > def change(some_list): > some_list[1] = 4 > > x = [1,2,3] > change(x) > print x # Prints out [1,4,3] > > some_list is a "local" list, isn't it? Maybe i can't have lists that > are only existing in a function? > > Thankyou all > > 2010/2/22 Kent Johnson > > > On Mon, Feb 22, 2010 at 9:13 AM, Giorgio > > > wrote: > > > And, i have some difficulties understanding the other "strange" > example in > > that howto. Just scroll down to: "However, the point is that the > value > > of x is picked up from the environment at the time when the > function is > > defined. How is this useful? Let?s take an example ? a function > which > > composes two other functions." > > He is working on a function that compose other 2 functions. This > is the > > final solution > > def compose(fun1, fun2): > > def inner(x, fun1=fun1, fun2=fun2): > > return fun1(fun2(x)) > > return inner > > But also tries to explain why this example: > > # Wrong version > > def compose(fun1, fun2): > > def inner(x): > > return fun1(fun2(x)) > > return inner > > def fun1(x): > > return x + " world!" > > def fun2(x): > > return "Hello," > > sincos = compose(sin,cos) # Using the wrong version > > x = sincos(3) > > Won't work. Now, the problem is that the "inner" function gets > fun1 and fun2 > > from other 2 functions. > > My question is: why? inner is a sub-function of compose, where > fun1 and fun2 > > are defined. > > It does work: > In [6]: def compose(fun1, fun2): > ...: def inner(x): > ...: return fun1(fun2(x)) > ...: return inner > ...: > > In [7]: def fun1(x): > ...: return x + " world!" > ...: > > In [8]: def fun2(x): > ...: return "Hello," > ...: > > In [9]: from math import sin, cos > > In [10]: sincos = compose(sin,cos) # Using the wrong version > > In [11]: > > In [12]: x = sincos(3) > > In [13]: > > In [14]: x > Out[14]: -0.8360218615377305 > > That is a very old example, from python 2.1 or before where nested > scopes were not supported. See the note "A Note About Python 2.1 and > Nested Scopes" - that is now the default behaviour. > > Kent > > > > > -- > -- > AnotherNetFellow > Email: anothernetfellow at gmail.com > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Take a look at the Python gothcha's: http://www.ferg.org/projects/python_gotchas.html#contents_item_6 -- Kind Regards, Christian Witts From vorobyov.vladislav at gmail.com Tue Feb 23 13:38:25 2010 From: vorobyov.vladislav at gmail.com (Vladislav Vorobyov) Date: Tue, 23 Feb 2010 14:38:25 +0200 Subject: [Tutor] nonlocal variables Message-ID: #!/usr/bin/python def func_outer(): x = 2 print('x is', x) def func_inner(): nonlocal x x = 5 func_inner() print('Changed local x to', x) func_outer() Output: File "nonlocal_var.py", line 6 nonlocal x ^ SyntaxError: invalid syntax Why? Cannon find in google it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anothernetfellow at gmail.com Tue Feb 23 13:49:03 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Tue, 23 Feb 2010 13:49:03 +0100 Subject: [Tutor] Functions returning multiple values In-Reply-To: <4B83CA68.1020505@compuscan.co.za> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> <4B83CA68.1020505@compuscan.co.za> Message-ID: <23ce85921002230449p1066ee5ctd89ae99b050a8ca6@mail.gmail.com> Thankyou. It's clear, this definitely helps me with the first question. But still doesn't explain almost anything about the example i've posted in the last post, right? Giorgio 2010/2/23 Christian Witts > Giorgio wrote: > >> I have an update: >> >> I can easily undertand why this example doesn't work: >> >> def nochange(x): >> x = 0 >> >> y = 1 >> nochange(y) >> print y # Prints out 1 >> >> X is a local variable, and only gets modified in the function, that >> doesn't return any value. >> >> But it's very difficult for me to understand WHY this works: >> >> def change(some_list): >> some_list[1] = 4 >> >> x = [1,2,3] >> change(x) >> print x # Prints out [1,4,3] >> >> some_list is a "local" list, isn't it? Maybe i can't have lists that are >> only existing in a function? >> >> Thankyou all >> >> 2010/2/22 Kent Johnson > >> >> >> On Mon, Feb 22, 2010 at 9:13 AM, Giorgio >> > >> >> wrote: >> >> > And, i have some difficulties understanding the other "strange" >> example in >> > that howto. Just scroll down to: "However, the point is that the >> value >> > of x is picked up from the environment at the time when the >> function is >> > defined. How is this useful? Let?s take an example ? a function >> which >> > composes two other functions." >> > He is working on a function that compose other 2 functions. This >> is the >> > final solution >> > def compose(fun1, fun2): >> > def inner(x, fun1=fun1, fun2=fun2): >> > return fun1(fun2(x)) >> > return inner >> > But also tries to explain why this example: >> > # Wrong version >> > def compose(fun1, fun2): >> > def inner(x): >> > return fun1(fun2(x)) >> > return inner >> > def fun1(x): >> > return x + " world!" >> > def fun2(x): >> > return "Hello," >> > sincos = compose(sin,cos) # Using the wrong version >> > x = sincos(3) >> > Won't work. Now, the problem is that the "inner" function gets >> fun1 and fun2 >> > from other 2 functions. >> > My question is: why? inner is a sub-function of compose, where >> fun1 and fun2 >> > are defined. >> >> It does work: >> In [6]: def compose(fun1, fun2): >> ...: def inner(x): >> ...: return fun1(fun2(x)) >> ...: return inner >> ...: >> >> In [7]: def fun1(x): >> ...: return x + " world!" >> ...: >> >> In [8]: def fun2(x): >> ...: return "Hello," >> ...: >> >> In [9]: from math import sin, cos >> >> In [10]: sincos = compose(sin,cos) # Using the wrong version >> >> In [11]: >> >> In [12]: x = sincos(3) >> >> In [13]: >> >> In [14]: x >> Out[14]: -0.8360218615377305 >> >> That is a very old example, from python 2.1 or before where nested >> scopes were not supported. See the note "A Note About Python 2.1 and >> Nested Scopes" - that is now the default behaviour. >> >> Kent >> >> >> >> >> -- >> -- >> AnotherNetFellow >> Email: anothernetfellow at gmail.com >> ------------------------------------------------------------------------ >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > Take a look at the Python gothcha's: > http://www.ferg.org/projects/python_gotchas.html#contents_item_6 > > -- > Kind Regards, > Christian Witts > > > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Tue Feb 23 13:50:54 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 23 Feb 2010 13:50:54 +0100 Subject: [Tutor] nonlocal variables In-Reply-To: References: Message-ID: <29179d161002230450o1355fe50tfecc45291483539c@mail.gmail.com> On Tue, Feb 23, 2010 at 1:38 PM, Vladislav Vorobyov wrote: > #!/usr/bin/python > def func_outer(): > ??????? x = 2 > ??????? print('x is', x) > ??????? def func_inner(): > ??????????????? nonlocal x > ??????????????? x = 5 > ??????? func_inner() > ??????? print('Changed local x to', x) > > func_outer() > > Output: > File "nonlocal_var.py", line 6 > ??? nonlocal x > ???????????? ^ > SyntaxError: invalid syntax > Why? Cannon find in google it. > check your python version. The nonlocal keyword is only supported in python 3.x Hugo From vorobyov.vladislav at gmail.com Tue Feb 23 13:57:21 2010 From: vorobyov.vladislav at gmail.com (Vladislav Vorobyov) Date: Tue, 23 Feb 2010 14:57:21 +0200 Subject: [Tutor] nonlocal variables In-Reply-To: <29179d161002230450o1355fe50tfecc45291483539c@mail.gmail.com> References: <29179d161002230450o1355fe50tfecc45291483539c@mail.gmail.com> Message-ID: 2010/2/23 Hugo Arts > On Tue, Feb 23, 2010 at 1:38 PM, Vladislav Vorobyov > wrote: > > #!/usr/bin/python > > def func_outer(): > > x = 2 > > print('x is', x) > > def func_inner(): > > nonlocal x > > x = 5 > > func_inner() > > print('Changed local x to', x) > > > > func_outer() > > > > Output: > > File "nonlocal_var.py", line 6 > > nonlocal x > > ^ > > SyntaxError: invalid syntax > > Why? Cannon find in google it. > > > > check your python version. The nonlocal keyword is only supported in python > 3.x > > Hugo > O! Thank. I'm reading "Byte of Python". Didn't look about what version of python is it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Tue Feb 23 14:22:24 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 23 Feb 2010 14:22:24 +0100 Subject: [Tutor] Functions returning multiple values In-Reply-To: <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> Message-ID: <29179d161002230522g66a062fsb569e3dbf118304e@mail.gmail.com> On Tue, Feb 23, 2010 at 1:13 PM, Giorgio wrote: > I have an update: > I can easily undertand why this example doesn't work: > def nochange(x): > ?? ?x = 0 > y = 1 > nochange(y) > print y # Prints out 1 > X is a local variable, and only gets modified in the function, that doesn't > return any value. > But it's very difficult for me to understand WHY this works: > def change(some_list): > ?? ?some_list[1] = 4 > x = [1,2,3] > change(x) > print x # Prints out [1,4,3] > some_list is a "local" list, isn't it? Maybe i can't have lists that are > only existing in a function? Here is what happens, as I understand it: When you enter the function, a new name (x, in your case) is created in the local scope. That name points to the object you supplied when you called the function (an integer object, with a value of 1). the x = 0 statement creates a new object, and has the name x now pointing to this new object. The old integer object still exists, and y still points to it. This is why the global y name is not affected by the change in x Now, in the second example, the same thing basically happens. A new name is created and pointed at the object you supplied. However, the statement some_list[1] = 4 is different from the assignment, in that it doesn't create a new object; It modifies the existing one. Since the global and local names both point to the same object, the change you make is reflected in both. You can of course create a new list object, so that the original is not affected: def nochange(some_list): # create shallow copy of list. NOTE: Shallow copies may still bite you if you change the list members. some_list = some_list[:] some_list[1] = 2 >>> x = [1, 2, 3] >>> nochange(x) >>> x [1, 2, 3] HTH, Hugo From anothernetfellow at gmail.com Tue Feb 23 14:28:33 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Tue, 23 Feb 2010 14:28:33 +0100 Subject: [Tutor] Functions returning multiple values In-Reply-To: <29179d161002230522g66a062fsb569e3dbf118304e@mail.gmail.com> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> <29179d161002230522g66a062fsb569e3dbf118304e@mail.gmail.com> Message-ID: <23ce85921002230528m53c11513yfc0a0dd10eea2221@mail.gmail.com> Thankyou Hugo! Ok, so i think the key is of my problem is that when doing X = 0 i'm creating a new object, that only exist in the local namespace. BUT, when using a list as a parameter for a function i'm only giving it a new name, but the object it's referring to it's always the same, and is in the global namespace. Right? 2010/2/23 Hugo Arts > On Tue, Feb 23, 2010 at 1:13 PM, Giorgio > wrote: > > I have an update: > > I can easily undertand why this example doesn't work: > > def nochange(x): > > x = 0 > > y = 1 > > nochange(y) > > print y # Prints out 1 > > X is a local variable, and only gets modified in the function, that > doesn't > > return any value. > > But it's very difficult for me to understand WHY this works: > > def change(some_list): > > some_list[1] = 4 > > x = [1,2,3] > > change(x) > > print x # Prints out [1,4,3] > > some_list is a "local" list, isn't it? Maybe i can't have lists that are > > only existing in a function? > > Here is what happens, as I understand it: > When you enter the function, a new name (x, in your case) is created > in the local scope. That name points to the object you supplied when > you called the function (an integer object, with a value of 1). the x > = 0 statement creates a new object, and has the name x now pointing to > this new object. The old integer object still exists, and y still > points to it. This is why the global y name is not affected by the > change in x > > Now, in the second example, the same thing basically happens. A new > name is created and pointed at the object you supplied. However, the > statement some_list[1] = 4 is different from the assignment, in that > it doesn't create a new object; It modifies the existing one. Since > the global and local names both point to the same object, the change > you make is reflected in both. > > You can of course create a new list object, so that the original is > not affected: > > def nochange(some_list): > # create shallow copy of list. NOTE: Shallow copies may still bite > you if you change the list members. > some_list = some_list[:] > some_list[1] = 2 > > >>> x = [1, 2, 3] > >>> nochange(x) > >>> x > [1, 2, 3] > > HTH, > Hugo > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Feb 23 14:30:00 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Feb 2010 08:30:00 -0500 Subject: [Tutor] list to numpy record array In-Reply-To: <77e831101002222050xf2d90cfm16ef27160a2639ea@mail.gmail.com> References: <77e831101002222050xf2d90cfm16ef27160a2639ea@mail.gmail.com> Message-ID: <1c2a2c591002230530h389c3957jfb00594438ceeac9@mail.gmail.com> On Mon, Feb 22, 2010 at 11:50 PM, Vincent Davis wrote: > > I must be missing something simple. I have a list of lists data = "[[' ?0', ' ?0', '234.0', '24.0', ' 25'], [' ?1', ' ?0', '22428.0', '2378.1', ' 25'],......" and what to make a record array from it but it gets screwed up or I don't get it, maybe both. > > bdata = numpy.array(data, [('x', int),('y', int),('mean',float),('stdv',float),('npixcels',int)]) > >>> bdata > array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), ... > ?? ? ? ?(3486240, 0, 0.0, 0.0, 0)]], > > ?? ? ?dtype=[('x', ' References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> <29179d161002230522g66a062fsb569e3dbf118304e@mail.gmail.com> <23ce85921002230528m53c11513yfc0a0dd10eea2221@mail.gmail.com> Message-ID: <29179d161002230545t53b8a00ep29ba485c3e7e6534@mail.gmail.com> On Tue, Feb 23, 2010 at 2:28 PM, Giorgio wrote: > Thankyou Hugo! > Ok, so i think the key is of my problem is that when doing X = 0 i'm > creating a new object, that only exist in the local namespace. BUT, when > using a list as a parameter for a function i'm only giving it a new name, > but the object it's referring to it's always the same, and is in the global > namespace. > Right? Well, mostly, yes. It's important to see that it's not so much the objects that live in namespaces, it's the names (otherwise they would be called object-spaces, yes?). The objects do not live inside a namespace, but are in a conceptually separate place altogether. A name lives in a namespace, and can only be referenced inside that space. An object can be referenced from anywhere, as long as you have a name that points to it. So, when you're doing x = 0, you're creating a new object, and the name x (in the local namespace) points to that object. That doesn't mean the object itself is confined to the local namespace. You could write 'return x', which allows you to have a name in the global namespace point to that same object. Hugo From contactdayo at gmail.com Tue Feb 23 15:27:16 2010 From: contactdayo at gmail.com (Dayo Adewunmi) Date: Tue, 23 Feb 2010 15:27:16 +0100 Subject: [Tutor] Running PIL.Image on .svg file Message-ID: <4B83E5C4.5020803@gmail.com> Hi all When i use PIL.Image in this script:http://dpaste.com/163588/ on an .svg file, I get this error: http://dpaste.com/163584/ How do i process .svg files in python? Thanks Dayo From sierra_mtnview at sbcglobal.net Tue Feb 23 15:59:22 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 23 Feb 2010 06:59:22 -0800 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 Message-ID: <4B83ED4A.4040203@sbcglobal.net> A few days ago I posted a message titled ""Two" Card Monty. The problem I mentioned looks legitimate, and remains puzzling. I've probed this in a newsgroup, and no one has an explanation that fits. My claim is that if one creates a program in a folder that reads a file in the folder it and then copies it to another folder, it will read the data file in the first folder, and not a changed file in the new folder. I'd appreciate it if some w7 users could try the program below, and let me know what they find. I'm using IDLE in Win7 with Py 2.5. My experience is that if one checks the properties of the copied file, it will point to the original py file and execute it and not the copy. If win7 is the culprit, I would think this is a somewhat serious problem. It may be the sample program is not representative of the larger program that has me stuck. If necessary I can provide it. It uses common modules. (Could this be something like the namespace usage of variables that share a common value?) # Test program. Examine strange link in Python under Win7 # when copying py file to another folder. # Call the program vefifywin7.py # To verify my situation use IDLE, save and run this program there. # Put this program into a folder along with a data file # called verify.txt. Create a single text line with a few characters in it # Run this program and note the output # Copy the program and txt file to another folder # Change the contents of the txt file # Run it again, and see if the output is the same as in the other folder track_file = open("verify.txt") aline = track_file.readline(); print aline track_file.close() -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From anothernetfellow at gmail.com Tue Feb 23 17:24:13 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Tue, 23 Feb 2010 17:24:13 +0100 Subject: [Tutor] What Editori? Message-ID: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> Hi All, what text-editor do you use for python? I've always used kate/nano on Linux and Notepad++/PSPad on Win. Today i've installed portablepython to my pendrive, and found pyscripter in that. It's nice! Do you think it's a good editor? Do you know other names? Giorgio -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Feb 23 17:35:55 2010 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 23 Feb 2010 08:35:55 -0800 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> Message-ID: <20100223163555.GA50570@dragon.alchemy.com> On Tue, Feb 23, 2010 at 05:24:13PM +0100, Giorgio wrote: > what text-editor do you use for python? While the can of worms that particular question tends to open is always an issue (for some reason people get very emotionally passionate about why their editor is the best) I'm not sure you're going to get much of a useful answer beyond a few suggestions to try, since this is such a personal choice and depends so much on how you want to work. Personally, I find vim (on all platforms) to work well for me. I'm giving Eclipse+pydev a try to see how I like that. > Do you think it's a good editor? Do you know other names? Whether any particular editor is "good" as long as it does the minimum amount necessary for programming, is entirely subjective. Try a few and see how they work for you. Actually, I suppose even ed and TECO qualify for some work models ;) -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From anothernetfellow at gmail.com Tue Feb 23 17:46:24 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Tue, 23 Feb 2010 17:46:24 +0100 Subject: [Tutor] What Editori? In-Reply-To: <20100223163555.GA50570@dragon.alchemy.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <20100223163555.GA50570@dragon.alchemy.com> Message-ID: <23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> Definitely i just use pyscripter because it has the py idle integrated in the window. It's very useful! 2010/2/23 Steve Willoughby > On Tue, Feb 23, 2010 at 05:24:13PM +0100, Giorgio wrote: > > what text-editor do you use for python? > > While the can of worms that particular question tends to > open is always an issue (for some reason people get very > emotionally passionate about why their editor is the best) > I'm not sure you're going to get much of a useful answer > beyond a few suggestions to try, since this is such a > personal choice and depends so much on how you want to > work. > > Personally, I find vim (on all platforms) to work well > for me. I'm giving Eclipse+pydev a try to see how I like > that. > > > Do you think it's a good editor? Do you know other names? > > Whether any particular editor is "good" as long as it does > the minimum amount necessary for programming, is entirely > subjective. Try a few and see how they work for you. > > Actually, I suppose even ed and TECO qualify for some work > models ;) > > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Tue Feb 23 18:13:51 2010 From: denis.spir at free.fr (spir) Date: Tue, 23 Feb 2010 18:13:51 +0100 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <20100223163555.GA50570@dragon.alchemy.com> <23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> Message-ID: <20100223181351.37a12a70@o> On Tue, 23 Feb 2010 17:46:24 +0100 Giorgio wrote: > Definitely i just use pyscripter because it has the py idle integrated in > the window. > > It's very useful! Most editors have an integreated console that allow typing commands, launching the interactice interpreter, and running progs all without quitting the editor. I use geany which is imo good for every language... and has the absolutely necessary duplicate feature ;-) (*). Its only drawback is syntax highlighting must be set by editing config files. Denis (*) Does anyone know another editor that has it? ________________________________ la vita e estrany http://spir.wikidot.com/ From randyeraymond at mchsi.com Tue Feb 23 18:21:32 2010 From: randyeraymond at mchsi.com (Randy Raymond) Date: Tue, 23 Feb 2010 11:21:32 -0600 Subject: [Tutor] What Editori? In-Reply-To: <20100223181351.37a12a70@o> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com><20100223163555.GA50570@dragon.alchemy.com><23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> <20100223181351.37a12a70@o> Message-ID: <5B90CD512B5F4788A4AEA51C490358AD@RandyPC> I use Editra. Randy -------------------------------------------------- From: "spir" Sent: Tuesday, February 23, 2010 11:13 AM To: Subject: Re: [Tutor] What Editori? > On Tue, 23 Feb 2010 17:46:24 +0100 > Giorgio wrote: > >> Definitely i just use pyscripter because it has the py idle integrated in >> the window. >> >> It's very useful! > > Most editors have an integreated console that allow typing commands, > launching the interactice interpreter, and running progs all without > quitting the editor. > I use geany which is imo good for every language... and has the absolutely > necessary duplicate feature ;-) (*). Its only drawback is syntax > highlighting must be set by editing config files. > > Denis > > (*) Does anyone know another editor that has it? > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Tue Feb 23 18:27:53 2010 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 23 Feb 2010 09:27:53 -0800 Subject: [Tutor] What Editori? In-Reply-To: <20100223181351.37a12a70@o> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <20100223163555.GA50570@dragon.alchemy.com> <23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> <20100223181351.37a12a70@o> Message-ID: <20100223172753.GB50570@dragon.alchemy.com> On Tue, Feb 23, 2010 at 06:13:51PM +0100, spir wrote: > I use geany which is imo good for every language... and has the absolutely necessary duplicate feature ;-) (*). Most have a variety of features which could be called by that name. What specifically are you referring to here? -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From vincent at vincentdavis.net Tue Feb 23 18:44:28 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 23 Feb 2010 10:44:28 -0700 Subject: [Tutor] list to numpy record array In-Reply-To: <1c2a2c591002230530h389c3957jfb00594438ceeac9@mail.gmail.com> References: <77e831101002222050xf2d90cfm16ef27160a2639ea@mail.gmail.com> <1c2a2c591002230530h389c3957jfb00594438ceeac9@mail.gmail.com> Message-ID: <77e831101002230944w725dfe0ckae46eba01c5ef985@mail.gmail.com> @Kent All I know about RecordArrays is from reading this page: http://www.scipy.org/RecordArrays but it looks like you have done the right thing and created a RecordArray. What is wrong with this result? The number are completely different, or I have no idea how to read it. Here are the first row of each normal array [' 0', ' 0', '234.0', '24.0', ' 25'] Record array [(3153952, 0, 0.0, 0.0, 0) *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn On Tue, Feb 23, 2010 at 6:30 AM, Kent Johnson wrote: > On Mon, Feb 22, 2010 at 11:50 PM, Vincent Davis > wrote: > > > > I must be missing something simple. I have a list of lists data = "[[' > 0', ' 0', '234.0', '24.0', ' 25'], [' 1', ' 0', '22428.0', '2378.1', ' > 25'],......" and what to make a record array from it but it gets screwed up > or I don't get it, maybe both. > > > > bdata = numpy.array(data, [('x', int),('y', > int),('mean',float),('stdv',float),('npixcels',int)]) > > >>> bdata > > array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), > ... > > (3486240, 0, 0.0, 0.0, 0)]], > > > > dtype=[('x', ' ' > All I know about RecordArrays is from reading this page: > http://www.scipy.org/RecordArrays > but it looks like you have done the right thing and created a > RecordArray. What is wrong with this result? > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jsseabold at gmail.com Tue Feb 23 18:55:07 2010 From: jsseabold at gmail.com (Skipper Seabold) Date: Tue, 23 Feb 2010 12:55:07 -0500 Subject: [Tutor] list to numpy record array In-Reply-To: <77e831101002222050xf2d90cfm16ef27160a2639ea@mail.gmail.com> References: <77e831101002222050xf2d90cfm16ef27160a2639ea@mail.gmail.com> Message-ID: On Mon, Feb 22, 2010 at 11:50 PM, Vincent Davis wrote: > > I must be missing something simple. I have a list of lists data = "[[' ?0', ' ?0', '234.0', '24.0', ' 25'], [' ?1', ' ?0', '22428.0', '2378.1', ' 25'],......" and what to make a record array from it but it gets screwed up or I don't get it, maybe both. Notice that at this stage the items are strings, not numbers, and there is whitespace not sure this matters. > Here is what is happening > adata = numpy.array(data,numpy.float64) > > >>> adata > array([[ ?0.00000000e+00, ? 0.00000000e+00, ? 2.34000000e+02, > ?? ? ? ? ?2.40000000e+01, ? 2.50000000e+01], > ?? ? ? ..., > ?? ? ? [ ?4.77000000e+02, ? 4.77000000e+02, ? 2.07000000e+02, > ?? ? ? ? ?4.58000000e+01, ? 2.50000000e+01]]) > > This is what I would expect except it is not a record array. > This is not what I expect. I think I have tried every iteration including using numpy dtaypes numpy.int32 or?bdata = numpy.array(data, dtype = [('x', int),('y', int),('mean',float),('stdv',float),('npixcels',int)]) > What am I missing? > > bdata = numpy.array(data, [('x', int),('y', int),('mean',float),('stdv',float),('npixcels',int)]) > >>> bdata > array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), > ?? ? ? ?(206933603122, 0, 0.0, 0.0, 0), (808334386, 0, 0.0, 0.0, 0), > ?? ? ? ?(3486240, 0, 0.0, 0.0, 0)], > ?? ? ? [(3219488, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), > ?? ? ? ?(13561617777439282, 0, 0.0, 0.0, 0), > ?? ? ? ?(54074581398322, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)], > ?? ? ? [(3285024, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), > ?? ? ? ?(206933931058, 0, 0.0, 0.0, 0), (925775666, 0, 0.0, 0.0, 0), > ?? ? ? ?(3486240, 0, 0.0, 0.0, 0)], > ?? ? ? ..., > ?? ? ? [(3487540, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0), > ?? ? ? ?(206933602866, 0, 0.0, 0.0, 0), (908996661, 0, 0.0, 0.0, 0), > ?? ? ? ?(3486240, 0, 0.0, 0.0, 0)], > ?? ? ? [(3553076, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0), > ?? ? ? ?(13561596370041137, 0, 0.0, 0.0, 0), > ?? ? ? ?(62870573495603, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)], > ?? ? ? [(3618612, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0), > ?? ? ? ?(206933798962, 0, 0.0, 0.0, 0), (942552372, 0, 0.0, 0.0, 0), > ?? ? ? ?(3486240, 0, 0.0, 0.0, 0)]], > > ?? ? ?dtype=[('x', ' > I neglected to reply to the whole list on my first try. For posterity's sake: You should ask on the scipy-user list with a self-contained example. It is heavily trafficked. http://www.scipy.org/Mailing_Lists >From the example you gave above, I am not sure what's going unless it's something in the casting from strings. Note though that you have created a structured array and not a record array. The subtle difference is that the record array allows attribute lookup ie., you could do bdata.x instead of bdata['x']. Structured arrays are usually faster as the attribute lookup convenience is implemented in Python whereas the structured arrays use C code. hth, Skipper From eike.welk at gmx.net Tue Feb 23 18:57:23 2010 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 23 Feb 2010 18:57:23 +0100 Subject: [Tutor] Searchlight/MVPA/ValueError In-Reply-To: <7e1994871002221348mdf0090o4ed920256efc5409@mail.gmail.com> References: <7e1994871002221348mdf0090o4ed920256efc5409@mail.gmail.com> Message-ID: <201002231857.23642.eike.welk@gmx.net> Hey J! On Monday February 22 2010 22:48:11 J wrote: > Dear all, > I am trying to run a very simple searchlight on fMRI data via PyLab (on Mac > Leopard). > > My code is as follows: > > from mvpa.suite import * > import os > from matplotlib.pyplot import figure, show > from mvpa.misc.io.base import SampleAttributes > from mvpa.datasets.nifti import NiftiDataset > ------- > > Your input would be greatly appreciated. > > Thanks a lot, > J I think you are using a special library for processing tomographic images of brains. This one, right? http://www.pymvpa.org/ Probably no one else on this list is using it, unfortunately. However there is a special mailing list for this software: http://lists.alioth.debian.org/mailman/listinfo/pkg-exppsy-pymvpa HTH, Eike. From vincent at vincentdavis.net Tue Feb 23 18:58:38 2010 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 23 Feb 2010 10:58:38 -0700 Subject: [Tutor] list to numpy record array In-Reply-To: References: <77e831101002222050xf2d90cfm16ef27160a2639ea@mail.gmail.com> Message-ID: <77e831101002230958obb84af4l766d742e8cb6f347@mail.gmail.com> @Skipper Thanks I will post over on the scipy list *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn On Tue, Feb 23, 2010 at 10:55 AM, Skipper Seabold wrote: > On Mon, Feb 22, 2010 at 11:50 PM, Vincent Davis > wrote: > > > > I must be missing something simple. I have a list of lists data = "[[' > 0', ' 0', '234.0', '24.0', ' 25'], [' 1', ' 0', '22428.0', '2378.1', ' > 25'],......" and what to make a record array from it but it gets screwed up > or I don't get it, maybe both. Notice that at this stage the items are > strings, not numbers, and there is whitespace not sure this matters. > > Here is what is happening > > adata = numpy.array(data,numpy.float64) > > > > >>> adata > > array([[ 0.00000000e+00, 0.00000000e+00, 2.34000000e+02, > > 2.40000000e+01, 2.50000000e+01], > > ..., > > [ 4.77000000e+02, 4.77000000e+02, 2.07000000e+02, > > 4.58000000e+01, 2.50000000e+01]]) > > > > This is what I would expect except it is not a record array. > > This is not what I expect. I think I have tried every iteration including > using numpy dtaypes numpy.int32 or bdata = numpy.array(data, dtype = [('x', > int),('y', int),('mean',float),('stdv',float),('npixcels',int)]) > > What am I missing? > > > > bdata = numpy.array(data, [('x', int),('y', > int),('mean',float),('stdv',float),('npixcels',int)]) > > >>> bdata > > array([[(3153952, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), > > (206933603122, 0, 0.0, 0.0, 0), (808334386, 0, 0.0, 0.0, 0), > > (3486240, 0, 0.0, 0.0, 0)], > > [(3219488, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), > > (13561617777439282, 0, 0.0, 0.0, 0), > > (54074581398322, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)], > > [(3285024, 0, 0.0, 0.0, 0), (3153952, 0, 0.0, 0.0, 0), > > (206933931058, 0, 0.0, 0.0, 0), (925775666, 0, 0.0, 0.0, 0), > > (3486240, 0, 0.0, 0.0, 0)], > > ..., > > [(3487540, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0), > > (206933602866, 0, 0.0, 0.0, 0), (908996661, 0, 0.0, 0.0, 0), > > (3486240, 0, 0.0, 0.0, 0)], > > [(3553076, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0), > > (13561596370041137, 0, 0.0, 0.0, 0), > > (62870573495603, 0, 0.0, 0.0, 0), (3486240, 0, 0.0, 0.0, 0)], > > [(3618612, 0, 0.0, 0.0, 0), (3618612, 0, 0.0, 0.0, 0), > > (206933798962, 0, 0.0, 0.0, 0), (942552372, 0, 0.0, 0.0, 0), > > (3486240, 0, 0.0, 0.0, 0)]], > > > > dtype=[('x', ' ' > > > > > I neglected to reply to the whole list on my first try. For posterity's > sake: > > You should ask on the scipy-user list with a self-contained example. > It is heavily trafficked. http://www.scipy.org/Mailing_Lists > > From the example you gave above, I am not sure what's going unless > it's something in the casting from strings. Note though that you have > created a structured array and not a record array. The subtle > difference is that the record array allows attribute lookup ie., you > could do bdata.x instead of bdata['x']. Structured arrays are usually > faster as the attribute lookup convenience is implemented in Python > whereas the structured arrays use C code. > > hth, > > Skipper > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lowelltackett at yahoo.com Tue Feb 23 19:04:46 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Tue, 23 Feb 2010 10:04:46 -0800 (PST) Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> Message-ID: <113709.11559.qm@web110101.mail.gq1.yahoo.com> The environment [OS} of choice can do a lot to expand/enhance the capabilities of an editor.? I fell upon Vim from the beginning, and stayed with it for its' rich palate of features and adaptability (and of course, the often...and exhilarating "oh, Vim can do that!").? But beyond that, the Linux platform I work within offers its own dimension. Generally, I will split a [terminal] screen into two (or even 3) virtual screens with bash's 'screen' workhorse, and from there I have in front of me [perhaps] a; 1) script edit screen, 2) interactive screen, and 3) script-launching screen...all on the same physical monitor. For me, that combination creates an awfully rich & deep working canvas.?? The whole...is at least as great as the sum of its' parts. >From the virtual desk of Lowell Tackett? --- On Tue, 2/23/10, Giorgio wrote: From: Giorgio Subject: [Tutor] What Editori? To: tutor at python.org Date: Tuesday, February 23, 2010, 11:24 AM Hi All, what text-editor do you use for python? I've always used kate/nano on Linux and Notepad++/PSPad on Win. Today i've installed portablepython to my pendrive, and found pyscripter in that. It's nice! Do you think it's a good editor? Do you know other names? Giorgio -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -----Inline Attachment Follows----- _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From anothernetfellow at gmail.com Tue Feb 23 19:55:17 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Tue, 23 Feb 2010 19:55:17 +0100 Subject: [Tutor] Functions returning multiple values In-Reply-To: <29179d161002230545t53b8a00ep29ba485c3e7e6534@mail.gmail.com> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> <29179d161002230522g66a062fsb569e3dbf118304e@mail.gmail.com> <23ce85921002230528m53c11513yfc0a0dd10eea2221@mail.gmail.com> <29179d161002230545t53b8a00ep29ba485c3e7e6534@mail.gmail.com> Message-ID: <23ce85921002231055u6db06a23h30a632043742d768@mail.gmail.com> Ok Hugo, so, going back to your example: def nochange(some_list): # create shallow copy of list. NOTE: Shallow copies may still bite you if you change the list members. some_list = some_list[:] some_list[1] = 2 Here we've created a new list. It's an object in the global "object-space :)" but i can't access it outside the function because i don't have a name referring to it in the global namespace. Right? And, please let me ask a question: Kent told that nested_namespace(s) are default in python 2.6. And i found a line confirming this in py2.6 library. But, what about python 2.5 that as you know is the default on linux? Thankyou Giorgio 2010/2/23 Hugo Arts > On Tue, Feb 23, 2010 at 2:28 PM, Giorgio > wrote: > > Thankyou Hugo! > > Ok, so i think the key is of my problem is that when doing X = 0 i'm > > creating a new object, that only exist in the local namespace. BUT, when > > using a list as a parameter for a function i'm only giving it a new name, > > but the object it's referring to it's always the same, and is in the > global > > namespace. > > Right? > > Well, mostly, yes. It's important to see that it's not so much the > objects that live in namespaces, it's the names (otherwise they would > be called object-spaces, yes?). The objects do not live inside a > namespace, but are in a conceptually separate place altogether. A name > lives in a namespace, and can only be referenced inside that space. An > object can be referenced from anywhere, as long as you have a name > that points to it. > > So, when you're doing x = 0, you're creating a new object, and the > name x (in the local namespace) points to that object. That doesn't > mean the object itself is confined to the local namespace. You could > write 'return x', which allows you to have a name in the global > namespace point to that same object. > > Hugo > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Feb 23 19:56:31 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 23 Feb 2010 12:56:31 -0600 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> Message-ID: <333efb451002231056s16079633oa7ee2cbef7a46f3f@mail.gmail.com> On Tue, Feb 23, 2010 at 10:24 AM, Giorgio wrote: > Hi All, > > what text-editor do you use for python? > I use vim - for me it's the hands-down best editor. I usually have two terminals (I run linux) open - one for ipython, and one for vim. I usually have vim split into several buffers for each of the files I'm editing, and I have some nice scripts and plugins that help me edit/modify python code. But then again I've never worked on any huge (read: 1000+ lines, unquantifiable "many" files). For everything I do, my method works excellent. HTH -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From randyeraymond at aim.com Tue Feb 23 18:22:38 2010 From: randyeraymond at aim.com (Randy Raymond) Date: Tue, 23 Feb 2010 11:22:38 -0600 Subject: [Tutor] What Editori? In-Reply-To: <20100223181351.37a12a70@o> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com><20100223163555.GA50570@dragon.alchemy.com><23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> <20100223181351.37a12a70@o> Message-ID: <1084F60195D440E2AC0F5AA123ADE930@RandyPC> I use Editra. Randy -------------------------------------------------- From: "spir" Sent: Tuesday, February 23, 2010 11:13 AM To: Subject: Re: [Tutor] What Editori? > On Tue, 23 Feb 2010 17:46:24 +0100 > Giorgio wrote: > >> Definitely i just use pyscripter because it has the py idle integrated in >> the window. >> >> It's very useful! > > Most editors have an integreated console that allow typing commands, > launching the interactice interpreter, and running progs all without > quitting the editor. > I use geany which is imo good for every language... and has the absolutely > necessary duplicate feature ;-) (*). Its only drawback is syntax > highlighting must be set by editing config files. > > Denis > > (*) Does anyone know another editor that has it? > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Feb 23 20:12:23 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 23 Feb 2010 14:12:23 -0500 Subject: [Tutor] Functions returning multiple values In-Reply-To: <23ce85921002231055u6db06a23h30a632043742d768@mail.gmail.com> References: <23ce85921002210800k77898eb8yddc034161c008673@mail.gmail.com> <201002220346.42100.steve@pearwood.info> <23ce85921002220613n21a7ee46kfa5a633f8f97730@mail.gmail.com> <1c2a2c591002220629v59e3a4d3x662806fe7595f647@mail.gmail.com> <23ce85921002230413w5708ce3bic0092fb4c85f81cc@mail.gmail.com> <29179d161002230522g66a062fsb569e3dbf118304e@mail.gmail.com> <23ce85921002230528m53c11513yfc0a0dd10eea2221@mail.gmail.com> <29179d161002230545t53b8a00ep29ba485c3e7e6534@mail.gmail.com> <23ce85921002231055u6db06a23h30a632043742d768@mail.gmail.com> Message-ID: <1c2a2c591002231112ob05c7eh97eaa08ccc18359d@mail.gmail.com> On Tue, Feb 23, 2010 at 1:55 PM, Giorgio > And, please let me ask a question: Kent told that nested_namespace(s) are > default in python 2.6. And i found a line confirming this in py2.6 library. > But, what about python 2.5 that as you know is the default on linux? Yes, since 2.2 nested namespaces have been standard. Kent From wescpy at gmail.com Tue Feb 23 20:42:40 2010 From: wescpy at gmail.com (wesley chun) Date: Tue, 23 Feb 2010 11:42:40 -0800 Subject: [Tutor] What Editori? In-Reply-To: <1084F60195D440E2AC0F5AA123ADE930@RandyPC> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <20100223163555.GA50570@dragon.alchemy.com> <23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> <20100223181351.37a12a70@o> <1084F60195D440E2AC0F5AA123ADE930@RandyPC> Message-ID: <78b3a9581002231142q398fd368j978a2ced104a000d@mail.gmail.com> > what text-editor do you use for python? as an FYI Guido himself uses both emacs and vi/m... he mentioned this during his PyCon 2010 keynote last week, to which someone tweeted: http://twitter.com/bradallen137/status/9337630806 i primarily use vi/m and emacs as necessary, -- 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 eduardo.susan at gmail.com Tue Feb 23 20:47:40 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Tue, 23 Feb 2010 12:47:40 -0700 Subject: [Tutor] Running PIL.Image on .svg file In-Reply-To: <4B83E5C4.5020803@gmail.com> References: <4B83E5C4.5020803@gmail.com> Message-ID: <9356b9f31002231147t6d7f028cy625b67e1a6503f14@mail.gmail.com> On Tue, Feb 23, 2010 at 7:27 AM, Dayo Adewunmi wrote: > Hi all > > When i use PIL.Image in this script:http://dpaste.com/163588/ ?on an .svg > file, I get this error: ? ? ? ? ? ?http://dpaste.com/163584/ > How do i process .svg files in python? > Thanks > > Dayo > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi, svg is not an image (like a bitmap), it's a vector format file, an xml file to be more precise. From alan.gauld at btinternet.com Tue Feb 23 21:11:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Feb 2010 20:11:59 -0000 Subject: [Tutor] What Editori? References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <20100223163555.GA50570@dragon.alchemy.com> Message-ID: "Steve Willoughby" wrote > Actually, I suppose even ed and TECO qualify for some work > models ;) I even use edlin occasionally - usually in batch files... But Teco is the only editor that I've given up on as being just tooooo hard to use! And that's out of more than a couple of dozen editors on 9 different OSs! Alan G. From alan.gauld at btinternet.com Tue Feb 23 21:14:46 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Feb 2010 20:14:46 -0000 Subject: [Tutor] What Editori? References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com><20100223163555.GA50570@dragon.alchemy.com> <23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> Message-ID: "Giorgio" wrote > Definitely i just use pyscripter because it has the py idle integrated in > the window. PyScripter is an alternative to IDLE but it doesn't have IDLE embedded within it. I think you are getting confused between IDLE and the Python interactive prompt which is available in several tools. The only snag I found with Pyscripter is that its shell is hard coded to a Python release as far as I could tell. But thats not unusual, IDLE is too, as is Pythonwin. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Feb 23 21:15:49 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Feb 2010 20:15:49 -0000 Subject: [Tutor] What Editori? References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com><20100223163555.GA50570@dragon.alchemy.com><23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> <20100223181351.37a12a70@o> Message-ID: "spir" wrote > ...and has the absolutely necessary duplicate feature ;-) (*). > (*) Does anyone know another editor that has it? OK, I'll bite. What is the duplicate feature? :-) Alan G From anothernetfellow at gmail.com Tue Feb 23 21:23:22 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Tue, 23 Feb 2010 21:23:22 +0100 Subject: [Tutor] What Editori? In-Reply-To: References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <20100223163555.GA50570@dragon.alchemy.com> <23ce85921002230846x18775154q26cb7111f817c57f@mail.gmail.com> Message-ID: <23ce85921002231223w65cfe81ci2e17e0a2cc536a15@mail.gmail.com> Yes sorry Alan i've only used the wrong word :D I know the difference :) Giorgio 2010/2/23 Alan Gauld > > "Giorgio" wrote > > Definitely i just use pyscripter because it has the py idle integrated in >> the window. >> > > PyScripter is an alternative to IDLE but it doesn't have IDLE embedded > within it. I think you are getting confused between IDLE and the Python > interactive prompt which is available in several tools. > > The only snag I found with Pyscripter is that its shell is hard coded to > a Python release as far as I could tell. But thats not unusual, IDLE is > too, > as is Pythonwin. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 23 21:23:03 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Feb 2010 20:23:03 -0000 Subject: [Tutor] What Editori? References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <333efb451002231056s16079633oa7ee2cbef7a46f3f@mail.gmail.com> Message-ID: "Wayne Werner" wrote > I use vim - for me it's the hands-down best editor. I usually have two > terminals (I run linux) open - one for ipython, and one for vim. I > usually > have vim split into several buffers for each of the files I'm editing, > and I > have some nice scripts and plugins that help me edit/modify python code. > > But then again I've never worked on any huge (read: 1000+ lines, > unquantifiable "many" files). I have, same setup except I use a third terminal for actually running the program for testing. And of course I use ctags for navigating around from file to file from vim. If you haven't played with ctags and vim start reading man ctags now! :-) Alan G From eire1130 at gmail.com Tue Feb 23 21:43:28 2010 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 23 Feb 2010 15:43:28 -0500 Subject: [Tutor] Python 3 Statistics? Message-ID: <98c3f7c51002231243r1506733i69361f4d08d42ac8@mail.gmail.com> Hi All, I am brand new to python and programing in general. I've been writing a program that will eventually run a monte carlo simulation of some mortality events and I've been making decent progress so far. I decided to use Python 3, as a long term decision, but getting access to modules seems to be tricky. For me to progress further though, I need to do some statistics work in Python. Does anyone know of a python module in Python 3.1 which will allow me to do statistics work? Otherwise I will have to go back to Python 2.5? to get numpy and scipy? -------------- next part -------------- An HTML attachment was scrubbed... URL: From anothernetfellow at gmail.com Tue Feb 23 22:08:56 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Tue, 23 Feb 2010 22:08:56 +0100 Subject: [Tutor] What Editori? In-Reply-To: References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <333efb451002231056s16079633oa7ee2cbef7a46f3f@mail.gmail.com> Message-ID: <23ce85921002231308w7d732acbk363a5416cc08345@mail.gmail.com> O_O. I've downloaded some python examples from my debian server. Then, have edited one of them with pyscript. The IDLE (the real idle alan :D) was giving out a "unexpected indent" error, so i've checked again and again the code -it was ok-. Then, i've opened it in the IDLE. And there, ONLY there i see a double indentation for the line that was giving the error. I think it's because the script has been written on linux and i'm modifying it from windows, any idea or solution? 2010/2/23 Alan Gauld > > "Wayne Werner" wrote > > > I use vim - for me it's the hands-down best editor. I usually have two >> terminals (I run linux) open - one for ipython, and one for vim. I usually >> have vim split into several buffers for each of the files I'm editing, and >> I >> have some nice scripts and plugins that help me edit/modify python code. >> >> But then again I've never worked on any huge (read: 1000+ lines, >> unquantifiable "many" files). >> > > I have, same setup except I use a third terminal for actually running > the program for testing. > > And of course I use ctags for navigating around from file to file from vim. > If you haven't played with ctags and vim start reading man ctags now! :-) > > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Feb 23 23:48:51 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 24 Feb 2010 09:48:51 +1100 Subject: [Tutor] Python 3 Statistics? In-Reply-To: <98c3f7c51002231243r1506733i69361f4d08d42ac8@mail.gmail.com> References: <98c3f7c51002231243r1506733i69361f4d08d42ac8@mail.gmail.com> Message-ID: <201002240948.52342.steve@pearwood.info> On Wed, 24 Feb 2010 07:43:28 am James Reynolds wrote: > For me to progress further though, I need to do some statistics work > in Python. Does anyone know of a python module in Python 3.1 which > will allow me to do statistics work? Otherwise I will have to go back > to Python 2.5? to get numpy and scipy? If you need to go back to the 2.x series, you should use 2.6 not 2.5. The Windows installer for numpy only supports 2.5, but the source install should work with any recent Python 2.x version. -- Steven D'Aprano From contactdayo at gmail.com Tue Feb 23 23:59:21 2010 From: contactdayo at gmail.com (Dayo Adewunmi) Date: Tue, 23 Feb 2010 23:59:21 +0100 Subject: [Tutor] Running PIL.Image on .svg file In-Reply-To: <9356b9f31002231147t6d7f028cy625b67e1a6503f14@mail.gmail.com> References: <4B83E5C4.5020803@gmail.com> <9356b9f31002231147t6d7f028cy625b67e1a6503f14@mail.gmail.com> Message-ID: <4B845DC9.506@gmail.com> Eduardo Vieira wrote: > On Tue, Feb 23, 2010 at 7:27 AM, Dayo Adewunmi wrote: > >> Hi all >> >> When i use PIL.Image in this script:http://dpaste.com/163588/ on an .svg >> file, I get this error: http://dpaste.com/163584/ >> How do i process .svg files in python? >> Thanks >> >> Dayo >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > Hi, svg is not an image (like a bitmap), it's a vector format file, an > xml file to be more precise. > > Ahhh, I see. Ok thanks. From rabidpoobear at gmail.com Wed Feb 24 00:23:28 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 23 Feb 2010 17:23:28 -0600 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002231308w7d732acbk363a5416cc08345@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <333efb451002231056s16079633oa7ee2cbef7a46f3f@mail.gmail.com> <23ce85921002231308w7d732acbk363a5416cc08345@mail.gmail.com> Message-ID: On Tue, Feb 23, 2010 at 3:08 PM, Giorgio wrote: > O_O. > > I've downloaded some python examples from my debian server. Then, have > edited one of them with pyscript. The IDLE (the real idle alan :D) was > giving out a "unexpected indent" error, so i've checked again and again the > code -it was ok-. > > Then, i've opened it in the IDLE. And there, ONLY there i see a double > indentation for the line that was giving the error. > > I think it's because the script has been written on linux and i'm modifying > it from windows, any idea or solution? > > Are you sure you're not mixing spaces and tabs? -------------- next part -------------- An HTML attachment was scrubbed... URL: From transmogribenno at gmail.com Wed Feb 24 01:40:22 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Wed, 24 Feb 2010 09:40:22 +0900 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> Message-ID: <9b00d1a91002231640p6399fb79p68fa416a9a275f44@mail.gmail.com> On 24 February 2010 01:24, Giorgio wrote: > what text-editor do you use for python? I use jEdit, and without a GUI I guess I'd use nano - I'm not the sort who likes reading manuals in order to use a text editor. Many years ago when I was on Windows I used to use TextPad. Then I started using jEdit because it was easy to get going on Windows, Mac, and Linux. I used to switch between operating systems a lot. > I've always used kate/nano on Linux and Notepad++/PSPad on Win. Today i've > installed portablepython to my pendrive, and found pyscripter in that. It's > nice! > Do you think it's a good editor? Do you know other names? Use whatever works for you. Cheers, benno From cmcaine at googlemail.com Wed Feb 24 00:27:42 2010 From: cmcaine at googlemail.com (C M Caine) Date: Tue, 23 Feb 2010 23:27:42 +0000 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> Message-ID: On 22 February 2010 23:28, Wayne Werner wrote: > On Mon, Feb 22, 2010 at 4:10 PM, C M Caine wrote: >> >> Or possibly strange list of object behaviour >> >> IDLE 2.6.2 >> >>> class Player(): >> ? ? ? ?hand = [] >> >> >> >>> Colin = Player() >> >>> Alex = Player() >> >>> >> >>> Players = [Colin, Alex] >> >>> >> >>> def hands(): >> ? ? ? ?for player in Players: >> ? ? ? ? ? ? ? ?player.hand.append("A") >> >> >>> hands() >> >>> >> >>> Colin.hand >> ['A', 'A'] >> >>> Alex.hand >> ['A', 'A'] >> >> I would have expected hand for each object to be simply ['A']. Why >> does this not occur and how would I implement the behaviour I >> expected/want? >> >> Thanks in advance for your help, >> Colin Caine > > This comes from the nature of the list object. Python lists are pass/shared > as reference objects. In your case, both Colin and Alex are pointing to the > Player object's copy of hands - they both get a reference to the same > object. > If you want to create different hand lists you could do something like this: > class Player: > ?? ?def __init__(self, hand=None): > ?? ? ? ?if isinstance(hand, list): > ?? ? ? ? ? ? self.hand = hand > ?? ? ? ?else: > ?? ? ? ? ? ? print "Player needs a list object for its hand!" > > ex: > In [11]: Alan = Player() > Player needs a list object for its hand! > In [12]: Alan = Player([]) > In [13]: Jim = Player([]) > In [14]: Alan.hand.append(3) > In [15]: Jim.hand > Out[15]: [] > HTH, > Wayne > Thanks all (again). I've read the classes tutorial in its entirety now, the problem I had didn't seem to have been mentioned at any point explicitly. I'm still a fairly inexperienced programmer, however, so maybe I missed something in there or maybe this is a standard procedure in other OO programming languages. From davea at ieee.org Wed Feb 24 02:35:39 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 23 Feb 2010 20:35:39 -0500 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <4B83ED4A.4040203@sbcglobal.net> References: <4B83ED4A.4040203@sbcglobal.net> Message-ID: <4B84826B.7030204@ieee.org> Wayne Watson wrote: > A few days ago I posted a message titled ""Two" Card Monty. The > problem I mentioned looks legitimate, and remains puzzling. I've > probed this in a newsgroup, and no one has an explanation that fits. > > My claim is that if one creates a program in a folder that reads a > file in the folder it and then copies it to another folder, it will > read the data file in the first folder, and not a changed file in the > new folder. I'd appreciate it if some w7 users could try the program > below, and let me know what they find. I'm using IDLE in Win7 with Py > 2.5. > > My experience is that if one checks the properties of the copied file, > it will point to the original py file and execute it and not the copy. > If win7 is the culprit, I would think this is a somewhat serious > problem. It may be the sample program is not representative of the > larger program that has me stuck. If necessary I can provide it. It > uses common modules. (Could this be something like the namespace usage > of variables that share a common value?) > > # Test program. Examine strange link in Python under Win7 > # when copying py file to another folder. > # Call the program vefifywin7.py > # To verify my situation use IDLE, save and run this program there. > # Put this program into a folder along with a data file > # called verify.txt. Create a single text line with a few characters > in it > # Run this program and note the output > # Copy the program and txt file to another folder > # Change the contents of the txt file > # Run it again, and see if the output is the same as in the other folder > track_file = open("verify.txt") > aline = track_file.readline(); > print aline > track_file.close() > I find your English is very confusing. Instead of using so many pronouns with confusing antecedents, try being explicit. >My claim is that if one creates a program in a folder that reads a file in the folder Why not say that you created a program and a data file in the same folder, and had the program read the data file? >...in the folder it and then copies it to another folder That first 'it' makes no sense, and the second 'it' probably is meant to be "them". And who is it that does this copying? And using what method? > ... it will read the data file in the first folder Who will read the data file? The first program, the second, or maybe the operator? About now, I have to give up. I'm guessing that the last four lines of your message were intended to be the entire program, and that that same program is stored in two different folders, along with data files having the same name but different first lines. When you run one of these programs it prints the wrong version of the line. You have lots of variables here, Python version, program contents, Idle, Windows version. Windows 7 doesn't do any mysterious "linking," so I'd stop making that your working hypothesis. Your problem is most likely the value of current directory ( os.getcwd() ). And that's set according to at least three different rules, depending on what program launches Python. If you insist on using Idle to launch it, then you'll have to convince someone who uses Idle to tell you its quirks. Most likely it has a separate menu for the starting directory than for the script name & location. But if you're willing to use the command line, then I could probably help, once you get a clear statement of the problem. By default, CMD.EXE uses the current directory as part of its prompt, and that's the current directory Python will start in. But the first things to do are probably to print out the value of os.getcwd(), and to add a slightly different print in each version of the program so you know which one is running. Incidentally, I'd avoid ever opening a data file in "the current directory." If I felt it important to use the current directory as an implied parameter to the program, I'd save it in a string, and build the full path to the desired file using os.path.join() or equivalent. DaveA From dorseye at gmail.com Wed Feb 24 02:43:08 2010 From: dorseye at gmail.com (Eric Dorsey) Date: Tue, 23 Feb 2010 18:43:08 -0700 Subject: [Tutor] Using Python with a Mac In-Reply-To: <4bdcec5e1002210906q40e5632fw4585a528c1a52e15@mail.gmail.com> References: <4bdcec5e1002210906q40e5632fw4585a528c1a52e15@mail.gmail.com> Message-ID: Not sure if this is what you're asking, but you can invoke the Python interpreter from the command line (Terminal) Open a new terminal, and at the $ prompt just type "python".. $ python Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print "now in the python interpreter" now in the python interpreter To run a python program from the command line (assuming its in the same directory), just type: $ python myprogram.py On Sun, Feb 21, 2010 at 10:06 AM, Marco Rompr? wrote: > Hi everyone, I would like to know how to use python with a mac. > > For now, I go to spotlight, open terminal then type IDLE and a window pops > up but its like the window that opens when you run your programs already > saved and I'm not able to open another window to write a script from > scratch. > > Could someone help me please please???? > > I have the latest Macbook Pro so 2,88ghz 15 inches screen. > > Thank you in advance > > Marchoes > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorseye at gmail.com Wed Feb 24 02:48:32 2010 From: dorseye at gmail.com (Eric Dorsey) Date: Tue, 23 Feb 2010 18:48:32 -0700 Subject: [Tutor] What Editori? In-Reply-To: <9b00d1a91002231640p6399fb79p68fa416a9a275f44@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <9b00d1a91002231640p6399fb79p68fa416a9a275f44@mail.gmail.com> Message-ID: On any platform, I use (gui) vim (gvim on Win/Linux, mvim/macvim on OSX) with this plugin: http://www.vim.org/scripts/script.php?script_id=30 On Tue, Feb 23, 2010 at 5:40 PM, Benno Lang wrote: > On 24 February 2010 01:24, Giorgio wrote: > > what text-editor do you use for python? > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kbailey at howlermonkey.net Wed Feb 24 03:53:31 2010 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Tue, 23 Feb 2010 21:53:31 -0500 Subject: [Tutor] webmail client for pop3 in python Message-ID: <4B8494AB.7020009@howlermonkey.net> Anyone knoow of a good python Webmail client in python for my windows notebook? From lie.1296 at gmail.com Wed Feb 24 04:07:52 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 24 Feb 2010 14:07:52 +1100 Subject: [Tutor] webmail client for pop3 in python In-Reply-To: <4B8494AB.7020009@howlermonkey.net> References: <4B8494AB.7020009@howlermonkey.net> Message-ID: On 02/24/10 13:53, Kirk Bailey wrote: > Anyone knoow of a good python Webmail client in python for my windows > notebook? what do you mean by "python webmail client"? Could you elaborate? If you want to send email programmatically, use the smtplib module if the server supports SMTP. From lie.1296 at gmail.com Wed Feb 24 04:27:26 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 24 Feb 2010 14:27:26 +1100 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> Message-ID: On 02/24/10 10:27, C M Caine wrote: > Thanks all (again). I've read the classes tutorial in its entirety > now, the problem I had didn't seem to have been mentioned at any point > explicitly. I'm still a fairly inexperienced programmer, however, so > maybe I missed something in there or maybe this is a standard > procedure in other OO programming languages. Not exactly, staticcally-typed languages typically uses keywords (like "static") to declare an variable as a class variable; but since in python, you don't need to do variable declaration the chosen design is to define class variable in the class itself and instance variable inside __init__() [actually this is not a precise description of what's actually happening, but it'll suffice for newbies] class MyClass(object): classvariable = 'classvar' def __init__(self): self.instancevariable = 'instvar' if you want to access class attribute from inside a method, you prefix the attribute's name with the class' name, and if you want to access instance attribute from inside a method, prefix with self: class MyClass(object): classvariable = 'classvar' def __init__(self): self.instancevariable = 'instvar' def method(self): print MyClass.classvariable print self.instancevariable But due to attribute name resolution rule, you can also access a class variable from self: class MyClass(object): classvariable = 'classvar' def __init__(self): self.instancevariable = 'instvar' def method(self): print self.classvariable as long as the class variable isn't shadowed by an instance variable class MyClass(object): var = 'classvar' def method(self): print self.var #'classvar' self.var = 'instvar' print self.var #'instvar' del self.var print self.var #'classvar' From eire1130 at gmail.com Wed Feb 24 04:53:07 2010 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 23 Feb 2010 22:53:07 -0500 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> Message-ID: <98c3f7c51002231953h20d2483dp4420911bb819b4d1@mail.gmail.com> This thread inspired me to start learning object oriented as well, but it seems I must be missing something fundamental. If I could get an explanation of why I am raising the following exception, I would greatly appreciate it. I'm getting: Traceback (most recent call last): File "C:\Python31\Lib\COI\Project\test.py", line 8, in median = Statistics.stats.median(*a) File "C:\Python31\Lib\COI\Project\Statistics.py", line 23, in median n = (self.value[m] + self.value[m+1]) / 2 IndexError: tuple index out of range Module 1: import Statistics a = [1,2,3,4,5,6,7,8,9,10] mean = Statistics.stats.mean(a) median = Statistics.stats.median(*a) stdev = Statistics.stats.stdev(*a) z = Statistics.stats.zscore(5, *a) print(mean, median, stdev, z) print() Module 2: #!/usr/bin/python # Filename: Statistics.py import math value_list = [] class Statistics: def __init__(self, *value_list): self.value = value_list #self.average = mean(*value_list) self.square_list= [] def mean(self, *value_list): ave = sum(self.value) #/ len(value_list) return ave def median(self, *value_list): if len(self.value) % 2 == 1: m = (len(self.value) - 1)/2 n = self.value[m+1] else: m = len(self.value) / 2 m = int(m) n = (self.value[m] + self.value[m+1]) / 2 return n def variance(self, *value_list): average = self.mean(*value_list) for n in range(len(value_list)): square = (self.value[n] - average)**2 self.square_list.append(square) var = sum(self.square_list) / len(self.square_list) return var stats = Statistics(*value_list) On Tue, Feb 23, 2010 at 10:27 PM, Lie Ryan wrote: > On 02/24/10 10:27, C M Caine wrote: > > Thanks all (again). I've read the classes tutorial in its entirety > > now, the problem I had didn't seem to have been mentioned at any point > > explicitly. I'm still a fairly inexperienced programmer, however, so > > maybe I missed something in there or maybe this is a standard > > procedure in other OO programming languages. > > Not exactly, staticcally-typed languages typically uses keywords (like > "static") to declare an variable as a class variable; but since in > python, you don't need to do variable declaration the chosen design is > to define class variable in the class itself and instance variable > inside __init__() [actually this is not a precise description of what's > actually happening, but it'll suffice for newbies] > > class MyClass(object): > classvariable = 'classvar' > def __init__(self): > self.instancevariable = 'instvar' > > if you want to access class attribute from inside a method, you prefix > the attribute's name with the class' name, and if you want to access > instance attribute from inside a method, prefix with self: > > class MyClass(object): > classvariable = 'classvar' > def __init__(self): > self.instancevariable = 'instvar' > def method(self): > print MyClass.classvariable > print self.instancevariable > > > But due to attribute name resolution rule, you can also access a class > variable from self: > > class MyClass(object): > classvariable = 'classvar' > def __init__(self): > self.instancevariable = 'instvar' > def method(self): > print self.classvariable > > > as long as the class variable isn't shadowed by an instance variable > > class MyClass(object): > var = 'classvar' > def method(self): > print self.var #'classvar' > self.var = 'instvar' > print self.var #'instvar' > del self.var > print self.var #'classvar' > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shurui91 at gmail.com Wed Feb 24 04:58:52 2010 From: shurui91 at gmail.com (Shurui Liu (Aaron Liu)) Date: Tue, 23 Feb 2010 22:58:52 -0500 Subject: [Tutor] ask Message-ID: <2b9003cf1002231958s34b701b6sc69408a0b855acd2@mail.gmail.com> This time is not my assignment, I promise. In python, when we want to list numbers, we use the command "range", like, if we want to list integer from 0 to 9, we can write: range(10); if we want to list integer from 10 to 29, we can write: range(10,30). I was going to show a list of number from 1.0 to 1.9, and I did this in the same way as integer: range(1.0,2.0,0.1), but it doesn't work. Can you help me? Thank you! -- Shurui Liu (Aaron Liu) Computer Science & Engineering Technology University of Toledo -------------- next part -------------- An HTML attachment was scrubbed... URL: From transmogribenno at gmail.com Wed Feb 24 05:19:10 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Wed, 24 Feb 2010 13:19:10 +0900 Subject: [Tutor] ask In-Reply-To: <2b9003cf1002231958s34b701b6sc69408a0b855acd2@mail.gmail.com> References: <2b9003cf1002231958s34b701b6sc69408a0b855acd2@mail.gmail.com> Message-ID: <9b00d1a91002232019j25cfba53r3fd4669b86cf585d@mail.gmail.com> On 24 February 2010 12:58, Shurui Liu (Aaron Liu) wrote: > This time is not my assignment, I promise. > > In python, when we want to list numbers, we use the command "range", like, > if we want to list integer from 0 to 9, we can write: range(10); if we want > to list integer from 10 to 29, we can write: range(10,30). I was going to > show a list of number from 1.0 to 1.9, and I did this in the same way as > integer: range(1.0,2.0,0.1), but it doesn't work. Can you help me? Thank > you! Remember to include your error messages instead of saying "it doesn't work". It appears that range only supports integers. I did a quick search for "python float range" and the first link was the following: http://code.activestate.com/recipes/66472/ HTH, benno From zack at layeredlogic.com Wed Feb 24 06:43:13 2010 From: zack at layeredlogic.com (Zack Jarrett) Date: Tue, 23 Feb 2010 22:43:13 -0700 Subject: [Tutor] Using Python with a Mac In-Reply-To: <4bdcec5e1002210906q40e5632fw4585a528c1a52e15@mail.gmail.com> References: <4bdcec5e1002210906q40e5632fw4585a528c1a52e15@mail.gmail.com> Message-ID: <46C70782-A9F1-4143-AEF5-947E0A1F2EEF@layeredlogic.com> Even though it's written for kids "Snake Wrangling for Kids" is a good resource to get you started with writing Python code. Don't be put off by the title or the target audience; seriously. This book will have you writing and executing Python scripts by page 8. You can get it from: http://code.google.com/p/swfk/downloads/list Make sure to pull down one of the Mac versions. The latest revision uses Python 3.x syntax. Good luck! Zack On Feb 21, 2010, at 10:06 AM, Marco Rompr? wrote: > Could someone help me please please???? From cwitts at compuscan.co.za Wed Feb 24 07:34:20 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 24 Feb 2010 08:34:20 +0200 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> Message-ID: <4B84C86C.3010801@compuscan.co.za> Giorgio wrote: > Hi All, > > what text-editor do you use for python? > > I've always used kate/nano on Linux and Notepad++/PSPad on Win. Today > i've installed portablepython to my pendrive, and found pyscripter in > that. It's nice! > > Do you think it's a good editor? Do you know other names? > > Giorgio > > -- > -- > AnotherNetFellow > Email: anothernetfellow at gmail.com > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I use Spyder mainly, also have Geany, SciTe, and Emacs setup but I like Spyder for pyLint right there, console inside, the ability to run applications in seperate threads and many more useful features. -- Kind Regards, Christian Witts From timomlists at gmail.com Wed Feb 24 09:38:56 2010 From: timomlists at gmail.com (Timo) Date: Wed, 24 Feb 2010 09:38:56 +0100 Subject: [Tutor] Cannot open SQLite database Message-ID: <4B84E5A0.6010105@gmail.com> Hello all, my program uses SQLite as database and everything worked fine until now. I have over 3000 downloads of my program, but I got 2 mails this week from people who get this error: OperationalError: unable to open database file I searched the net, and all problems seem to be of a not writeable directory or passing a tilde to connect to the database. As far as I know, this isn't the case with my program. Here is some code: # Get the application data folder # This will return: C:\Documents and Settings\user\Application Data\myapp PREFDIR = os.path.join(os.environ['APPDATA'], 'myapp') # Connect to the database def db_connect(): conn = sqlite3.connect(os.path.join(PREFDIR, 'myapp.db')) # This line gives the error conn.text_factory = str cursor = conn.cursor() return (conn, cursor) I noticed that the 2 users that got the error are Russian, so I thought that the Russian characters would cause problems. I tried on my Linux and Windows machines with some Russian names, but thet doesn't seem the problem. Some help is appreciated :-). Cheers, Timo From cwitts at compuscan.co.za Wed Feb 24 09:59:33 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 24 Feb 2010 10:59:33 +0200 Subject: [Tutor] Cannot open SQLite database In-Reply-To: <4B84E5A0.6010105@gmail.com> References: <4B84E5A0.6010105@gmail.com> Message-ID: <4B84EA75.2090507@compuscan.co.za> Timo wrote: > Hello all, my program uses SQLite as database and everything worked > fine until now. > I have over 3000 downloads of my program, but I got 2 mails this week > from people who get this error: > > OperationalError: unable to open database file > > I searched the net, and all problems seem to be of a not writeable > directory or passing a tilde to connect to the database. > As far as I know, this isn't the case with my program. > Here is some code: > > > # Get the application data folder > # This will return: C:\Documents and Settings\user\Application Data\myapp > PREFDIR = os.path.join(os.environ['APPDATA'], 'myapp') > > # Connect to the database > def db_connect(): > conn = sqlite3.connect(os.path.join(PREFDIR, 'myapp.db')) # This > line gives the error > conn.text_factory = str > cursor = conn.cursor() > return (conn, cursor) > > > I noticed that the 2 users that got the error are Russian, so I > thought that the Russian characters would cause problems. I tried on > my Linux and Windows machines with some Russian names, but thet > doesn't seem the problem. > > Some help is appreciated :-). > > Cheers, > Timo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Is that folder write-able for the user/application under Windows Vista/7 ? There are some older games for example that cannot be installed in the default locations due to being denied write access to their own data. -- Kind Regards, Christian Witts From alan.gauld at btinternet.com Wed Feb 24 10:02:26 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Feb 2010 09:02:26 -0000 Subject: [Tutor] Strange list behaviour in classes References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> <98c3f7c51002231953h20d2483dp4420911bb819b4d1@mail.gmail.com> Message-ID: "James Reynolds" wrote > This thread inspired me to start learning object oriented as well, but it > seems I must be missing something fundamental. No, this has nothing to do with objects, its just a broken algorithm. > median = Statistics.stats.median(*a) > n = (self.value[m] + self.value[m+1]) / 2 > IndexError: tuple index out of range > > def median(self, *value_list): > if len(self.value) % 2 == 1: > m = (len(self.value) - 1)/2 > n = self.value[m+1] > else: > m = len(self.value) / 2 > m = int(m) > n = (self.value[m] + self.value[m+1]) / 2 > return n Consider the case where the length of value is 2. We will use the else part of the branch. m will have value 1 The highest index is 1 because indexes start at zero so value[m+1] will fail with an index error. A similar error will happen when the list has only 1 entry since the highest index there will be zero. You need to rethink your rules for generating the indexes remembering that they start at zero. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 24 10:09:27 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Feb 2010 09:09:27 -0000 Subject: [Tutor] Cannot open SQLite database References: <4B84E5A0.6010105@gmail.com> Message-ID: "Timo" wrote > OperationalError: unable to open database file Does the file actually exist where you say it does? > # This will return: C:\Documents and Settings\user\Application Data\myapp > PREFDIR = os.path.join(os.environ['APPDATA'], 'myapp') Do you check that APPDATA is actually set? > # Connect to the database > def db_connect(): > conn = sqlite3.connect(os.path.join(PREFDIR, 'myapp.db')) # This Do you do an is file exists check before trrying to use it? And that the permissions on both directory and file are set up correctly? That would be my guess at likely errors. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 24 10:23:31 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Feb 2010 09:23:31 -0000 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python andWin7 References: <4B83ED4A.4040203@sbcglobal.net> Message-ID: "Wayne Watson" wrote > My claim is that if one creates a program in a folder that reads a file > in the folder it and then copies it to another folder, it will read the > data file in the first folder, and not a changed file in the new folder. Thats what I would expect in any OS. Unless you explicitly change the folder name the program will still be using the original file. You would need to explicitly tell Python to open the new copied file. > My experience is that if one checks the properties of the copied file, it > will point to the original py file and execute it and not the copy. OK, Now I'm confused. If you copied the file it should not reference the original. How are you copying it? Are you using shutil.copy()? > If win7 is the culprit, I would think this is a somewhat serious > problem. It seems unlikely to be W7. > It may be the sample program is not representative of the larger program > that has me stuck. If necessary I can provide it. It uses common modules. > (Could this be something like the namespace usage of variables that share > a common value?) No idea, please post it if it is reasonably short. Working from code is always more precise than from text descriptions. > # To verify my situation use IDLE, save and run this program there. > # Put this program into a folder along with a data file > # called verify.txt. Create a single text line with a few characters in > it > # Run this program and note the output > # Copy the program and txt file to another folder > # Change the contents of the txt file > # Run it again, and see if the output is the same as in the other folder > track_file = open("verify.txt") > aline = track_file.readline(); > print aline > track_file.close() OK, This is not what I thought you meant from your description! You are copying the files as a user. How are you doing that? - from a command window? - Or using Windows Explorer? - Using drag n drop or copy/paste? Still a lot of variables. What happens if you run the program from the command line rather than IDLE? Did you close and restart IDLE between runs? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 24 10:25:52 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Feb 2010 09:25:52 -0000 Subject: [Tutor] ask References: <2b9003cf1002231958s34b701b6sc69408a0b855acd2@mail.gmail.com> Message-ID: "Shurui Liu (Aaron Liu)" wrote in message news:2b9003cf1002231958s34b701b6sc69408a0b855acd2 at mail.gmail.com... > This time is not my assignment, I promise. > > In python, when we want to list numbers, we use the command "range", > like, > if we want to list integer from 0 to 9, we can write: range(10); if we > want > to list integer from 10 to 29, we can write: range(10,30). I was going to > show a list of number from 1.0 to 1.9, and I did this in the same way as > integer: range(1.0,2.0,0.1), but it doesn't work. Can you help me? Thank > you! > > -- > Shurui Liu (Aaron Liu) > Computer Science & Engineering Technology > University of Toledo > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From denis.spir at free.fr Wed Feb 24 11:16:50 2010 From: denis.spir at free.fr (spir) Date: Wed, 24 Feb 2010 11:16:50 +0100 Subject: [Tutor] common (sub)attributes Message-ID: <20100224111650.0301dfe3@o> Hello, Just a really basic note: Classes are often used to hold common or default attribute. Then, some of these attrs may get custom values for individual objects of a given type. Simply by overriding the attr on this object (see code below). But this will not only if the attr is a top-level one; not if it is itself part of a composite object. In the latter case, the (sub)attribute is still shared, so the change affects everybody. So, we must redefine the whole top-level attr instead. Trivial, but not obvious for me ;-) === sample code === #!/usr/bin/env python # coding: utf-8 # case x is top-level attr class C(object): x = 0 y = 0 a = 'u' def __str__ (self) : return "C(%s,%s,%s)" %(self.x,self.y,self.a) c1 = C() ; c2 = C() c1.x = 1 # change x for c1 only c1.a = 'v' # change a for c1 only print c1,c2 # ==> C(1,0,v) C(0,0,u) # case x is element of composite attr class P: x = 0 y = 0 class C(object): p = P() a = 'u' def __str__ (self) : return "C(%s,%s,%s)" %(self.p.x,self.p.y,self.a) c1 = C() ; c2 = C() c1.p.x = 1 # change x for c1, but x is actually shared c1.a = 'v' # change a for c1 only print c1,c2 # ==> C(1,0,v) C(1,0,u) Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From computing.account at googlemail.com Wed Feb 24 11:23:18 2010 From: computing.account at googlemail.com (AG) Date: Wed, 24 Feb 2010 10:23:18 +0000 Subject: [Tutor] Using Matplotlib - program still running when graph window is closed Message-ID: <4B84FE16.7030106@gmail.com> How does one ensure that once a graph has been produced by Matplotlib and that graph has been closed by the user that the program itself stops? What I am currently getting is that when I close the graph pop-up window and then close IDLE, I get a message that the program is still running and am I sure that I want to stop it. Yes, I am sure, but I don't want to have to keep killing the IDLE interpreter window in order to do so, but if I don't, then I am seemingly unable to produce another graph pop-up window. How do I control this from within the script itself? TIA AG From denis.spir at free.fr Wed Feb 24 11:58:06 2010 From: denis.spir at free.fr (spir) Date: Wed, 24 Feb 2010 11:58:06 +0100 Subject: [Tutor] Cannot open SQLite database In-Reply-To: <4B84E5A0.6010105@gmail.com> References: <4B84E5A0.6010105@gmail.com> Message-ID: <20100224115806.36fabc90@o> On Wed, 24 Feb 2010 09:38:56 +0100 Timo wrote: > Hello all, my program uses SQLite as database and everything worked fine > until now. > I have over 3000 downloads of my program, but I got 2 mails this week > from people who get this error: > > OperationalError: unable to open database file > > I searched the net, and all problems seem to be of a not writeable > directory or passing a tilde to connect to the database. > As far as I know, this isn't the case with my program. > Here is some code: > > > # Get the application data folder > # This will return: C:\Documents and Settings\user\Application Data\myapp > PREFDIR = os.path.join(os.environ['APPDATA'], 'myapp') > > # Connect to the database > def db_connect(): > conn = sqlite3.connect(os.path.join(PREFDIR, 'myapp.db')) # This > line gives the error > conn.text_factory = str > cursor = conn.cursor() > return (conn, cursor) I would first add debug lines print os.path.join(PREFDIR, 'myapp.db') print os.path.exists(os.path.join(PREFDIR, 'myapp.db')) print open(os.path.join(PREFDIR, 'myapp.db'), 'r') print open(os.path.join(PREFDIR, 'myapp.db'), 'a') conn = sqlite3.connect(os.path.join(PREFDIR, 'myapp.db')) to check name, existence, read access right, write access right, of the file. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From tbrown at snapsurveys.com Wed Feb 24 12:02:35 2010 From: tbrown at snapsurveys.com (Tim Brown) Date: Wed, 24 Feb 2010 11:02:35 +0000 Subject: [Tutor] distutils and the postinstallation script Message-ID: Hi, I've written an installation, for Windows, using distutils to produce a .exe setup file. When the setup.exe is run, can my postinstallation script can find out which folder the setup.exe is in ? Thanks Tim From anothernetfellow at gmail.com Wed Feb 24 14:14:49 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Wed, 24 Feb 2010 14:14:49 +0100 Subject: [Tutor] What Editori? In-Reply-To: References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <333efb451002231056s16079633oa7ee2cbef7a46f3f@mail.gmail.com> <23ce85921002231308w7d732acbk363a5416cc08345@mail.gmail.com> Message-ID: <23ce85921002240514j38fa8879wc02e737f7aaca0d8@mail.gmail.com> > > >> >> Are you sure you're not mixing spaces and tabs? > Yes i'm sure. I'm using the "tab button" and the same button works perfectly in the IDLE editor. -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Feb 24 14:45:17 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Feb 2010 08:45:17 -0500 Subject: [Tutor] ask In-Reply-To: <2b9003cf1002231958s34b701b6sc69408a0b855acd2@mail.gmail.com> References: <2b9003cf1002231958s34b701b6sc69408a0b855acd2@mail.gmail.com> Message-ID: <1c2a2c591002240545g52e19593jf2eb07b056a29413@mail.gmail.com> On Tue, Feb 23, 2010 at 10:58 PM, Shurui Liu (Aaron Liu) wrote: > This time is not my assignment, I promise. > > In python, when we want to list numbers, we use the command "range", like, > if we want to list integer from 0 to 9, we can write: range(10); if we want > to list integer from 10 to 29, we can write: range(10,30). I was going to > show a list of number from 1.0 to 1.9, and I did this in the same way as > integer: range(1.0,2.0,0.1), but it doesn't work. Can you help me? Thank > you! Right, range() only works with integer arguments. You can use a list comprehension to convert to floats: In [2]: print [ x/10.0 for x in range(10, 20) ] [1.0, 1.1000000000000001, 1.2, 1.3, 1.3999999999999999, 1.5, 1.6000000000000001, 1.7, 1.8, 1.8999999999999999] The rounding errors are to be expected, see this link for an explanation: http://docs.python.org/tutorial/floatingpoint.html Kent From kent37 at tds.net Wed Feb 24 14:51:10 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Feb 2010 08:51:10 -0500 Subject: [Tutor] DreamPie - The Python shell you've always dreamed about! Message-ID: <1c2a2c591002240551m21402044ka11566dcd5becadc@mail.gmail.com> This looks promising and probably of interest to some on this list. Kent ---------- Forwarded message ---------- From:?Noam Yorav-Raphael To:?Python-announce-list at python.org Date:?Sun, 21 Feb 2010 11:39:02 +0200 Subject:?DreamPie - The Python shell you've always dreamed about! I'm pleased to announce DreamPie 1.0 - a new graphical interactive Python shell! Some highlights: * Has whatever you would expect from a graphical Python shell - attribute completion, tooltips which show how to call functions, highlighting of matching parentheses, etc. * Fixes a lot of IDLE nuisances - in DreamPie interrupt always works, history recall and completion works as expected, etc. * Results are saved in the Result History. * Long output is automatically folded so you can focus on what's important. * Jython and IronPython support makes DreamPie a great tool for exploring Java and .NET classes. * You can copy any amount of code and immediately execute it, and you can also copy code you typed interactively into a new file, with the Copy Code Only command. No tabs are used! * Free software licensed under GPL version 3. Check it out at http://dreampie.sourceforge.net/ and tell me what you think! Have fun, Noam From eike.welk at gmx.net Wed Feb 24 15:00:34 2010 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 24 Feb 2010 15:00:34 +0100 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002240514j38fa8879wc02e737f7aaca0d8@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <23ce85921002240514j38fa8879wc02e737f7aaca0d8@mail.gmail.com> Message-ID: <201002241500.34254.eike.welk@gmx.net> On Wednesday February 24 2010 14:14:49 Giorgio wrote: > Yes i'm sure. I'm using the "tab button" and the same button works > perfectly in the IDLE editor. The editors could be configured differently with respect to the "tab button". Some may insert tabs some may insert spaces. EMACS can even mix tabs and spaces; it can replace long runs of space characters with the equivalent, smaller number of tabs (IMHO). Here is a somewhat related comic: http://xkcd.com/378/ By the way, I'm using Eclipse/Pydev. Eike. From anothernetfellow at gmail.com Wed Feb 24 15:11:12 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Wed, 24 Feb 2010 15:11:12 +0100 Subject: [Tutor] What Editori? In-Reply-To: <201002241500.34254.eike.welk@gmx.net> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <23ce85921002240514j38fa8879wc02e737f7aaca0d8@mail.gmail.com> <201002241500.34254.eike.welk@gmx.net> Message-ID: <23ce85921002240611n4066674epf1207fc20888feeb@mail.gmail.com> > The editors could be configured differently with respect to the "tab > button". > Some may insert tabs some may insert spaces. > Ok, found the problem. I'm inserting tabs, but the original file only has spaces. Do you think i can look for a function that automatically inserts a certain number of spaces when i press tab? > > By the way, I'm using Eclipse/Pydev. > > NetBeans is a good alternative, and supports py in the new beta plugin. I've also tried eclipse/aptana/pydev but think they're too difficult! -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Wed Feb 24 15:23:19 2010 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 24 Feb 2010 15:23:19 +0100 Subject: [Tutor] Using Matplotlib - program still running when graph window is closed In-Reply-To: <4B84FE16.7030106@gmail.com> References: <4B84FE16.7030106@gmail.com> Message-ID: <201002241523.19432.eike.welk@gmx.net> On Wednesday February 24 2010 11:23:18 AG wrote: > How does one ensure that once a graph has been produced by Matplotlib > and that graph has been closed by the user that the program itself stops? > > What I am currently getting is that when I close the graph pop-up window > and then close IDLE, I get a message that the program is still running > and am I sure that I want to stop it. Yes, I am sure, but I don't want > to have to keep killing the IDLE interpreter window in order to do so, > but if I don't, then I am seemingly unable to produce another graph > pop-up window. There seem to be erroneous interference between Idle and Matplotlib. Similar problems are reported on the Matplotlib list too. The list for Matplotlib users is here: https://lists.sourceforge.net/lists/listinfo/matplotlib-users You could also try out the Spyder IDE, which reportedly works well with Matplotlib. http://packages.python.org/spyder/ Eike. From computing.account at googlemail.com Wed Feb 24 16:06:56 2010 From: computing.account at googlemail.com (AG) Date: Wed, 24 Feb 2010 15:06:56 +0000 Subject: [Tutor] Using Matplotlib - program still running when graph window is closed In-Reply-To: <201002241523.19432.eike.welk@gmx.net> References: <4B84FE16.7030106@gmail.com> <201002241523.19432.eike.welk@gmx.net> Message-ID: <4B854090.4090705@gmail.com> Eike Welk wrote: > On Wednesday February 24 2010 11:23:18 AG wrote: > >> How does one ensure that once a graph has been produced by Matplotlib >> and that graph has been closed by the user that the program itself stops? >> >> What I am currently getting is that when I close the graph pop-up window >> and then close IDLE, I get a message that the program is still running >> and am I sure that I want to stop it. Yes, I am sure, but I don't want >> to have to keep killing the IDLE interpreter window in order to do so, >> but if I don't, then I am seemingly unable to produce another graph >> pop-up window. >> > > There seem to be erroneous interference between Idle and Matplotlib. Similar > problems are reported on the Matplotlib list too. The list for Matplotlib > users is here: > https://lists.sourceforge.net/lists/listinfo/matplotlib-users > > You could also try out the Spyder IDE, which reportedly works well with > Matplotlib. > http://packages.python.org/spyder/ > > > Eike. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Thanks Eike, that was helpful. At least it reassures me that I am not screwing something up. Spyder looks interesting, but I think is probably far more than I need and may be a little dubious installing it on Debian. But I may want to give it a more considered rethink. Cheers AG -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Feb 24 16:13:58 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Feb 2010 02:13:58 +1100 Subject: [Tutor] ask In-Reply-To: <2b9003cf1002231958s34b701b6sc69408a0b855acd2@mail.gmail.com> References: <2b9003cf1002231958s34b701b6sc69408a0b855acd2@mail.gmail.com> Message-ID: <201002250214.00205.steve@pearwood.info> On Wed, 24 Feb 2010 02:58:52 pm Shurui Liu (Aaron Liu) wrote: > This time is not my assignment, I promise. > > In python, when we want to list numbers, we use the command "range", > like, if we want to list integer from 0 to 9, we can write: > range(10); if we want to list integer from 10 to 29, we can write: > range(10,30). I was going to show a list of number from 1.0 to 1.9, > and I did this in the same way as integer: range(1.0,2.0,0.1), but it > doesn't work. Can you help me? Thank you! Hope this helps: http://code.activestate.com/recipes/577068-floating-point-range/ -- Steven D'Aprano From kent37 at tds.net Wed Feb 24 16:25:19 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 24 Feb 2010 10:25:19 -0500 Subject: [Tutor] Regular expression generator Message-ID: <1c2a2c591002240725j61519bd6lc7f7875bfb002649@mail.gmail.com> Another interesting tool - you give it a sample string and it helps you build a regular expression to match the string. This is not a regex tester, it actually creates the regex for you as you click on elements of the string. http://txt2re.com/index-python.php3 Kent From anothernetfellow at gmail.com Wed Feb 24 16:40:07 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Wed, 24 Feb 2010 16:40:07 +0100 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002240611n4066674epf1207fc20888feeb@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <23ce85921002240514j38fa8879wc02e737f7aaca0d8@mail.gmail.com> <201002241500.34254.eike.welk@gmx.net> <23ce85921002240611n4066674epf1207fc20888feeb@mail.gmail.com> Message-ID: <23ce85921002240740y52ae331ela0d2d7965fef13e@mail.gmail.com> And, what about more powerful editors? I mean editors with features like SVN/GIT management and so on. I use Netbeans, but also know Eclipse/Aptana. > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From yam at nerd.cx Wed Feb 24 17:07:41 2010 From: yam at nerd.cx (William Witteman) Date: Wed, 24 Feb 2010 11:07:41 -0500 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002240740y52ae331ela0d2d7965fef13e@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> <23ce85921002240514j38fa8879wc02e737f7aaca0d8@mail.gmail.com> <201002241500.34254.eike.welk@gmx.net> <23ce85921002240611n4066674epf1207fc20888feeb@mail.gmail.com> <23ce85921002240740y52ae331ela0d2d7965fef13e@mail.gmail.com> Message-ID: <20100224160741.GA13105@yam.witteman.ca> On Wed, Feb 24, 2010 at 04:40:07PM +0100, Giorgio wrote: >And, what about more powerful editors? I mean editors with features like SVN/ >GIT management and so on. I think you'll find that there is extensive version control integration in most/all of the "less powerful" editors. Certainly you would find many who would (perhaps strenuously) refute a suggestion that vi[m]|emacs are not "powerful". Of the many editors mentioned in this thread at least vim, emacs and geany have integration available for any version control system. -- yours, William From ricaraoz at gmail.com Wed Feb 24 16:33:22 2010 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 24 Feb 2010 12:33:22 -0300 Subject: [Tutor] What Editori? In-Reply-To: <113709.11559.qm@web110101.mail.gq1.yahoo.com> References: <113709.11559.qm@web110101.mail.gq1.yahoo.com> Message-ID: <4B8546C2.6080309@gmail.com> Lowell Tackett wrote: > The environment [OS} of choice can do a lot to expand/enhance the > capabilities of an editor. I fell upon Vim from the beginning, and > stayed with it for its' rich palate of features and adaptability (and > of course, the often...and exhilarating "oh, Vim can do that!"). But > beyond that, the Linux platform I work within offers its own dimension. > > Generally, I will split a [terminal] screen into two (or even 3) > virtual screens with bash's 'screen' workhorse, and from there I have > in front of me [perhaps] a; 1) script edit screen, 2) interactive > screen, and 3) script-launching screen...all on the same physical monitor. > > For me, that combination creates an awfully rich & deep working > canvas. The whole...is at least as great as the sum of its' parts. > LOL Any modern editor can do that! In SPE I'm just now working in 7 scripts at a time (a few of them just for checking stuff) each in it's own tab, a python shell, locals window, output window, to do window, procedure index, object index, notes window, directory explorer window, each in its own tab. And on top of that I can execute a program and debug it through winpdb, test regular expressions, check code with pyChecker, run in a terminal the current script with or without arguments, design a GUI with wxGlade or XRC, and many other actions all a menu choice away. And nobody would claim this is extraordinary. Vim has other advantages for an expert user (but you have a steep learning curve) but what you mention are hardly outstanding issues nowadays. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdole1 at cogeco.ca Wed Feb 24 17:34:02 2010 From: rdole1 at cogeco.ca (rick) Date: Wed, 24 Feb 2010 11:34:02 -0500 Subject: [Tutor] strange bidi requirement Message-ID: <1267029242.9270.13.camel@rick-desktop> I'm trying to write a math quiz program that replicates an old book on arithmetic. when it comes to summing a long column, I need to read the answer from the user, one digit at a time. so, if the answer should be something like 14238.83 I would need to read the .03, then the .8, and so on. I figure all strings, cast to int (well, for this example, float). Would this be easier if I learned some GUI programming? Can it be done at all in just console? I'd post some code, but I'm completely clueless on this one. RTFM replies are welcome, just point me to the section I need to read! thanks, Rick From Mike.Hansen at atmel.com Wed Feb 24 18:07:52 2010 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Wed, 24 Feb 2010 10:07:52 -0700 Subject: [Tutor] What Editori? In-Reply-To: <4B8546C2.6080309@gmail.com> References: <113709.11559.qm@web110101.mail.gq1.yahoo.com> <4B8546C2.6080309@gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D0EF0D989@csomb01.corp.atmel.com> I'm surprised no one has mentioned ActiveState's KOMODO. I primarily use VIM, but I hop into KOMODO for doing little scripts and watching the output. KOMODO comes in two flavors, KOMODO Edit which is free and KOMODO IDE which costs about $300. I suspect that KOMODO Edit does most of what people need. For those that don't want the steep learning curve of VIM or Emacs, I'd recommend KOMODO. Mike No, I don't work for ActiveState. =) From transmogribenno at gmail.com Wed Feb 24 18:46:26 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Thu, 25 Feb 2010 02:46:26 +0900 Subject: [Tutor] strange bidi requirement In-Reply-To: <1267029242.9270.13.camel@rick-desktop> References: <1267029242.9270.13.camel@rick-desktop> Message-ID: <9b00d1a91002240946q5e32ff55yb65334862bb692fa@mail.gmail.com> On 25 February 2010 01:34, rick wrote: > I'm trying to write a math quiz program that replicates an old book on > arithmetic. > > when it comes to summing a long column, I need to read the answer from > the user, one digit at a time. > > so, if the answer should be something like > > 14238.83 > > I would need to read the .03, then the .8, and so on. ? I figure all > strings, cast to int ?(well, for this example, float). ?Would this be > easier if I learned some GUI programming? ? Can it be done at all in > just console? If you really want just console, you'll probably need to use curses: http://docs.python.org/library/curses.html HTH, benno From xchimeras at gmail.com Wed Feb 24 21:55:49 2010 From: xchimeras at gmail.com (Mike) Date: Wed, 24 Feb 2010 15:55:49 -0500 Subject: [Tutor] What Editori? In-Reply-To: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com> Message-ID: I use and love Pyscripter for Windows. I guess I am used to the Delphi IDE. Mike On Tue, Feb 23, 2010 at 11:24 AM, Giorgio wrote: > Hi All, > what text-editor do you use for python? > I've always used kate/nano on Linux and Notepad++/PSPad on Win. Today i've > installed portablepython to my pendrive, and found pyscripter in that. It's > nice! > Do you think it's a good editor? Do you know other names? > Giorgio > > -- > -- > AnotherNetFellow > Email: anothernetfellow at gmail.com > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From zstumgoren at gmail.com Wed Feb 24 23:14:03 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 24 Feb 2010 17:14:03 -0500 Subject: [Tutor] Python-based address standardization script? Message-ID: Hey folks, Anyone know if there's a Python script floating out there to standardize U.S. addresses? I couldn't find anything on ActiveState or by Googling...I'm interested in something similar to this Perl module: http://search.cpan.org/~sderle/Geo-StreetAddress-US-0.99/US.pm Just curious if anyone's seen an implementation in Python. As always, the pointers are appreciated. Serdar -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 24 23:32:51 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Feb 2010 22:32:51 -0000 Subject: [Tutor] What Editori? References: <23ce85921002230824q626642ddt9e6f4d31dd62f3bb@mail.gmail.com><23ce85921002240514j38fa8879wc02e737f7aaca0d8@mail.gmail.com><201002241500.34254.eike.welk@gmx.net><23ce85921002240611n4066674epf1207fc20888feeb@mail.gmail.com> <23ce85921002240740y52ae331ela0d2d7965fef13e@mail.gmail.com> Message-ID: "Giorgio" wrote > And, what about more powerful editors? I mean editors with features like > SVN/GIT management and so on. THose aren't really editor features but IDE features. But thats probably splityting hairs. But emacs does that too and truly is a powerful editor. Certainly more so than the standard editor in many of the modern IDEs > I use Netbeans, but also know Eclipse/Aptana. I liked Netbeans but Eclipse has become the de-facto IDE at work so I now use that. Its OK, but not outstanding. I like all the plugins etc but as an editor it is nothing special. As an IDE its pretty neat. Alan G. From alan.gauld at btinternet.com Wed Feb 24 23:47:05 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Feb 2010 22:47:05 -0000 Subject: [Tutor] common (sub)attributes References: <20100224111650.0301dfe3@o> Message-ID: "spir" wrote > Classes are often used to hold common or default attribute. True > Then, some of these attrs may get custom values for individual > objects of a given type. Simply by overriding the attr on this object Yes, but then the arttribute becomes an instance attribute which masks the class one (unless accessed via the class). > But this will not only if the attr is a top-level one; not if it is > itself part > of a composite object. Sorry, you lost me there! > In the latter case, the (sub)attribute is still shared, so the change > affects everybody. So, we must redefine the whole top-level attr > instead. Trivial, but not obvious for me ;-) Nope, Didn't understand that either. Not sure what you mean by a sub-attribute or top-level attribute?. > === sample code === > #!/usr/bin/env python > # coding: utf-8 > > # case x is top-level attr > class C(object): > x = 0 > y = 0 > a = 'u' > def __str__ (self) : > return "C(%s,%s,%s)" %(self.x,self.y,self.a) Using an instance to access class attributes is IMHO a bad idea. Better to always access class attributes via the class, it makes it obvious what you are working with. > c1 = C() ; c2 = C() > c1.x = 1 # change x for c1 only > c1.a = 'v' # change a for c1 only Really creating new instance attributes called x and a > print c1,c2 # ==> C(1,0,v) C(0,0,u) > # case x is element of composite attr > class P: > x = 0 > y = 0 > class C(object): > p = P() > a = 'u' > def __str__ (self) : > return "C(%s,%s,%s)" %(self.p.x,self.p.y,self.a) > c1 = C() ; c2 = C() > c1.p.x = 1 # change x for c1, but x is actually shared Yes but try P.x, it will have the original value of 0 You are again creating a new instance attribute in the instance of P which is shared by the class C. > c1.a = 'v' # change a for c1 only Create a new instance variable a This is consistent with how Python deals with ocal variables in a function: x = 0 print x def f() print x x = 5 print x print x prints 0 0 5 0 The 5 is local to the function and only exists for the duration of the code execution. In the case of an instance the "local" or instyance barianle lasts for the life of the object. The class variable last for the life of the class. (and in Python you can del() a class... to end its life - but it will exist until the last instance is destroyed because each instance has a reference to it.) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 24 23:53:18 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Feb 2010 22:53:18 -0000 Subject: [Tutor] strange bidi requirement References: <1267029242.9270.13.camel@rick-desktop> Message-ID: "rick" wrote in message news:1267029242.9270.13.camel at rick-desktop... > 14238.83 > > I would need to read the .03, then the .8, and so on. I figure all > strings, cast to int (well, for this example, float). Would this be > easier if I learned some GUI programming? Can it be done at all in > just console? It can but you probably need to fake it by storting the previous anser then pre-pending the next character. You can do it by using one of the console I/O libraries to delete the line and rewrite it - conio is one such. In pseudocode ans = '' while not done ch = getch() ans = ch+ans delete line print line, Hope thats enough to start. Another option for a known length is to use cursor positioning commands to move the cursor from right to left with each character. Finally you could use curses, but thats just a pseudo GUI for consoles! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Feb 24 23:57:20 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Feb 2010 09:57:20 +1100 Subject: [Tutor] strange bidi requirement In-Reply-To: <1267029242.9270.13.camel@rick-desktop> References: <1267029242.9270.13.camel@rick-desktop> Message-ID: <201002250957.20763.steve@pearwood.info> On Thu, 25 Feb 2010 03:34:02 am rick wrote: > I'm trying to write a math quiz program that replicates an old book > on arithmetic. > > when it comes to summing a long column, I need to read the answer > from the user, one digit at a time. > > so, if the answer should be something like > > 14238.83 > > I would need to read the .03, then the .8, and so on. I figure all > strings, cast to int (well, for this example, float). Would this be > easier if I learned some GUI programming? Hell no! GUI programming is a whole new lot of stuff to learn! It's worth learning if you want a GUI interface, but not because it makes other things easier. > Can it be done at all in just console? Do you actually need to ask the user for one digit at a time? I don't imagine so, but could be wrong. So you can ask the user for the number at the console, and then process it in reverse: >>> s = raw_input("Please enter a decimal number: ") Please enter a decimal number: 123.456 >>> >>> print s 123.456 >>> >>> for c in reversed(s): ... print c ... 6 5 4 . 3 2 1 Hope this helps. -- Steven D'Aprano From alan.gauld at btinternet.com Wed Feb 24 23:59:09 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 24 Feb 2010 22:59:09 +0000 (GMT) Subject: [Tutor] Strange list behaviour in classes In-Reply-To: <98c3f7c51002240431k3a15308v1abc78bf23001aa@mail.gmail.com> References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> <98c3f7c51002231953h20d2483dp4420911bb819b4d1@mail.gmail.com> <98c3f7c51002240431k3a15308v1abc78bf23001aa@mail.gmail.com> Message-ID: <610803.84007.qm@web86707.mail.ird.yahoo.com> Forwarding to the list. Please alweays use Reply All so others can comment too. I made a few changes, but I'm getting the same error on variance (see below): Looks like a different error to me! It would seem to me that it should never evaluate if the denominator is zero because of the if statement. But the if statement doesn't test whether len(self.square_list) is zero. It tests whether self.value is zero. The other thing I don't understand is that the object that is being passed into the instance is a list, but it seems to be a tuple once the object is called. Why does this happen? Am I doing something additional wrong? > > Sorry, your code doesn't show any instances let alone lists being pased in? Alan G. File "C:\Python31\Lib\COI\Project\Statistics.py", line 39, in variance > var = sum(self.square_list) / len(self.square_list) >ZeroDivisionError: int division or modulo by zero > > >#!/usr/bin/python ># Filename: Statistics.py > > >import math >value_list = [] >class Statistics: >def __init__(self, *value_list): >self.value = value_list >#self.average = mean(*value_list) >self.square_list= [] >def mean(self, *value_list): >if len(self.value) == 0: >ave = 0 >else: >ave = sum(self.value) / len(self.value) >return ave > > >def median(self, *value_list): >if len(self.value) <= 2: >n = self.mean(self.value) >elif len(self.value) % 2 == 1: >m = (len(self.value) - 1)/2 >n = self.value[m+1] >else: >m = len(self.value) / 2 >m = int(m) >n = (self.value[m] + self.value[m+1]) / 2 >return n >def variance(self, *value_list): >if self.value == 0: >var = 0 >else: >average = self.mean(*self.value) >for n in range(len(self.value)): >square = (self.value[n] - average)**2 >self.square_list.append(square) >var = sum(self.square_list) / len(self.square_list) >return var > > > >On Wed, Feb 24, 2010 at 4:02 AM, Alan Gauld wrote: > > >>>>"James Reynolds" wrote >> >> >> >>>>>This thread inspired me to start learning object oriented as well, but it >>>>>>seems I must be missing something fundamental. >>> >> >>No, this has nothing to do with objects, its just a broken algorithm. >> >> >>>>> median = Statistics.stats.median(*a) >>> >>>>>> n = (self.value[m] + self.value[m+1]) / 2 >>>>>>IndexError: tuple index out of range >>> >>> >>>>>>def median(self, *value_list): >>>>>> if len(self.value) % 2 == 1: >>>>>> m = (len(self.value) - 1)/2 >>>>>> n = self.value[m+1] >>>>>> else: >>>>>> m = len(self.value) / 2 >>>>>> m = int(m) >>>>>> n = (self.value[m] + self.value[m+1]) / 2 >>>>>> return n >>> >>>>Consider the case where the length of value is 2. >>>>We will use the else part of the branch. >>>>m will have value 1 >>>>The highest index is 1 because indexes start at zero >>>>so value[m+1] will fail with an index error. >> >>>>A similar error will happen when the list has only 1 entry >>>>since the highest index there will be zero. >> >>>>You need to rethink your rules for generating the indexes >>>>remembering that they start at zero. >> >> >> >>>>-- >>>>Alan Gauld >>>>Author of the Learn to Program web site >>http://www.alan-g.me.uk/ >> >>>>_______________________________________________ >> >>>>Tutor maillist - Tutor at python.org >>>>To unsubscribe or change subscription options: >>http://mail.python.org/mailman/listinfo/tutor >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu Feb 25 00:26:58 2010 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 24 Feb 2010 18:26:58 -0500 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: <610803.84007.qm@web86707.mail.ird.yahoo.com> References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> <98c3f7c51002231953h20d2483dp4420911bb819b4d1@mail.gmail.com> <98c3f7c51002240431k3a15308v1abc78bf23001aa@mail.gmail.com> <610803.84007.qm@web86707.mail.ird.yahoo.com> Message-ID: <98c3f7c51002241526w5bf73845xd185066325cdc9d1@mail.gmail.com> Thanks for the reply. I understand, but if self.value is any number other then 0, then the "for" will append to the square list, in which case square_list will always have some len greater than 0 when "value" is greater than 0? I'm just trying to understand the mechanics. I'm assuming that isn't the way the statement is evaluated? When I get home from work I'll work around it. Is this an occasion which is best suited for a try:, except statement? Or should it, in general, but checked with "if's". Which is more expensive? The rest of the code was in the prior email (please see below) Module 1: import Statistics a = [1,2,3,4,5,6,7,8,9,10] mean = Statistics.stats.mean(*a) median = Statistics.stats.median(*a) var = Statistics.stats.variance(*a) print(mean, median, var) print() Module 2: #!/usr/bin/python # Filename: Statistics.py import math value_list = [] class Statistics: def __init__(self, *value_list): self.value = value_list #self.average = mean(*value_list) self.square_list= [] def mean(self, *value_list): if len(self.value) == 0: ave = 0 else: ave = sum(self.value) / len(self.value) return ave def median(self, *value_list): if len(self.value) <= 2: n = self.mean(self.value) elif len(self.value) % 2 == 1: m = (len(self.value) - 1)/2 n = self.value[m+1] else: m = len(self.value) / 2 m = int(m) n = (self.value[m] + self.value[m+1]) / 2 return n def variance(self, *value_list): if self.value == 0: var = 0 else: average = self.mean(*self.value) for n in range(len(self.value)): square = (self.value[n] - average)**2 self.square_list.append(square) var = sum(self.square_list) / len(self.square_list) return var stats = Statistics(*value_list) On Wed, Feb 24, 2010 at 5:59 PM, ALAN GAULD wrote: > Forwarding to the list. > Please alweays use Reply All so others can comment too. > > I made a few changes, but I'm getting the same error on variance (see > below): > > Looks like a different error to me! > > It would seem to me that it should never evaluate if the denominator is > zero because of the if statement. > > But the if statement doesn't test whether len(self.square_list) is zero. > It tests whether self.value is zero. > > The other thing I don't understand is that the object that is being passed > into the instance is a list, but it seems to be a tuple once the object is > called. Why does this happen? Am I doing something additional wrong? > > Sorry, your code doesn't show any instances let alone lists being pased in? > > Alan G. > > File "C:\Python31\Lib\COI\Project\Statistics.py", line 39, in variance > var = sum(self.square_list) / len(self.square_list) > ZeroDivisionError: int division or modulo by zero > > #!/usr/bin/python > # Filename: Statistics.py > > import math > value_list = [] > class Statistics: > def __init__(self, *value_list): > self.value = value_list > #self.average = mean(*value_list) > self.square_list= [] > def mean(self, *value_list): > if len(self.value) == 0: > ave = 0 > else: > ave = sum(self.value) / len(self.value) > return ave > > def median(self, *value_list): > if len(self.value) <= 2: > n = self.mean(self.value) > elif len(self.value) % 2 == 1: > m = (len(self.value) - 1)/2 > n = self.value[m+1] > else: > m = len(self.value) / 2 > m = int(m) > n = (self.value[m] + self.value[m+1]) / 2 > return n > def variance(self, *value_list): > if self.value == 0: > var = 0 > else: > average = self.mean(*self.value) > for n in range(len(self.value)): > square = (self.value[n] - average)**2 > self.square_list.append(square) > var = sum(self.square_list) / len(self.square_list) > return var > > > On Wed, Feb 24, 2010 at 4:02 AM, Alan Gauld wrote: > >> >> "James Reynolds" wrote >> >> >> This thread inspired me to start learning object oriented as well, but it >>> seems I must be missing something fundamental. >>> >> >> No, this has nothing to do with objects, its just a broken algorithm. >> >> median = Statistics.stats.median(*a) >>> n = (self.value[m] + self.value[m+1]) / 2 >>> IndexError: tuple index out of range >>> >>> def median(self, *value_list): >>> if len(self.value) % 2 == 1: >>> m = (len(self.value) - 1)/2 >>> n = self.value[m+1] >>> else: >>> m = len(self.value) / 2 >>> m = int(m) >>> n = (self.value[m] + self.value[m+1]) / 2 >>> return n >>> >> >> Consider the case where the length of value is 2. >> We will use the else part of the branch. >> m will have value 1 >> The highest index is 1 because indexes start at zero >> so value[m+1] will fail with an index error. >> >> A similar error will happen when the list has only 1 entry >> since the highest index there will be zero. >> >> You need to rethink your rules for generating the indexes >> remembering that they start at zero. >> >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Feb 25 00:38:19 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 24 Feb 2010 17:38:19 -0600 Subject: [Tutor] Python-based address standardization script? In-Reply-To: References: Message-ID: On Wed, Feb 24, 2010 at 4:14 PM, Serdar Tumgoren wrote: > Hey folks, > Anyone know if there's a Python script floating out there to standardize > U.S. addresses? I couldn't find anything on ActiveState or by Googling...I'm > interested in something similar to this Perl module: > > http://search.cpan.org/~sderle/Geo-StreetAddress-US-0.99/US.pm > > Just curious if anyone's seen an implementation in Python. > > I could really use this too, I haven't been able to find one. Would you be interested in porting the Perl one? Maybe we could work on it if no one knows of any Python versions? -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Thu Feb 25 01:15:06 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 24 Feb 2010 19:15:06 -0500 Subject: [Tutor] Python-based address standardization script? In-Reply-To: References: Message-ID: > Hey folks, >> Anyone know if there's a Python script floating out there to standardize >> U.S. addresses? I couldn't find anything on ActiveState or by Googling...I'm >> interested in something similar to this Perl module: >> >> http://search.cpan.org/~sderle/Geo-StreetAddress-US-0.99/US.pm >> >> Just curious if anyone's seen an implementation in Python. >> >> I could really use this too, I haven't been able to find one. Would you > be interested in porting the Perl one? Maybe we could work on it if no one > knows of any Python versions? > Hey Luke, I'm definitely interested in porting it over and would be happy to collaborate on that project. I know a lot of folks that would *love* to get their hands on this type of code. Should I start a project on github? (I'm open to other VCS's that offer free web hosting for open source...) Anyone who wants to join in, just shout it out. Serdar -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 25 01:33:50 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Feb 2010 00:33:50 -0000 Subject: [Tutor] Strange list behaviour in classes References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com><98c3f7c51002231953h20d2483dp4420911bb819b4d1@mail.gmail.com><98c3f7c51002240431k3a15308v1abc78bf23001aa@mail.gmail.com><610803.84007.qm@web86707.mail.ird.yahoo.com> <98c3f7c51002241526w5bf73845xd185066325cdc9d1@mail.gmail.com> Message-ID: "James Reynolds" wrote > I understand, but if self.value is any number other then 0, then the > "for" > will append to the square list, in which case square_list will always > have > some len greater than 0 when "value" is greater than 0? And if value does equal zero? Actually I'm confused by value because you treat it as both an integer and a collection in different places? > Is this an occasion which is best suited for a try:, except statement? Or > should it, in general, but checked with "if's". Which is more expensive? try/except is the Python way :-) > def variance(self, *value_list): > if self.value == 0: > var = 0 > else: > average = self.mean(*self.value) > for n in range(len(self.value)): > square = (self.value[n] - average)**2 > self.square_list.append(square) > var = sum(self.square_list) / len(self.square_list) > return var -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Thu Feb 25 01:39:41 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 24 Feb 2010 18:39:41 -0600 Subject: [Tutor] Python-based address standardization script? In-Reply-To: References: Message-ID: On Wed, Feb 24, 2010 at 6:15 PM, Serdar Tumgoren wrote: > > Hey folks, >>> Anyone know if there's a Python script floating out there to standardize >>> U.S. addresses? I couldn't find anything on ActiveState or by Googling...I'm >>> interested in something similar to this Perl module: >>> >>> http://search.cpan.org/~sderle/Geo-StreetAddress-US-0.99/US.pm >>> >>> Just curious if anyone's seen an implementation in Python. >>> >>> I could really use this too, I haven't been able to find one. Would you >> be interested in porting the Perl one? Maybe we could work on it if no one >> knows of any Python versions? >> > > Hey Luke, > > I'm definitely interested in porting it over and would be happy to > collaborate on that project. I know a lot of folks that would *love* to get > their hands on this type of code. Should I start a project on github? (I'm > open to other VCS's that offer free web hosting for open source...) > > Anyone who wants to join in, just shout it out. > > Sure, just send me a link when it's up. I don't have any experience with git but I've wanted to learn so go ahead and use that. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Thu Feb 25 02:21:58 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 24 Feb 2010 20:21:58 -0500 Subject: [Tutor] Python-based address standardization script? In-Reply-To: References: Message-ID: > Sure, just send me a link when it's up. I don't have any experience with > git but I've wanted to learn so go ahead and use that. > > Okay - the git repo is here: http://github.com/zstumgoren/python-addressparser You can clone it with the following shell command (assuming you've installed git): git clone git://github.com/zstumgoren/python-addressparser.git And if it helps, here are a few git resources: http://www.kernel.org/pub/software/scm/git/docs/ http://book.git-scm.com/ http://progit.org/book/ Anyone else interested in contributing, ping us offline or just clone away and push back your changes. Cheers! Serdar -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu Feb 25 03:36:23 2010 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 24 Feb 2010 21:36:23 -0500 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> <98c3f7c51002231953h20d2483dp4420911bb819b4d1@mail.gmail.com> <98c3f7c51002240431k3a15308v1abc78bf23001aa@mail.gmail.com> <610803.84007.qm@web86707.mail.ird.yahoo.com> <98c3f7c51002241526w5bf73845xd185066325cdc9d1@mail.gmail.com> Message-ID: <98c3f7c51002241836o10d058a7sb6f12e5b57241f02@mail.gmail.com> Thank you! I think I have working in the right direction. I have one more question related to this module. I had to move everything to a single module, but what I would like to do is have this class in a file by itself so I can call this from other modules. when it was in separate modules it ran with all 0's in the output. Here is the code in one module: #import Statistics class Statistics: def __init__(self, *value_list): self.value = value_list self.square_list= [] def mean(self, *value_list): try : ave = sum(self.value) / len(self.value) except ZeroDivisionError: ave = 0 return ave def median(self, *value_list): if len(self.value) <= 2: n = self.mean(self.value) elif len(self.value) % 2 == 1: m = (len(self.value) - 1)/2 n = self.value[m+1] else: m = len(self.value) / 2 m = int(m) n = (self.value[m-1] + self.value[m]) / 2 return n def variance(self, *value_list): average = self.mean(*self.value) for n in range(len(self.value)): square = (self.value[n] - average)**2 self.square_list.append(square) try: var = sum(self.square_list) / len(self.square_list) except ZeroDivisionError: var = 0 return var def stdev(self, *value_list): var = self.variance(*self.value) sdev = var**(1/2) return sdev def zscore(self, x, *value_list): average = self.mean(self.value) sdev = self.stdev(self.value) try: z = (x - average) / sdev except ZeroDivisionError: z = 0 return z a = [1,2,3,4,5,6,7,8,9,10] stats = Statistics(*a) mean = stats.mean(*a) median = stats.median(*a) var = stats.variance(*a) stdev = stats.stdev(*a) z = stats.zscore(5, *a) print(mean, median, var, stdev, z) print() On Wed, Feb 24, 2010 at 7:33 PM, Alan Gauld wrote: > > "James Reynolds" wrote > > I understand, but if self.value is any number other then 0, then the "for" >> will append to the square list, in which case square_list will always have >> some len greater than 0 when "value" is greater than 0? >> > > And if value does equal zero? > > Actually I'm confused by value because you treat it as both an > integer and a collection in different places? > > > Is this an occasion which is best suited for a try:, except statement? Or >> should it, in general, but checked with "if's". Which is more expensive? >> > > try/except is the Python way :-) > > > def variance(self, *value_list): >> if self.value == 0: >> var = 0 >> else: >> average = self.mean(*self.value) >> for n in range(len(self.value)): >> square = (self.value[n] - average)**2 >> self.square_list.append(square) >> var = sum(self.square_list) / len(self.square_list) >> return var >> > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From galaxywatcher at gmail.com Thu Feb 25 08:02:48 2010 From: galaxywatcher at gmail.com (galaxywatcher at gmail.com) Date: Thu, 25 Feb 2010 14:02:48 +0700 Subject: [Tutor] Omitting lines matching a list of strings from a file In-Reply-To: References: Message-ID: <81F5DEE7-8EB1-4758-B57C-2CA44B92CC3E@gmail.com> I am trying to output a list of addresses that do not match a list of State abbreviations. What I have so far is: def main(): infile = open("list.txt", "r") for line in infile: state = line[146:148] omit_states = ['KS', 'KY', 'MA', 'ND', 'NE', 'NJ', 'PR', 'RI', 'SD', 'VI', 'VT', 'WI'] for n in omit_states: if state != n: print line infile.close() main() This outputs multiple duplicate lines. The strange thing is that if I change 'if state == n:' then I correctly output all matching lines. But I don't want that. I want to output all lines that do NOT match the States in the omit_states list. I am probably overlooking something very simple. Thanks in advance. From cwitts at compuscan.co.za Thu Feb 25 08:15:20 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 25 Feb 2010 09:15:20 +0200 Subject: [Tutor] Omitting lines matching a list of strings from a file In-Reply-To: <81F5DEE7-8EB1-4758-B57C-2CA44B92CC3E@gmail.com> References: <81F5DEE7-8EB1-4758-B57C-2CA44B92CC3E@gmail.com> Message-ID: <4B862388.1030108@compuscan.co.za> galaxywatcher at gmail.com wrote: > I am trying to output a list of addresses that do not match a list of > State abbreviations. What I have so far is: > > def main(): > infile = open("list.txt", "r") > for line in infile: > state = line[146:148] > omit_states = ['KS', 'KY', 'MA', 'ND', 'NE', 'NJ', 'PR', 'RI', > 'SD', 'VI', 'VT', 'WI'] > for n in omit_states: > if state != n: > print line > infile.close() > main() > > This outputs multiple duplicate lines. The strange thing is that if I > change 'if state == n:' then I correctly output all matching lines. > But I don't want that. I want to output all lines that do NOT match > the States in the omit_states list. > > I am probably overlooking something very simple. Thanks in advance. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The more pythonic way of doing it would be to use `not in` like listed below. You should consider normalizing your input (state) by using .upper() unless you know for certain it's always upper-case. state = line[146:148] omit_states = ['KS', 'KY', ..., 'VT', 'WI'] if state not in omit_states: print line -- Kind Regards, Christian Witts Business Intelligence C o m p u s c a n | Confidence in Credit Telephone: +27 21 888 6000 National Cell Centre: 0861 51 41 31 Fax: +27 21 413 2424 E-mail: cwitts at compuscan.co.za NOTE: This e-mail (including attachments )is subject to the disclaimer published at: http://www.compuscan.co.za/live/content.php?Item_ID=494. If you cannot access the disclaimer, request it from email.disclaimer at compuscan.co.za or 0861 514131. National Credit Regulator Credit Bureau Registration No. NCRCB6 From reed at reedobrien.com Thu Feb 25 08:17:53 2010 From: reed at reedobrien.com (Reed O'Brien) Date: Thu, 25 Feb 2010 02:17:53 -0500 Subject: [Tutor] Omitting lines matching a list of strings from a file In-Reply-To: <81F5DEE7-8EB1-4758-B57C-2CA44B92CC3E@gmail.com> References: <81F5DEE7-8EB1-4758-B57C-2CA44B92CC3E@gmail.com> Message-ID: <38870687-0AC6-45DA-8CA6-66A5BAF001C9@reedobrien.com> > def main(): > infile = open("list.txt", "r") > for line in infile: > state = line[146:148] > omit_states = ['KS', 'KY', 'MA', 'ND', 'NE', 'NJ', 'PR', > 'RI', 'SD', 'VI', 'VT', 'WI'] > for n in omit_states: > if state != n: > print line > infile.close() > main() If state not in omit_states: process_line(line) ~ro -- Sent from a mobile device. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 25 09:25:31 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 25 Feb 2010 08:25:31 +0000 (GMT) Subject: [Tutor] Strange list behaviour in classes In-Reply-To: <98c3f7c51002241836o10d058a7sb6f12e5b57241f02@mail.gmail.com> References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> <98c3f7c51002231953h20d2483dp4420911bb819b4d1@mail.gmail.com> <98c3f7c51002240431k3a15308v1abc78bf23001aa@mail.gmail.com> <610803.84007.qm@web86707.mail.ird.yahoo.com> <98c3f7c51002241526w5bf73845xd185066325cdc9d1@mail.gmail.com> <98c3f7c51002241836o10d058a7sb6f12e5b57241f02@mail.gmail.com> Message-ID: <118504.28632.qm@web86705.mail.ird.yahoo.com> One point: class Statistics: def __init__(self, *value_list): >self.value = value_list >self.square_list= [] >def mean(self, *value_list): >try : >ave = sum(self.value) / len(self.value) >except ZeroDivisionError: >ave = 0 >return ave You don't use value_list here you use self.value. So you don't need value_list def median(self, *value_list): >if len(self.value) <= 2: >n = self.mean(self.value) >elif len(self.value) % 2 == 1: >m = (len(self.value) - 1)/2 >n = self.value[m+1] >else: >m = len(self.value) / 2 >m = int(m) >n = (self.value[m-1] + self.value[m]) / 2 >return n Same here... def variance(self, *value_list): >average = self.mean(*self.value) >for n in range(len(self.value)): >square = (self.value[n] - average)**2 >self.square_list.append(square) >try: >var = sum(self.square_list) / len(self.square_list) >except ZeroDivisionError: >var = 0 >return var And here... def stdev(self, *value_list): >var = self.variance(*self.value) >sdev = var**(1/2) >return sdev And here... def zscore(self, x, *value_list): >average = self.mean(self.value) >sdev = self.stdev(self.value) >try: >z = (x - average) / sdev >except ZeroDivisionError: >z = 0 >return z And here.... a = [1,2,3,4,5,6,7,8,9,10] >stats = Statistics(*a) >So you need the *a here mean = stats.mean(*a) >median = stats.median(*a) >var = stats.variance(*a) >stdev = stats.stdev(*a) >z = stats.zscore(5, *a) >But you don't need to pass in *a in any of these calls. Its already stored in the object. Also instead of returning these values (or as well as) you could have stored them as variables inside the object. print(mean, median, var, stdev, z) > >In which case this would become print(self.theMean,self.theMedian, etc...) Just an alternative for consideration. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Thu Feb 25 09:29:29 2010 From: timomlists at gmail.com (Timo) Date: Thu, 25 Feb 2010 09:29:29 +0100 Subject: [Tutor] Cannot open SQLite database In-Reply-To: <476167.35894.qm@web86708.mail.ird.yahoo.com> References: <4B84E5A0.6010105@gmail.com> <476167.35894.qm@web86708.mail.ird.yahoo.com> Message-ID: <4B8634E9.8050104@gmail.com> On 25-02-10 00:03, ALAN GAULD wrote: > Does the file actually exist where you say it does? > > It doesn't need to exist, it will be created if it isn't found. > > Of course I should have known that! > It points to the path/folder then... > > It is on Windows XP, and in the logfile it says it uses the directory: > C:\Documents and Settings\user\Application Data\myapp > > That directory should always be writeable for the user, no? > > > Not on my PC its Read Only.... > > And I have administrator rights. > A normal user is even more likely to be limited. > And a Guest account definitely would be. Hmm that's strange. I thought the application data folder is the correct folder on Windows systems to put your configuration files. And until now, it worked perfectly for every user. What should be the correct folder then? Cheers, Timo > > HTH, > > Alan G. > From alan.gauld at btinternet.com Thu Feb 25 09:49:43 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 25 Feb 2010 08:49:43 +0000 (GMT) Subject: [Tutor] Cannot open SQLite database In-Reply-To: <4B8634E9.8050104@gmail.com> References: <4B84E5A0.6010105@gmail.com> <476167.35894.qm@web86708.mail.ird.yahoo.com> <4B8634E9.8050104@gmail.com> Message-ID: <369712.40981.qm@web86705.mail.ird.yahoo.com> > > It is on Windows XP, and in the logfile it says it uses the directory: > > C:\Documents and Settings\user\Application Data\myapp > > > > That directory should always be writeable for the user, no? > > > > Not on my PC its Read Only.... > > > > And I have administrator rights. > > A normal user is even more likely to be limited. > > And a Guest account definitely would be. > Hmm that's strange. I thought the application data folder is the correct > folder on Windows systems to put your configuration files. And until > now, it worked perfectly for every user. > > What should be the correct folder then? I don't know! To be honest I was surprised by the result too. Personally I tend to either use the application folder or the registry. But the app folder doesn't work for user specific settings unless you have a separate file based on user ID. Its very odd. In fact Windows explorer appears to be lying. I just tried creating a file using Python and it worked perfectly. But Explorer definitely claims its R/Only! I also tried the ATTRIB command from DOS and it does not show it as Read only. Cygwin shows it as readonly for world access but open for user and group. The security tab in exporer shows it read/write for admins and me. (It doesn't show a world setting) So I think that was a red herring, sorry. It also looks like the Read Only check box in the main Explorer property dialog tab doesn't mean what it says... Alan G. From timomlists at gmail.com Thu Feb 25 10:21:56 2010 From: timomlists at gmail.com (Timo) Date: Thu, 25 Feb 2010 10:21:56 +0100 Subject: [Tutor] Cannot open SQLite database In-Reply-To: <369712.40981.qm@web86705.mail.ird.yahoo.com> References: <4B84E5A0.6010105@gmail.com> <476167.35894.qm@web86708.mail.ird.yahoo.com> <4B8634E9.8050104@gmail.com> <369712.40981.qm@web86705.mail.ird.yahoo.com> Message-ID: 2010/2/25 ALAN GAULD > > > What should be the correct folder then? > > I don't know! To be honest I was surprised by the result too. > Personally I tend to either use the application folder or the registry. > But the app folder doesn't work for user specific settings unless > you have a separate file based on user ID. > > Its very odd. > > In fact Windows explorer appears to be lying. I just tried creating > a file using Python and it worked perfectly. But Explorer definitely > claims its R/Only! I also tried the ATTRIB command from DOS > and it does not show it as Read only. > > Cygwin shows it as readonly for world access but open for user > and group. The security tab in exporer shows it read/write for > admins and me. (It doesn't show a world setting) > > So I think that was a red herring, sorry. > It also looks like the Read Only check box in the main Explorer > property dialog tab doesn't mean what it says... > > Alan G. > I just thought of something, and it can't be that the folder isn't writeable. Because I asked the user for the logfile that my program produces, and it is located in the same folder as where the database should be. So if the folder wasn't writeable, the creation of the logfile would have caused an error too. So I'm a bit stuck about this one. Timo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 25 10:24:31 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Feb 2010 09:24:31 -0000 Subject: [Tutor] Omitting lines matching a list of strings from a file References: <81F5DEE7-8EB1-4758-B57C-2CA44B92CC3E@gmail.com> Message-ID: wrote >I am trying to output a list of addresses that do not match a list of > State abbreviations. What I have so far is: > > def main(): > infile = open("list.txt", "r") > for line in infile: > state = line[146:148] > omit_states = ['KS', 'KY', 'MA', 'ND', 'NE', 'NJ', 'PR', > 'RI', 'SD', 'VI', 'VT', 'WI'] > for n in omit_states: > if state != n: > print line This prints it for every entry in omit_states. You probably want to add a break command after the print But I would do this with a list comprehension or generator expression (depending on your Python version): lines = [line for line in infile if line[146:148] not in omit_states] print '\n'.join(lines) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Thu Feb 25 12:22:30 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 25 Feb 2010 06:22:30 -0500 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: <98c3f7c51002241836o10d058a7sb6f12e5b57241f02@mail.gmail.com> References: <333efb451002221528n4a458c1cnaa70a13903e1be0f@mail.gmail.com> <98c3f7c51002231953h20d2483dp4420911bb819b4d1@mail.gmail.com> <98c3f7c51002240431k3a15308v1abc78bf23001aa@mail.gmail.com> <610803.84007.qm@web86707.mail.ird.yahoo.com> <98c3f7c51002241526w5bf73845xd185066325cdc9d1@mail.gmail.com> <98c3f7c51002241836o10d058a7sb6f12e5b57241f02@mail.gmail.com> Message-ID: <4B865D76.8050905@ieee.org> James Reynolds wrote: > Thank you! I think I have working in the right direction. I have one more > question related to this module. > > I had to move everything to a single module, but what I would like to do is > have this class in a file by itself so I can call this from other modules. > when it was in separate modules it ran with all 0's in the output. > > Here is the code in one module: > > #import Statistics > > class Statistics: > def __init__(self, *value_list): > self.value = value_list > self.square_list= [] > def mean(self, *value_list): > try : > ave = sum(self.value) / len(self.value) > except ZeroDivisionError: > ave = 0 > return ave > > def median(self, *value_list): > if len(self.value) <= 2: > n = self.mean(self.value) > elif len(self.value) % 2 == 1: > m = (len(self.value) - 1)/2 > n = self.value[m+1] > else: > m = len(self.value) / 2 > m = int(m) > n = (self.value[m-1] + self.value[m]) / 2 > return n > def variance(self, *value_list): > average = self.mean(*self.value) > for n in range(len(self.value)): > square = (self.value[n] - average)**2 > self.square_list.append(square) > try: > var = sum(self.square_list) / len(self.square_list) > except ZeroDivisionError: > var = 0 > return var > > def stdev(self, *value_list): > var = self.variance(*self.value) > sdev = var**(1/2) > return sdev > def zscore(self, x, *value_list): > average = self.mean(self.value) > sdev = self.stdev(self.value) > try: > z = (x - average) / sdev > except ZeroDivisionError: > z = 0 > return z > > > > a = [1,2,3,4,5,6,7,8,9,10] > stats = Statistics(*a) > mean = stats.mean(*a) > median = stats.median(*a) > var = stats.variance(*a) > stdev = stats.stdev(*a) > z = stats.zscore(5, *a) > print(mean, median, var, stdev, z) > print() > > > > On Wed, Feb 24, 2010 at 7:33 PM, Alan Gauld wrote: > > >> "James Reynolds" wrote >> >> I understand, but if self.value is any number other then 0, then the "for" >> >>> will append to the square list, in which case square_list will always have >>> some len greater than 0 when "value" is greater than 0? >>> >>> >> And if value does equal zero? >> >> Actually I'm confused by value because you treat it as both an >> integer and a collection in different places? >> >> >> Is this an occasion which is best suited for a try:, except statement? Or >> >>> should it, in general, but checked with "if's". Which is more expensive? >>> >>> >> try/except is the Python way :-) >> >> >> def variance(self, *value_list): >> >>> if self.value == 0: >>> var = 0 >>> else: >>> average = self.mean(*self.value) >>> for n in range(len(self.value)): >>> square = (self.value[n] - average)**2 >>> self.square_list.append(square) >>> var = sum(self.square_list) / len(self.square_list) >>> return var >>> >>> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> > The indentation in your code is lost when I look for it -- everything's butted up against the left margin except for a single space before def variance. This makes it very hard to follow, so I've ignored the thread till now. This may be caused by the mail digest logic, or it may because you're posting online, and don't tell it to leave the code portion unformatted. But either way, you should find a way to leave the code indented as Python would see it. If you're posting by mail, be sure and send it as text. But a few things I notice in your code: You keep using the * notation on your formal parameters. That's what turns a list into a tuple. And you pass those lists into methods (like median()) which already have access to the data in the object, which is very confusing. If the caller actually passes something different there, he's going to be misled, since the argument is ignored. Also, in method variance() you append to the self.square_list. So if it gets called more than once, the list will continue to grow. Since square_list is only referenced within the one method, why not just define it there, and remove it as a instance attribute? If I were you, I'd remove the asterisk from both the __init__() method parameter, and from the caller in top-level code. You're building a list, and passing it. Why mess with turning it into multiple arguments, and then back to a tuple? Then I'd remove the spurious arguments to mean(), variance(), stdev() and zscore(). There are a few other things, but this should make it cleaner. DaveA From wprins at gmail.com Thu Feb 25 13:09:23 2010 From: wprins at gmail.com (Walter Prins) Date: Thu, 25 Feb 2010 12:09:23 +0000 Subject: [Tutor] Strange list behaviour in classes In-Reply-To: <4B865D76.8050905@ieee.org> References: <98c3f7c51002231953h20d2483dp4420911bb819b4d1@mail.gmail.com> <98c3f7c51002240431k3a15308v1abc78bf23001aa@mail.gmail.com> <610803.84007.qm@web86707.mail.ird.yahoo.com> <98c3f7c51002241526w5bf73845xd185066325cdc9d1@mail.gmail.com> <98c3f7c51002241836o10d058a7sb6f12e5b57241f02@mail.gmail.com> <4B865D76.8050905@ieee.org> Message-ID: <7d961c461002250409k710dab5co2b332f035ba30ee3@mail.gmail.com> On 25 February 2010 11:22, Dave Angel wrote: > The indentation in your code is lost when I look for it -- everything's > butted up against the left margin except for a single space before def > variance. This makes it very hard to follow, so I've ignored the thread > till now. This may be caused by the mail digest logic, or it may because > you're posting online, and don't tell it to leave the code portion > unformatted. This is probably something your end, I read and post from within Google mail (as well as from Thunderbird occassionally) and I have no trouble seeing the indentation. (I don't use the mail digest, I receive single emails/posts.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From raghavendra.gv.vanam at gmail.com Thu Feb 25 13:17:34 2010 From: raghavendra.gv.vanam at gmail.com (vanam) Date: Thu, 25 Feb 2010 17:47:34 +0530 Subject: [Tutor] [Installing Spyder IDE]:Help Message-ID: <4499cb6a1002250417j631fb92dx92a5ce32a9c9705b@mail.gmail.com> I have been trying to install spyder ide but of no avail. Downloaded and installed spyder-1.03_py26.exe I have downloaded pyqt4 for that purpose(Direct Installer) pyqt-py2.6-gpl-4.7-1.exe after installing the above softwares and then launching Spyder it is showing initialising and gets disappears. Is that something or dependency i have missed to install? -- Raghavendra Vanam -- Raghavendra Vanam From galaxywatcher at gmail.com Thu Feb 25 14:42:21 2010 From: galaxywatcher at gmail.com (galaxywatcher at gmail.com) Date: Thu, 25 Feb 2010 20:42:21 +0700 Subject: [Tutor] Omitting lines matching a list of strings from a file In-Reply-To: References: Message-ID: <86405F1B-54DF-422C-AC63-01D79B014FAA@gmail.com> > But I would do this with a list comprehension or generator > expression (depending on your Python version): > > > lines = [line for line in infile if line[146:148] not in omit_states] > print '\n'.join(lines) That's very helpful. Thanks. One formatting detail: there is a blank line after each line printed, how do I ged rid of the extra blank lines? From cwitts at compuscan.co.za Thu Feb 25 14:54:52 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 25 Feb 2010 15:54:52 +0200 Subject: [Tutor] Omitting lines matching a list of strings from a file In-Reply-To: <86405F1B-54DF-422C-AC63-01D79B014FAA@gmail.com> References: <86405F1B-54DF-422C-AC63-01D79B014FAA@gmail.com> Message-ID: <4B86812C.2020902@compuscan.co.za> galaxywatcher at gmail.com wrote: >> But I would do this with a list comprehension or generator >> expression (depending on your Python version): >> >> >> lines = [line for line in infile if line[146:148] not in omit_states] >> print '\n'.join(lines) > > That's very helpful. Thanks. One formatting detail: there is a blank > line after each line printed, how do I ged rid of the extra blank lines? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > lines = [line.strip() for line in infile if line[146:148] not in omit_states] print '\n'.join(lines) or alternatively lines = [line for line in infile if line[146:148] not in omit_states] print ''.join(lines) Just remember that doing a list comprehension like that on a large file will drastically reduce the speed of your application as well as introduce memory bloat. -- Kind Regards, Christian Witts From ksterling at mindspring.com Thu Feb 25 14:52:28 2010 From: ksterling at mindspring.com (Ken Oliver) Date: Thu, 25 Feb 2010 08:52:28 -0500 (EST) Subject: [Tutor] Strange list behaviour in classes Message-ID: <20198414.1267105949528.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> An HTML attachment was scrubbed... URL: From michael at shamirlens.co.uk Thu Feb 25 16:18:46 2010 From: michael at shamirlens.co.uk (Michael M Mason) Date: Thu, 25 Feb 2010 15:18:46 -0000 Subject: [Tutor] Cannot open SQLite database In-Reply-To: <369712.40981.qm@web86705.mail.ird.yahoo.com> References: <4B84E5A0.6010105@gmail.com> <476167.35894.qm@web86708.mail.ird.yahoo.com><4B8634E9.8050104@gmail.com> <369712.40981.qm@web86705.mail.ird.yahoo.com> Message-ID: <2B7AA81C577B0942A14C2B388867E2C70E08CF@harry.shamirlens.co.uk> ALAN GAULD wrote on 25 February 2010 at 08:50:- > So I think that was a red herring, sorry. > It also looks like the Read Only check box in the main > Explorer property dialog tab doesn't mean what it says... Doesn't the Read Only checkbox have a coloured square rather than a tick? AFAIK the coloured square is intended to mean "doesn't apply", and you should see the same thing on all folders. You can tick the checkbox and click the "Apply" button to make all the files in the folder Read-Only in one easy move. It doesn't make the folder Read-Only, and if you close and re-open the Properties dialog after ticking the checkbox you'll find the coloured square will reappear. -- Michael From mail at timgolden.me.uk Thu Feb 25 16:29:19 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 25 Feb 2010 15:29:19 +0000 Subject: [Tutor] Cannot open SQLite database In-Reply-To: <2B7AA81C577B0942A14C2B388867E2C70E08CF@harry.shamirlens.co.uk> References: <4B84E5A0.6010105@gmail.com> <476167.35894.qm@web86708.mail.ird.yahoo.com><4B8634E9.8050104@gmail.com> <369712.40981.qm@web86705.mail.ird.yahoo.com> <2B7AA81C577B0942A14C2B388867E2C70E08CF@harry.shamirlens.co.uk> Message-ID: <4B86974F.8020603@timgolden.me.uk> On 25/02/2010 15:18, Michael M Mason wrote: > ALAN GAULD wrote on 25 February 2010 at 08:50:- > >> So I think that was a red herring, sorry. >> It also looks like the Read Only check box in the main >> Explorer property dialog tab doesn't mean what it says... > > Doesn't the Read Only checkbox have a coloured square rather than > a tick? > > AFAIK the coloured square is intended to mean "doesn't apply", and > you should see the same thing on all folders. You can tick the > checkbox and click the "Apply" button to make all the files in the > folder Read-Only in one easy move. It doesn't make the folder > Read-Only, and if you close and re-open the Properties dialog after > ticking the checkbox you'll find the coloured square will reappear. > Haven't been following this thread, but just picking up on this: the read-only attribute on folders means: this is a special folder (eg My Documents). There's no way to make a directory read-only like this... TJG From memilanuk at gmail.com Thu Feb 25 16:47:07 2010 From: memilanuk at gmail.com (Monte Milanuk) Date: Thu, 25 Feb 2010 07:47:07 -0800 Subject: [Tutor] raising number to a power Message-ID: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> Is there a benefit (besides brevity) one way or the other between using: import math ... math.pow(x,y) # x raised to the power y vs. x**y ? Thanks, Monte -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Thu Feb 25 17:02:12 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 25 Feb 2010 17:02:12 +0100 Subject: [Tutor] raising number to a power In-Reply-To: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> Message-ID: Monte Milanuk, 25.02.2010 16:47: > Is there a benefit (besides brevity) one way or the other between using: > > import math > ... > math.pow(x,y) # x raised to the power y > > vs. > > x**y > > ? Did you try it? >>> import math >>> print(math.pow(4,4)) 256.0 >>> 4**4 256 >>> 4.0**4 256.0 Stefan From stefan_ml at behnel.de Thu Feb 25 17:08:16 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 25 Feb 2010 17:08:16 +0100 Subject: [Tutor] raising number to a power In-Reply-To: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> Message-ID: Monte Milanuk, 25.02.2010 16:47: > Is there a benefit (besides brevity) one way or the other between using: > > import math > ... > math.pow(x,y) # x raised to the power y > > vs. > > x**y > > ? You might also be interested in this: http://docs.python.org/reference/datamodel.html#emulating-numeric-types The difference is that math.pow() is a function that works on two float values, whereas '**' is an operator that can work on anything, including your own classes. It's the number types that define the operator as meaning the power function, not the operator itself. Stefan From memilanuk at gmail.com Thu Feb 25 18:27:06 2010 From: memilanuk at gmail.com (Monte Milanuk) Date: Thu, 25 Feb 2010 09:27:06 -0800 Subject: [Tutor] raising number to a power In-Reply-To: References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> Message-ID: <6f26596c1002250927m25ca01bbkc73a8c36d996e87c@mail.gmail.com> So... pow(4,4) is equivalent to 4**4, which works on anything - integers, floats, etc., but math.pow(4,4) only works on floats... and in this case it converts or interprets (4,4) as (4.0,4.0), hence returning a float: 256.0. Is that about right? Thanks, Monte -------------- next part -------------- An HTML attachment was scrubbed... URL: From ricaraoz at gmail.com Thu Feb 25 19:34:39 2010 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 25 Feb 2010 15:34:39 -0300 Subject: [Tutor] raising number to a power In-Reply-To: References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> Message-ID: <4B86C2BF.1020305@gmail.com> Stefan Behnel wrote: > Monte Milanuk, 25.02.2010 16:47: > >> Is there a benefit (besides brevity) one way or the other between using: >> >> import math >> ... >> math.pow(x,y) # x raised to the power y >> >> vs. >> >> x**y >> >> ? >> > > You might also be interested in this: > > http://docs.python.org/reference/datamodel.html#emulating-numeric-types > > The difference is that math.pow() is a function that works on two float > values, whereas '**' is an operator that can work on anything, including > your own classes. It's the number types that define the operator as meaning > the power function, not the operator itself. > So why would the coders of the math module go to the trouble of creating the pow function? Did they create a sum function and a subtract function? It seems to me the question has not been properly answered. When to use one, when to use the other? If you don't know the answer it's all right. I don't know it either. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ricaraoz at gmail.com Thu Feb 25 19:35:05 2010 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 25 Feb 2010 15:35:05 -0300 Subject: [Tutor] raising number to a power In-Reply-To: References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> Message-ID: <4B86C2D9.9090903@gmail.com> Stefan Behnel wrote: > Monte Milanuk, 25.02.2010 16:47: > >> Is there a benefit (besides brevity) one way or the other between using: >> >> import math >> ... >> math.pow(x,y) # x raised to the power y >> >> vs. >> >> x**y >> >> ? >> > > Did you try it? > > >>> import math > >>> print(math.pow(4,4)) > 256.0 > >>> 4**4 > 256 > >>> 4.0**4 > 256.0 > > Stefan > Yes, I tried it. Now, is there a benefit (besides brevity) one way or the other? -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Feb 25 19:44:21 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 25 Feb 2010 12:44:21 -0600 Subject: [Tutor] raising number to a power In-Reply-To: <4B86C2BF.1020305@gmail.com> References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> <4B86C2BF.1020305@gmail.com> Message-ID: <333efb451002251044h1e44fbeale441191ea5d99f53@mail.gmail.com> 2010/2/25 Ricardo Ar?oz > Stefan Behnel wrote: > So why would the coders of the math module go to the trouble of creating > the pow function? Did they create a sum function and a subtract function? > It seems to me the question has not been properly answered. When to use > one, when to use the other? > If you don't know the answer it's all right. I don't know it either. > Only a theory: Perhaps for familiarities sake - many other languages (and all of them that I know with a math library) have something like, if not, math.pow(base, exp), so it could be they wanted to allow that similarity... or it could just be from way back in the early days of Python? just my thoughts on the subject, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Thu Feb 25 19:55:47 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 25 Feb 2010 19:55:47 +0100 Subject: [Tutor] raising number to a power In-Reply-To: <6f26596c1002250927m25ca01bbkc73a8c36d996e87c@mail.gmail.com> References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> <6f26596c1002250927m25ca01bbkc73a8c36d996e87c@mail.gmail.com> Message-ID: Monte Milanuk, 25.02.2010 18:27: > So... pow(4,4) is equivalent to 4**4, which works on anything - integers, > floats, etc. Correct, e.g. >>> class Test(object): ... def __pow__(self, other, modulo=None): ... print("POW!") ... return 'tutu' ... >>> pow(Test(), 4) POW! 'tutu' >>> Test() ** 4 POW! 'tutu' But: >>> pow(Test(), 4, 5) POW! 'tutu' The pow() function has a 3-argument form that efficiently calculates the modulo. There is no operator for that, and, IMHO, that's the raison d'?tre for the pow() function in the first place. > but math.pow(4,4) only works on floats... and in this case it > converts or interprets (4,4) as (4.0,4.0), hence returning a float: 256.0. > Is that about right? Yes. Read the docs: """ 10.2. math ? Mathematical functions This module is always available. It provides access to the mathematical functions defined by the C standard. [...] The following functions are provided by this module. Except when explicitly noted otherwise, all return values are floats. """ http://docs.python.org/library/math.html So these are purely numeric and therefore actually pretty fast functions, which is /their/ raison d'?tre. $ python3.1 -m timeit -s 'from math import pow as mpow' 'pow(2,2)' 1000000 loops, best of 3: 0.562 usec per loop $ python3.1 -m timeit -s 'from math import pow as mpow' 'mpow(2,2)' 10000000 loops, best of 3: 0.18 usec per loop However: $ python3.1 -m timeit -s 'from math import pow as mpow' '2**2' 10000000 loops, best of 3: 0.0247 usec per loop Stefan From steve at pearwood.info Thu Feb 25 19:57:00 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 26 Feb 2010 05:57:00 +1100 Subject: [Tutor] raising number to a power In-Reply-To: <6f26596c1002250927m25ca01bbkc73a8c36d996e87c@mail.gmail.com> References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> <6f26596c1002250927m25ca01bbkc73a8c36d996e87c@mail.gmail.com> Message-ID: <201002260557.01484.steve@pearwood.info> On Fri, 26 Feb 2010 04:27:06 am Monte Milanuk wrote: > So... pow(4,4) is equivalent to 4**4, which works on anything - > integers, floats, etc., but math.pow(4,4) only works on floats... and > in this case it converts or interprets (4,4) as (4.0,4.0), hence > returning a float: 256.0. Is that about right? Pretty much, but the builtin pow also takes an optional third argument: >>> pow(4, 4, 65) # same as 4**4 % 65 only more efficient 61 By the way, are you aware that you can get help in the interactive interpreter? help(pow) -- Steven D'Aprano From salrayes2 at gmail.com Thu Feb 25 20:00:10 2010 From: salrayes2 at gmail.com (salaiman alrayes) Date: Thu, 25 Feb 2010 14:00:10 -0500 Subject: [Tutor] raising number to a power In-Reply-To: <4B86C2D9.9090903@gmail.com> References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> <4B86C2D9.9090903@gmail.com> Message-ID: <68F1B4A0-AC3D-4D0B-BF0A-12BA3C1554BC@gmail.com> i'm not an expert, but i have worked with "import math". i believe if you use import math; it will make you capable of using all kinds of math in python (sin,cos,sin^-1......) i recommend you google "python math" or "python import math", and that will take you to the library reference. its helpful. On Feb 25, 2010, at 1:35 PM, Ricardo Ar?oz wrote: > Stefan Behnel wrote: >> >> Monte Milanuk, 25.02.2010 16:47: >> >>> Is there a benefit (besides brevity) one way or the other between >>> using: >>> >>> import math >>> ... >>> math.pow(x,y) # x raised to the power y >>> >>> vs. >>> >>> x**y >>> >>> ? >>> >> >> Did you try it? >> >> >>> import math >> >>> print(math.pow(4,4)) >> 256.0 >> >>> 4**4 >> 256 >> >>> 4.0**4 >> 256.0 >> >> Stefan >> > Yes, I tried it. > Now, is there a benefit (besides brevity) one way or the other? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Thu Feb 25 20:26:51 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 26 Feb 2010 06:26:51 +1100 Subject: [Tutor] raising number to a power In-Reply-To: <4B86C2BF.1020305@gmail.com> References: <6f26596c1002250747m23cf27cn6945944c52559575@mail.gmail.com> <4B86C2BF.1020305@gmail.com> Message-ID: <201002260626.52473.steve@pearwood.info> On Fri, 26 Feb 2010 05:34:39 am Ricardo Ar?oz wrote: > So why would the coders of the math module go to the trouble of > creating the pow function? http://docs.python.org/library/math.html#math.pow http://docs.python.org/library/functions.html#pow The math module is mostly a thin wrapper around the native C maths library. The builtin pow function has more capabilities, and came before the ** operator. > Did they create a sum function As a matter of fact they did: http://docs.python.org/library/math.html#math.fsum -- Steven D'Aprano From kbailey at howlermonkey.net Thu Feb 25 23:03:07 2010 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Thu, 25 Feb 2010 17:03:07 -0500 Subject: [Tutor] test Message-ID: <4B86F39B.5010108@howlermonkey.net> test -- Cheers! -Kirk D Bailey THINK +-----+ .*. | BOX | ..* +-----+ *** THINK From vinces1979 at gmail.com Thu Feb 25 23:07:46 2010 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 25 Feb 2010 16:07:46 -0600 Subject: [Tutor] test In-Reply-To: <4B86F39B.5010108@howlermonkey.net> References: <4B86F39B.5010108@howlermonkey.net> Message-ID: <1e53c511002251407g4d373a8fx5fde46f141a2e462@mail.gmail.com> On Thu, Feb 25, 2010 at 4:03 PM, Kirk Bailey wrote: > test > -- > > > Cheers! > -Kirk D Bailey > > THINK > +-----+ > .*. | BOX | > ..* +-----+ > *** THINK > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hello World! << usually a good test -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 25 23:21:30 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Feb 2010 22:21:30 -0000 Subject: [Tutor] Omitting lines matching a list of strings from a file References: <86405F1B-54DF-422C-AC63-01D79B014FAA@gmail.com> <4B86812C.2020902@compuscan.co.za> Message-ID: "Christian Witts" wrote > lines = [line for line in infile if line[146:148] not in omit_states] > print ''.join(lines) > > Just remember that doing a list comprehension like that on a large file > will drastically reduce the speed of your application as well as > introduce memory bloat. Given he was originally doing an explicit for loop over the file I doubt if the comprehension will be any slower. But it may well use more memory. Alan G. From kbailey at howlermonkey.net Thu Feb 25 23:31:56 2010 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Thu, 25 Feb 2010 17:31:56 -0500 Subject: [Tutor] test again Message-ID: <4B86FA5C.1070707@howlermonkey.net> test- where is the list, nothing is coming to me! -- Cheers! -Kirk D Bailey THINK +-----+ .*. | BOX | ..* +-----+ *** THINK From kbailey at howlermonkey.net Fri Feb 26 00:11:57 2010 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Thu, 25 Feb 2010 18:11:57 -0500 Subject: [Tutor] wHY Message-ID: <4B8703BD.8010502@howlermonkey.net> IS NOTHING FROM THE LIST COMING TO ME? -- Cheers! -Kirk D Bailey THINK +-----+ .*. | BOX | ..* +-----+ *** THINK From kbailey at howlermonkey.net Fri Feb 26 00:20:14 2010 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Thu, 25 Feb 2010 18:20:14 -0500 Subject: [Tutor] test again In-Reply-To: <4B86FA5C.1070707@howlermonkey.net> References: <4B86FA5C.1070707@howlermonkey.net> Message-ID: <4B8705AE.6010200@howlermonkey.net> ook, thi new thunderbird 3.foo is... different, takes some getting used to. Sorry about the noise on the channel. On 2/25/2010 5:31 PM, Kirk Bailey wrote: > test- where is the list, nothing is coming to me! > -- Cheers! -Kirk D Bailey THINK +-----+ .*. | BOX | ..* +-----+ *** THINK From rabidpoobear at gmail.com Fri Feb 26 00:21:31 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 25 Feb 2010 17:21:31 -0600 Subject: [Tutor] wHY In-Reply-To: <4B8703BD.8010502@howlermonkey.net> References: <4B8703BD.8010502@howlermonkey.net> Message-ID: YOU DON'T GET YOUR OWN MESSAGES BACK. On Thu, Feb 25, 2010 at 5:11 PM, Kirk Bailey wrote: > IS NOTHING FROM THE LIST COMING TO ME? > > -- > > > Cheers! > -Kirk D Bailey > > THINK > +-----+ > .*. | BOX | > ..* +-----+ > *** THINK > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From toni at muybien.org Fri Feb 26 00:26:47 2010 From: toni at muybien.org (Antonio de la Fuente) Date: Thu, 25 Feb 2010 23:26:47 +0000 Subject: [Tutor] wHY In-Reply-To: <4B8703BD.8010502@howlermonkey.net> References: <4B8703BD.8010502@howlermonkey.net> Message-ID: <20100225232647.GE2601@cateto> Definitely there is somebody out there :) * Kirk Bailey [2010-02-25 18:11:57 -0500]: > Date: Thu, 25 Feb 2010 18:11:57 -0500 > From: Kirk Bailey > To: tutor at python.org > Subject: [Tutor] wHY > Organization: Silas Dent Memorial Cabal of ERIS Esoteric and hot dog > boiling > society FNORD! > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; > rv:1.9.1.8) Gecko/20100216 Thunderbird/3.0.2 > Message-ID: <4B8703BD.8010502 at howlermonkey.net> > > IS NOTHING FROM THE LIST COMING TO ME? > > -- > > > Cheers! > -Kirk D Bailey > > THINK > +-----+ > .*. | BOX | > ..* +-----+ > *** THINK > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- ----------------------------- Antonio de la Fuente Mart?nez E-mail: toni at muybien.org ----------------------------- Classical music is the kind we keep thinking will turn into a tune. -- Kin Hubbard, "Abe Martin's Sayings" From alan.gauld at btinternet.com Fri Feb 26 01:56:09 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 26 Feb 2010 00:56:09 -0000 Subject: [Tutor] wHY References: <4B8703BD.8010502@howlermonkey.net> Message-ID: "Kirk Bailey" wrote > IS NOTHING FROM THE LIST COMING TO ME? > Stating the obvious first - have you checked your subscription settings? Have you got delivery switched on? Have you tried switching it off then on again just to be sure? Alan G. From kbailey at howlermonkey.net Fri Feb 26 02:59:06 2010 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Thu, 25 Feb 2010 20:59:06 -0500 Subject: [Tutor] returning to my quest Message-ID: <4B872AEA.6000908@howlermonkey.net> for WEBMAIIL portal to a pop3/smtp email service in my server; centrally hosted or in the laptop is fine, what can people recommend? Without going to IMAP, i want to leave the mail on the server. -- Cheers! -Kirk D Bailey THINK +-----+ .*. | BOX | ..* +-----+ *** THINK From kent37 at tds.net Fri Feb 26 03:53:24 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Feb 2010 21:53:24 -0500 Subject: [Tutor] Top posters for 2009 Message-ID: <1c2a2c591002251853x5d2127a3p5c382abea293c336@mail.gmail.com> It's not really about keeping score :-), but once again I've compiled a list of the top 20 posters to the tutor list for the last year. For 2009, the rankings are 2009 (7730 posts, 709 posters) ==== Alan Gauld 969 (12.5%) Kent Johnson 804 (10.4%) Dave Angel 254 (3.3%) spir 254 (3.3%) Wayne Watson 222 (2.9%) bob gailer 191 (2.5%) Lie Ryan 186 (2.4%) David 127 (1.6%) Emile van Sebille 115 (1.5%) Wayne 112 (1.4%) Sander Sweers 111 (1.4%) Serdar Tumgoren 100 (1.3%) Luke Paireepinart 99 (1.3%) wesley chun 99 (1.3%) W W 74 (1.0%) Marc Tompkins 72 (0.9%) A.T.Hofkamp 71 (0.9%) Robert Berman 68 (0.9%) vince spicer 63 (0.8%) Emad Nawfal 62 (0.8%) Alan, congratulations, you pulled ahead of me for the first time in years! You posted more than in 2008, I posted less. Overall posts are up from last year, which was the slowest year since I started measuring (2003). Thank you to everyone who asks and answers questions here! The rankings are compiled by scraping the monthly author pages from the tutor archives, using Beautiful Soup to extract author names. I consolidate counts for different capitalizations of the same name but not for different spellings. The script is below. Kent ''' Counts all posts to Python-tutor by author''' # -*- coding: latin-1 -*- from datetime import date, timedelta import operator, urllib2 from BeautifulSoup import BeautifulSoup today = date.today() for year in range(2009, 2010): startDate = date(year, 1, 1) endDate = date(year, 12, 31) thirtyOne = timedelta(days=31) counts = {} # Collect all the counts for a year by scraping the monthly author archive pages while startDate < endDate and startDate < today: dateString = startDate.strftime('%Y-%B') url = 'http://mail.python.org/pipermail/tutor/%s/author.html' % dateString data = urllib2.urlopen(url).read() soup = BeautifulSoup(data) li = soup.findAll('li')[2:-2] for l in li: name = l.i.string.strip() counts[name] = counts.get(name, 0) + 1 startDate += thirtyOne # Consolidate names that vary by case under the most popular spelling nameMap = dict() # Map lower-case name to most popular name # Use counts.items() so we can delete from the dict. for name, count in sorted(counts.items(), key=operator.itemgetter(1), reverse=True): lower = name.lower() if lower in nameMap: # Add counts for a name we have seen already and remove the duplicate counts[nameMap[lower]] += count del counts[name] else: nameMap[lower] = name totalPosts = sum(counts.itervalues()) posters = len(counts) print print '%s (%s posts, %s posters)' % (year, totalPosts, posters) print '====' for name, count in sorted(counts.iteritems(), key=operator.itemgetter(1), reverse=True)[:20]: pct = round(100.0*count/totalPosts, 1) print '%s %s (%s%%)' % (name.encode('utf-8', 'xmlcharrefreplace'), count, pct) print From kent37 at tds.net Fri Feb 26 03:55:51 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 25 Feb 2010 21:55:51 -0500 Subject: [Tutor] returning to my quest In-Reply-To: <4B872AEA.6000908@howlermonkey.net> References: <4B872AEA.6000908@howlermonkey.net> Message-ID: <1c2a2c591002251855r78e6d3f9x37ad2a8dbeb29609@mail.gmail.com> On Thu, Feb 25, 2010 at 8:59 PM, Kirk Bailey wrote: > for ?WEBMAIIL portal to a pop3/smtp email service in my server; centrally > hosted or in the laptop is fine, what can people recommend? Without going to > IMAP, i want to leave the mail on the server. I still have no idea what you are asking for. What is a WEBMAIL portal? Are you trying to access mail that has a web interface, or create a web interface for an existing POP mailbox, or what? Oh, and what does this have to do with Python? Kent From anand.shashwat at gmail.com Fri Feb 26 04:34:00 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 26 Feb 2010 09:04:00 +0530 Subject: [Tutor] Top posters for 2009 In-Reply-To: <1c2a2c591002251853x5d2127a3p5c382abea293c336@mail.gmail.com> References: <1c2a2c591002251853x5d2127a3p5c382abea293c336@mail.gmail.com> Message-ID: nice. Kudos to all top posters. May be I should search my rank ;) ~l0nwlf On Fri, Feb 26, 2010 at 8:23 AM, Kent Johnson wrote: > It's not really about keeping score :-), but once again I've compiled > a list of the top 20 posters to the tutor list for the last year. For > 2009, the rankings are > > 2009 (7730 posts, 709 posters) > ==== > Alan Gauld 969 (12.5%) > Kent Johnson 804 (10.4%) > Dave Angel 254 (3.3%) > spir 254 (3.3%) > Wayne Watson 222 (2.9%) > bob gailer 191 (2.5%) > Lie Ryan 186 (2.4%) > David 127 (1.6%) > Emile van Sebille 115 (1.5%) > Wayne 112 (1.4%) > Sander Sweers 111 (1.4%) > Serdar Tumgoren 100 (1.3%) > Luke Paireepinart 99 (1.3%) > wesley chun 99 (1.3%) > W W 74 (1.0%) > Marc Tompkins 72 (0.9%) > A.T.Hofkamp 71 (0.9%) > Robert Berman 68 (0.9%) > vince spicer 63 (0.8%) > Emad Nawfal 62 (0.8%) > > Alan, congratulations, you pulled ahead of me for the first time in > years! You posted more than in 2008, I posted less. Overall posts are > up from last year, which was the slowest year since I started > measuring (2003). > > Thank you to everyone who asks and answers questions here! > > The rankings are compiled by scraping the monthly author pages from > the tutor archives, using Beautiful Soup to extract author names. I > consolidate counts for different capitalizations of the same name but > not for different spellings. The script is below. > > Kent > > ''' Counts all posts to Python-tutor by author''' > # -*- coding: latin-1 -*- > from datetime import date, timedelta > import operator, urllib2 > from BeautifulSoup import BeautifulSoup > > today = date.today() > > for year in range(2009, 2010): > startDate = date(year, 1, 1) > endDate = date(year, 12, 31) > thirtyOne = timedelta(days=31) > counts = {} > > # Collect all the counts for a year by scraping the monthly author > archive pages > while startDate < endDate and startDate < today: > dateString = startDate.strftime('%Y-%B') > > url = 'http://mail.python.org/pipermail/tutor/%s/author.html' > % dateString > data = urllib2.urlopen(url).read() > soup = BeautifulSoup(data) > > li = soup.findAll('li')[2:-2] > > for l in li: > name = l.i.string.strip() > counts[name] = counts.get(name, 0) + 1 > > startDate += thirtyOne > > # Consolidate names that vary by case under the most popular spelling > nameMap = dict() # Map lower-case name to most popular name > > # Use counts.items() so we can delete from the dict. > for name, count in sorted(counts.items(), > key=operator.itemgetter(1), reverse=True): > lower = name.lower() > if lower in nameMap: > # Add counts for a name we have seen already and remove the > duplicate > counts[nameMap[lower]] += count > del counts[name] > else: > nameMap[lower] = name > > totalPosts = sum(counts.itervalues()) > posters = len(counts) > > print > print '%s (%s posts, %s posters)' % (year, totalPosts, posters) > print '====' > for name, count in sorted(counts.iteritems(), > key=operator.itemgetter(1), reverse=True)[:20]: > pct = round(100.0*count/totalPosts, 1) > print '%s %s (%s%%)' % (name.encode('utf-8', > 'xmlcharrefreplace'), count, pct) > print > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Fri Feb 26 04:40:26 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 26 Feb 2010 09:10:26 +0530 Subject: [Tutor] Top posters for 2009 In-Reply-To: References: <1c2a2c591002251853x5d2127a3p5c382abea293c336@mail.gmail.com> Message-ID: How about Top-40 posters (so that I can make the cut..Yayyy) :P 2009 (7730 posts, 709 posters) ==== Alan Gauld 969 (12.5%) Kent Johnson 804 (10.4%) Dave Angel 254 (3.3%) spir 254 (3.3%) Wayne Watson 222 (2.9%) bob gailer 191 (2.5%) Lie Ryan 186 (2.4%) David 127 (1.6%) Emile van Sebille 115 (1.5%) Wayne 112 (1.4%) Sander Sweers 111 (1.4%) Serdar Tumgoren 100 (1.3%) Luke Paireepinart 99 (1.3%) wesley chun 99 (1.3%) W W 74 (1.0%) Marc Tompkins 72 (0.9%) A.T.Hofkamp 71 (0.9%) Robert Berman 68 (0.9%) vince spicer 63 (0.8%) Emad Nawfal 62 (0.8%) Andre Engels 61 (0.8%) Rich Lovely 60 (0.8%) Christian Witts 57 (0.7%) Martin Walsh 51 (0.7%) Eduardo Vieira 47 (0.6%) Tim Golden 47 (0.6%) prasad rao 47 (0.6%) Dinesh B Vadhia 47 (0.6%) John Fouhy 42 (0.5%) Norman Khine 41 (0.5%) Che M 41 (0.5%) Stephen Nelson-Smith 40 (0.5%) Mark Tolonen 40 (0.5%) Chris Fuller 38 (0.5%) Stefan Behnel 35 (0.5%) Wayne Werner 34 (0.4%) Steve Willoughby 32 (0.4%) Shashwat Anand 32 (0.4%) Eike Welk 31 (0.4%) Albert-Jan Roskam 30 (0.4%) ~l0nwlf On Fri, Feb 26, 2010 at 9:04 AM, Shashwat Anand wrote: > nice. Kudos to all top posters. May be I should search my rank ;) > > ~l0nwlf > > > On Fri, Feb 26, 2010 at 8:23 AM, Kent Johnson wrote: > >> It's not really about keeping score :-), but once again I've compiled >> a list of the top 20 posters to the tutor list for the last year. For >> 2009, the rankings are >> >> 2009 (7730 posts, 709 posters) >> ==== >> Alan Gauld 969 (12.5%) >> Kent Johnson 804 (10.4%) >> Dave Angel 254 (3.3%) >> spir 254 (3.3%) >> Wayne Watson 222 (2.9%) >> bob gailer 191 (2.5%) >> Lie Ryan 186 (2.4%) >> David 127 (1.6%) >> Emile van Sebille 115 (1.5%) >> Wayne 112 (1.4%) >> Sander Sweers 111 (1.4%) >> Serdar Tumgoren 100 (1.3%) >> Luke Paireepinart 99 (1.3%) >> wesley chun 99 (1.3%) >> W W 74 (1.0%) >> Marc Tompkins 72 (0.9%) >> A.T.Hofkamp 71 (0.9%) >> Robert Berman 68 (0.9%) >> vince spicer 63 (0.8%) >> Emad Nawfal 62 (0.8%) >> >> Alan, congratulations, you pulled ahead of me for the first time in >> years! You posted more than in 2008, I posted less. Overall posts are >> up from last year, which was the slowest year since I started >> measuring (2003). >> >> Thank you to everyone who asks and answers questions here! >> >> The rankings are compiled by scraping the monthly author pages from >> the tutor archives, using Beautiful Soup to extract author names. I >> consolidate counts for different capitalizations of the same name but >> not for different spellings. The script is below. >> >> Kent >> >> ''' Counts all posts to Python-tutor by author''' >> # -*- coding: latin-1 -*- >> from datetime import date, timedelta >> import operator, urllib2 >> from BeautifulSoup import BeautifulSoup >> >> today = date.today() >> >> for year in range(2009, 2010): >> startDate = date(year, 1, 1) >> endDate = date(year, 12, 31) >> thirtyOne = timedelta(days=31) >> counts = {} >> >> # Collect all the counts for a year by scraping the monthly author >> archive pages >> while startDate < endDate and startDate < today: >> dateString = startDate.strftime('%Y-%B') >> >> url = 'http://mail.python.org/pipermail/tutor/%s/author.html' >> % dateString >> data = urllib2.urlopen(url).read() >> soup = BeautifulSoup(data) >> >> li = soup.findAll('li')[2:-2] >> >> for l in li: >> name = l.i.string.strip() >> counts[name] = counts.get(name, 0) + 1 >> >> startDate += thirtyOne >> >> # Consolidate names that vary by case under the most popular spelling >> nameMap = dict() # Map lower-case name to most popular name >> >> # Use counts.items() so we can delete from the dict. >> for name, count in sorted(counts.items(), >> key=operator.itemgetter(1), reverse=True): >> lower = name.lower() >> if lower in nameMap: >> # Add counts for a name we have seen already and remove the >> duplicate >> counts[nameMap[lower]] += count >> del counts[name] >> else: >> nameMap[lower] = name >> >> totalPosts = sum(counts.itervalues()) >> posters = len(counts) >> >> print >> print '%s (%s posts, %s posters)' % (year, totalPosts, posters) >> print '====' >> for name, count in sorted(counts.iteritems(), >> key=operator.itemgetter(1), reverse=True)[:20]: >> pct = round(100.0*count/totalPosts, 1) >> print '%s %s (%s%%)' % (name.encode('utf-8', >> 'xmlcharrefreplace'), count, pct) >> print >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Fri Feb 26 04:57:04 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 26 Feb 2010 09:27:04 +0530 Subject: [Tutor] Top posters for 2009 In-Reply-To: References: <1c2a2c591002251853x5d2127a3p5c382abea293c336@mail.gmail.com> Message-ID: @Kent: thanks for the script. It is kool. Here is 2010 list of Top-20 (as of now): 2010 (1155 posts, 204 posters) ==== Alan Gauld 127 (11.0%) Kent Johnson 108 (9.4%) spir 52 (4.5%) Wayne Watson 46 (4.0%) Luke Paireepinart 32 (2.8%) Shashwat Anand 30 (2.6%) Wayne Werner 29 (2.5%) Steven D'Aprano 28 (2.4%) Stefan Behnel 24 (2.1%) Dave Angel 22 (1.9%) Lie Ryan 19 (1.6%) Hugo Arts 16 (1.4%) Benno Lang 14 (1.2%) David 14 (1.2%) Giorgio 14 (1.2%) Serdar Tumgoren 14 (1.2%) Grigor Kolev 13 (1.1%) Eike Welk 13 (1.1%) Christian Witts 12 (1.0%) invincible patriot 12 (1.0%) No more spamming now :P ~l0nwlf On Fri, Feb 26, 2010 at 9:10 AM, Shashwat Anand wrote: > How about Top-40 posters (so that I can make the cut..Yayyy) :P > > > 2009 (7730 posts, 709 posters) > ==== > Alan Gauld 969 (12.5%) > Kent Johnson 804 (10.4%) > Dave Angel 254 (3.3%) > spir 254 (3.3%) > Wayne Watson 222 (2.9%) > bob gailer 191 (2.5%) > Lie Ryan 186 (2.4%) > David 127 (1.6%) > Emile van Sebille 115 (1.5%) > Wayne 112 (1.4%) > Sander Sweers 111 (1.4%) > Serdar Tumgoren 100 (1.3%) > Luke Paireepinart 99 (1.3%) > wesley chun 99 (1.3%) > W W 74 (1.0%) > Marc Tompkins 72 (0.9%) > A.T.Hofkamp 71 (0.9%) > Robert Berman 68 (0.9%) > vince spicer 63 (0.8%) > Emad Nawfal 62 (0.8%) > Andre Engels 61 (0.8%) > Rich Lovely 60 (0.8%) > Christian Witts 57 (0.7%) > Martin Walsh 51 (0.7%) > Eduardo Vieira 47 (0.6%) > Tim Golden 47 (0.6%) > prasad rao 47 (0.6%) > Dinesh B Vadhia 47 (0.6%) > John Fouhy 42 (0.5%) > Norman Khine 41 (0.5%) > Che M 41 (0.5%) > Stephen Nelson-Smith 40 (0.5%) > Mark Tolonen 40 (0.5%) > Chris Fuller 38 (0.5%) > Stefan Behnel 35 (0.5%) > Wayne Werner 34 (0.4%) > Steve Willoughby 32 (0.4%) > Shashwat Anand 32 (0.4%) > Eike Welk 31 (0.4%) > Albert-Jan Roskam 30 (0.4%) > > ~l0nwlf > > > On Fri, Feb 26, 2010 at 9:04 AM, Shashwat Anand wrote: > >> nice. Kudos to all top posters. May be I should search my rank ;) >> >> ~l0nwlf >> >> >> On Fri, Feb 26, 2010 at 8:23 AM, Kent Johnson wrote: >> >>> It's not really about keeping score :-), but once again I've compiled >>> a list of the top 20 posters to the tutor list for the last year. For >>> 2009, the rankings are >>> >>> 2009 (7730 posts, 709 posters) >>> ==== >>> Alan Gauld 969 (12.5%) >>> Kent Johnson 804 (10.4%) >>> Dave Angel 254 (3.3%) >>> spir 254 (3.3%) >>> Wayne Watson 222 (2.9%) >>> bob gailer 191 (2.5%) >>> Lie Ryan 186 (2.4%) >>> David 127 (1.6%) >>> Emile van Sebille 115 (1.5%) >>> Wayne 112 (1.4%) >>> Sander Sweers 111 (1.4%) >>> Serdar Tumgoren 100 (1.3%) >>> Luke Paireepinart 99 (1.3%) >>> wesley chun 99 (1.3%) >>> W W 74 (1.0%) >>> Marc Tompkins 72 (0.9%) >>> A.T.Hofkamp 71 (0.9%) >>> Robert Berman 68 (0.9%) >>> vince spicer 63 (0.8%) >>> Emad Nawfal 62 (0.8%) >>> >>> Alan, congratulations, you pulled ahead of me for the first time in >>> years! You posted more than in 2008, I posted less. Overall posts are >>> up from last year, which was the slowest year since I started >>> measuring (2003). >>> >>> Thank you to everyone who asks and answers questions here! >>> >>> The rankings are compiled by scraping the monthly author pages from >>> the tutor archives, using Beautiful Soup to extract author names. I >>> consolidate counts for different capitalizations of the same name but >>> not for different spellings. The script is below. >>> >>> Kent >>> >>> ''' Counts all posts to Python-tutor by author''' >>> # -*- coding: latin-1 -*- >>> from datetime import date, timedelta >>> import operator, urllib2 >>> from BeautifulSoup import BeautifulSoup >>> >>> today = date.today() >>> >>> for year in range(2009, 2010): >>> startDate = date(year, 1, 1) >>> endDate = date(year, 12, 31) >>> thirtyOne = timedelta(days=31) >>> counts = {} >>> >>> # Collect all the counts for a year by scraping the monthly author >>> archive pages >>> while startDate < endDate and startDate < today: >>> dateString = startDate.strftime('%Y-%B') >>> >>> url = 'http://mail.python.org/pipermail/tutor/%s/author.html' >>> % dateString >>> data = urllib2.urlopen(url).read() >>> soup = BeautifulSoup(data) >>> >>> li = soup.findAll('li')[2:-2] >>> >>> for l in li: >>> name = l.i.string.strip() >>> counts[name] = counts.get(name, 0) + 1 >>> >>> startDate += thirtyOne >>> >>> # Consolidate names that vary by case under the most popular spelling >>> nameMap = dict() # Map lower-case name to most popular name >>> >>> # Use counts.items() so we can delete from the dict. >>> for name, count in sorted(counts.items(), >>> key=operator.itemgetter(1), reverse=True): >>> lower = name.lower() >>> if lower in nameMap: >>> # Add counts for a name we have seen already and remove the >>> duplicate >>> counts[nameMap[lower]] += count >>> del counts[name] >>> else: >>> nameMap[lower] = name >>> >>> totalPosts = sum(counts.itervalues()) >>> posters = len(counts) >>> >>> print >>> print '%s (%s posts, %s posters)' % (year, totalPosts, posters) >>> print '====' >>> for name, count in sorted(counts.iteritems(), >>> key=operator.itemgetter(1), reverse=True)[:20]: >>> pct = round(100.0*count/totalPosts, 1) >>> print '%s %s (%s%%)' % (name.encode('utf-8', >>> 'xmlcharrefreplace'), count, pct) >>> print >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From transmogribenno at gmail.com Fri Feb 26 07:38:59 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Fri, 26 Feb 2010 15:38:59 +0900 Subject: [Tutor] returning to my quest In-Reply-To: <1c2a2c591002251855r78e6d3f9x37ad2a8dbeb29609@mail.gmail.com> References: <4B872AEA.6000908@howlermonkey.net> <1c2a2c591002251855r78e6d3f9x37ad2a8dbeb29609@mail.gmail.com> Message-ID: <9b00d1a91002252238p5975fe31r6abb1a5ebcb7363a@mail.gmail.com> On 26 February 2010 11:55, Kent Johnson wrote: > On Thu, Feb 25, 2010 at 8:59 PM, Kirk Bailey wrote: >> for ?WEBMAIIL portal to a pop3/smtp email service in my server; centrally >> hosted or in the laptop is fine, what can people recommend? Without going to >> IMAP, i want to leave the mail on the server. > > I still have no idea what you are asking for. What is a WEBMAIL > portal? Are you trying to access mail that has a web interface, or > create a web interface for an existing POP mailbox, or what? > > Oh, and what does this have to do with Python? I'm pretty sure he wants to be able to install some python software on a server that will provide a web interface for accessing a POP mail account. For PHP there's squirrel mail, horde imp, roundcube, etc. I can't seem to find any at all for Python, at least none that have been worked on in the last 5 years. Does anyone else know? Thanks, benno From zubin.mithra at gmail.com Fri Feb 26 08:41:15 2010 From: zubin.mithra at gmail.com (Zubin Mithra) Date: Fri, 26 Feb 2010 13:11:15 +0530 Subject: [Tutor] PyAutoRun Message-ID: <8e7c74321002252341t2ac857aavc5a5a9d4d57e6a29@mail.gmail.com> I have been using python for quite some time; however this is the first python project i have worked on. The code is hosted at http://github.com/zubin71/PyAutoRun The code needs re-factoring and feature additions; i have put up a TODO list there too. It`d be great if anyone could work on this; i intend to develop this further(with a bit of help) and will request for its addition into debian and ubuntu repositories, in time. Also, any kind of code-review, criticism, is also appreciated. However, it`d be awesome if you could just fork it at github, pull, modify and push. :) Have a nice day! cheers!!! Zubin From denis.spir at gmail.com Fri Feb 26 10:11:18 2010 From: denis.spir at gmail.com (spir) Date: Fri, 26 Feb 2010 10:11:18 +0100 Subject: [Tutor] Top posters for 2009 In-Reply-To: <1c2a2c591002251853x5d2127a3p5c382abea293c336@mail.gmail.com> References: <1c2a2c591002251853x5d2127a3p5c382abea293c336@mail.gmail.com> Message-ID: <20100226101118.794fc80c@o> On Thu, 25 Feb 2010 21:53:24 -0500 Kent Johnson wrote: > 2009 (7730 posts, 709 posters) > ==== > Alan Gauld 969 (12.5%) > Kent Johnson 804 (10.4%) > Dave Angel 254 (3.3%) > spir 254 (3.3%) > Wayne Watson 222 (2.9%) I hope Dave is as thin as I am (*). Denis (*) for us to be able to climb on the same step of the podium ;-) -- ________________________________ la vita e estrany spir.wikidot.com From denis.spir at gmail.com Fri Feb 26 10:14:15 2010 From: denis.spir at gmail.com (spir) Date: Fri, 26 Feb 2010 10:14:15 +0100 Subject: [Tutor] Top posters for 2009 In-Reply-To: References: <1c2a2c591002251853x5d2127a3p5c382abea293c336@mail.gmail.com> Message-ID: <20100226101415.41767d04@o> On Fri, 26 Feb 2010 09:27:04 +0530 Shashwat Anand wrote: > @Kent: thanks for the script. It is kool. > > Here is 2010 list of Top-20 (as of now): > > 2010 (1155 posts, 204 posters) > ==== > Alan Gauld 127 (11.0%) > Kent Johnson 108 (9.4%) > spir 52 (4.5%) > Wayne Watson 46 (4.0%) > Luke Paireepinart 32 (2.8%) > Shashwat Anand 30 (2.6%) > Wayne Werner 29 (2.5%) > Steven D'Aprano 28 (2.4%) I think and hope Steven will fast climb up. His posts beeing so accurate and informative for me. Denis -- ________________________________ la vita e estrany spir.wikidot.com From rabidpoobear at gmail.com Fri Feb 26 13:26:15 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 26 Feb 2010 06:26:15 -0600 Subject: [Tutor] PyAutoRun In-Reply-To: <8e7c74321002252341t2ac857aavc5a5a9d4d57e6a29@mail.gmail.com> References: <8e7c74321002252341t2ac857aavc5a5a9d4d57e6a29@mail.gmail.com> Message-ID: On Fri, Feb 26, 2010 at 1:41 AM, Zubin Mithra wrote: > I have been using python for quite some time; however this is the > first python project i have worked on. > > The code is hosted at http://github.com/zubin71/PyAutoRun > > The code needs re-factoring and feature additions; i have put up a > TODO list there too. It`d be great if anyone could work on this; i > intend to develop this further(with a bit of help) and will request > for its addition into debian and ubuntu repositories, in time. > > Also, any kind of code-review, criticism, is also appreciated. > However, it`d be awesome if you could just fork it at github, pull, > modify and push. :) > I'm not too clear, perhaps you could explain what advantage this has over just writing a shell script / makefiles? -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Fri Feb 26 14:56:13 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 26 Feb 2010 14:56:13 +0100 Subject: [Tutor] Top posters for 2009 In-Reply-To: References: <1c2a2c591002251853x5d2127a3p5c382abea293c336@mail.gmail.com> Message-ID: Shashwat Anand, 26.02.2010 04:57: > @Kent: thanks for the script. It is kool. > > Here is 2010 list of Top-20 (as of now): > > 2010 (1155 posts, 204 posters) > ==== > Alan Gauld 127 (11.0%) > Kent Johnson 108 (9.4%) > spir 52 (4.5%) > Wayne Watson 46 (4.0%) > Luke Paireepinart 32 (2.8%) > Shashwat Anand 30 (2.6%) > Wayne Werner 29 (2.5%) > Steven D'Aprano 28 (2.4%) > Stefan Behnel 24 (2.1%) > Dave Angel 22 (1.9%) > Lie Ryan 19 (1.6%) > Hugo Arts 16 (1.4%) > Benno Lang 14 (1.2%) > David 14 (1.2%) > Giorgio 14 (1.2%) > Serdar Tumgoren 14 (1.2%) > Grigor Kolev 13 (1.1%) > Eike Welk 13 (1.1%) > Christian Witts 12 (1.0%) > invincible patriot 12 (1.0%) > > No more spamming now :P > > ~l0nwlf > > On Fri, Feb 26, 2010 at 9:10 AM, Shashwat Anand wrote: > >> How about Top-40 posters (so that I can make the cut..Yayyy) :P >> >> >> 2009 (7730 posts, 709 posters) >> ==== >> Alan Gauld 969 (12.5%) >> Kent Johnson 804 (10.4%) >> Dave Angel 254 (3.3%) >> spir 254 (3.3%) >> Wayne Watson 222 (2.9%) >> bob gailer 191 (2.5%) >> Lie Ryan 186 (2.4%) >> David 127 (1.6%) >> Emile van Sebille 115 (1.5%) >> Wayne 112 (1.4%) >> Sander Sweers 111 (1.4%) >> Serdar Tumgoren 100 (1.3%) >> Luke Paireepinart 99 (1.3%) >> wesley chun 99 (1.3%) >> W W 74 (1.0%) >> Marc Tompkins 72 (0.9%) >> A.T.Hofkamp 71 (0.9%) >> Robert Berman 68 (0.9%) >> vince spicer 63 (0.8%) >> Emad Nawfal 62 (0.8%) >> Andre Engels 61 (0.8%) >> Rich Lovely 60 (0.8%) >> Christian Witts 57 (0.7%) >> Martin Walsh 51 (0.7%) >> Eduardo Vieira 47 (0.6%) >> Tim Golden 47 (0.6%) >> prasad rao 47 (0.6%) >> Dinesh B Vadhia 47 (0.6%) >> John Fouhy 42 (0.5%) >> Norman Khine 41 (0.5%) >> Che M 41 (0.5%) >> Stephen Nelson-Smith 40 (0.5%) >> Mark Tolonen 40 (0.5%) >> Chris Fuller 38 (0.5%) >> Stefan Behnel 35 (0.5%) >> Wayne Werner 34 (0.4%) >> Steve Willoughby 32 (0.4%) >> Shashwat Anand 32 (0.4%) >> Eike Welk 31 (0.4%) >> Albert-Jan Roskam 30 (0.4%) >> >> ~l0nwlf >> >> >> On Fri, Feb 26, 2010 at 9:04 AM, Shashwat Anand wrote: >> >>> nice. Kudos to all top posters. May be I should search my rank ;) >>> >>> ~l0nwlf >>> >>> >>> On Fri, Feb 26, 2010 at 8:23 AM, Kent Johnson wrote: >>> >>>> It's not really about keeping score :-), but once again I've compiled >>>> a list of the top 20 posters to the tutor list for the last year. For >>>> 2009, the rankings are >>>> >>>> 2009 (7730 posts, 709 posters) >>>> ==== >>>> Alan Gauld 969 (12.5%) >>>> Kent Johnson 804 (10.4%) >>>> Dave Angel 254 (3.3%) >>>> spir 254 (3.3%) >>>> Wayne Watson 222 (2.9%) >>>> bob gailer 191 (2.5%) >>>> Lie Ryan 186 (2.4%) >>>> David 127 (1.6%) >>>> Emile van Sebille 115 (1.5%) >>>> Wayne 112 (1.4%) >>>> Sander Sweers 111 (1.4%) >>>> Serdar Tumgoren 100 (1.3%) >>>> Luke Paireepinart 99 (1.3%) >>>> wesley chun 99 (1.3%) >>>> W W 74 (1.0%) >>>> Marc Tompkins 72 (0.9%) >>>> A.T.Hofkamp 71 (0.9%) >>>> Robert Berman 68 (0.9%) >>>> vince spicer 63 (0.8%) >>>> Emad Nawfal 62 (0.8%) >>>> >>>> Alan, congratulations, you pulled ahead of me for the first time in >>>> years! You posted more than in 2008, I posted less. Overall posts are >>>> up from last year, which was the slowest year since I started >>>> measuring (2003). >>>> >>>> Thank you to everyone who asks and answers questions here! >>>> >>>> The rankings are compiled by scraping the monthly author pages from >>>> the tutor archives, using Beautiful Soup to extract author names. I >>>> consolidate counts for different capitalizations of the same name but >>>> not for different spellings. The script is below. >>>> >>>> Kent >>>> >>>> ''' Counts all posts to Python-tutor by author''' >>>> # -*- coding: latin-1 -*- >>>> from datetime import date, timedelta >>>> import operator, urllib2 >>>> from BeautifulSoup import BeautifulSoup >>>> >>>> today = date.today() >>>> >>>> for year in range(2009, 2010): >>>> startDate = date(year, 1, 1) >>>> endDate = date(year, 12, 31) >>>> thirtyOne = timedelta(days=31) >>>> counts = {} >>>> >>>> # Collect all the counts for a year by scraping the monthly author >>>> archive pages >>>> while startDate < endDate and startDate < today: >>>> dateString = startDate.strftime('%Y-%B') >>>> >>>> url = 'http://mail.python.org/pipermail/tutor/%s/author.html' >>>> % dateString >>>> data = urllib2.urlopen(url).read() >>>> soup = BeautifulSoup(data) >>>> >>>> li = soup.findAll('li')[2:-2] >>>> >>>> for l in li: >>>> name = l.i.string.strip() >>>> counts[name] = counts.get(name, 0) + 1 >>>> >>>> startDate += thirtyOne >>>> >>>> # Consolidate names that vary by case under the most popular spelling >>>> nameMap = dict() # Map lower-case name to most popular name >>>> >>>> # Use counts.items() so we can delete from the dict. >>>> for name, count in sorted(counts.items(), >>>> key=operator.itemgetter(1), reverse=True): >>>> lower = name.lower() >>>> if lower in nameMap: >>>> # Add counts for a name we have seen already and remove the >>>> duplicate >>>> counts[nameMap[lower]] += count >>>> del counts[name] >>>> else: >>>> nameMap[lower] = name >>>> >>>> totalPosts = sum(counts.itervalues()) >>>> posters = len(counts) >>>> >>>> print >>>> print '%s (%s posts, %s posters)' % (year, totalPosts, posters) >>>> print '====' >>>> for name, count in sorted(counts.iteritems(), >>>> key=operator.itemgetter(1), reverse=True)[:20]: >>>> pct = round(100.0*count/totalPosts, 1) >>>> print '%s %s (%s%%)' % (name.encode('utf-8', >>>> 'xmlcharrefreplace'), count, pct) >>>> print I think Kent was referring to "top posters" in the sense that they post a lot, not that they reply as a top-post. http://en.wikipedia.org/wiki/Posting_style Stefan From ricaraoz at gmail.com Fri Feb 26 14:31:06 2010 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 26 Feb 2010 10:31:06 -0300 Subject: [Tutor] How to use pydoc Message-ID: <4B87CD1A.1080108@gmail.com> Checked the manuals on pydoc and wanted to try it. Must certainly be doing something wrong but I can't figure what. Here's my session : Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> pydoc sys File "", line 1 pydoc sys ^ SyntaxError: invalid syntax >>> import pydoc >>> pydoc sys File "", line 1 pydoc sys ^ SyntaxError: invalid syntax >>> pydoc >>> import sys >>> pydoc sys File "", line 1 pydoc sys ^ SyntaxError: invalid syntax >>> What's my mistake? TIA From dwightdhutto at yahoo.com Fri Feb 26 16:51:30 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Fri, 26 Feb 2010 07:51:30 -0800 (PST) Subject: [Tutor] How to use pydoc In-Reply-To: <4B87CD1A.1080108@gmail.com> Message-ID: <183917.98794.qm@web45307.mail.sp1.yahoo.com> --- On Fri, 2/26/10, Ricardo Ar?oz wrote: From: Ricardo Ar?oz Subject: [Tutor] How to use pydoc To: tutor at python.org Date: Friday, February 26, 2010, 8:31 AM Checked the manuals on pydoc and wanted to try it. Must certainly be doing something wrong but I can't figure what. Here's my session : Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> pydoc sys ? File "", line 1 ? ? pydoc sys ? ? ? ? ? ? ^ SyntaxError: invalid syntax >>> import pydoc >>> pydoc sys ? File "", line 1 ? ? pydoc sys ? ? ? ? ? ? ^ SyntaxError: invalid syntax >>> pydoc >>> import sys >>> pydoc sys ? File "", line 1 ? ? pydoc sys ? ? ? ? ? ? ^ SyntaxError: invalid syntax >>> What's my mistake? TIA _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor It looks like you're using idle, you place the command in the command prompt/terminal like: python -m pydoc sys Look here about three down it's in the page summary: http://www.google.com/search?hl=en&client=firefox-a&rls=com.ubuntu%3Aen-US%3Aofficial&q=pydoc+sys&aq=f&aqi=g1g-s1g-sx1&aql=&oq= -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at bobdel.com Fri Feb 26 18:52:39 2010 From: lists at bobdel.com (Robert DeLaurentis) Date: Fri, 26 Feb 2010 09:52:39 -0800 Subject: [Tutor] Help me understand this tkinter related code In-Reply-To: <4B86F39B.5010108@howlermonkey.net> References: <4B86F39B.5010108@howlermonkey.net> Message-ID: I've just begun learning Python and programming using the Head First Programming from O'Reilly. The following code works on my Mac just fine, but there is a mystery as to how its working that escapes me so far. The local function change_volume(v) requires the argument v to operate properly, but I'm unclear where the value of that argument is being set or why the code fails without it. It appears to be a detail that isn't explained in the text. When I compare the two widgets and their associated functions, both seem to use the .get method to access the value set by the widget, so in that case the v seems superfluous. I thought that perhaps the answer might be found in the tkinter code that defines Scale, but I'm not even sure where on the computer that code is located. Thank you! Bob Here is the code (the comments are mine, otherwise the code matches the book except that I grouped some items differently -- I like to keep variables all in one place as much as possible): #!/usr/local/bin/python3 # load external libraries from tkinter import * import pygame.mixer # initialize the visual interface app = Tk() app.title("Head First Mix") app.geometry('250x100+200+100') # initialize the sound player mixer = pygame.mixer mixer.init() # initialize the variables sound_file = "50459_M_RED_Nephlimizer.wav" track = mixer.Sound(sound_file) track_playing = IntVar() # local functions def shutdown(): track.stop() app.destroy() def track_toggle(): if track_playing.get() == 1: track.play(loops = -1) else: track.stop() def change_volume(v): track.set_volume(volume.get()) # define interface widgets track_button = Checkbutton(app, variable = track_playing, command = track_toggle, text = sound_file) track_button.pack() volume = DoubleVar() volume.set(track.get_volume()) volume_scale = Scale(app, variable = volume, from_ = 0.0, to = 1.0, resolution = 0.1, command = change_volume, label = "Volume", orient = HORIZONTAL) volume_scale.pack() # main entry point app.protocol("WM_DELETE_WINDOW", shutdown) app.mainloop() From bill at celestial.net Fri Feb 26 20:48:49 2010 From: bill at celestial.net (Bill Campbell) Date: Fri, 26 Feb 2010 11:48:49 -0800 Subject: [Tutor] imaplib command to delete messages Message-ID: <20100226194849.GA31962@ayn.mi.celestial.com> I've written a script to go through varions Sent folders on IMAP servers to archive the messages on a central server using imaplib to do the heavy lifting. Perhaps I'm a bit thick, but I have not been able to figure out how to delete messages in the folders after processing them. The imaplib documentation as lots of ways to delete mailboxes (folders) and expunge messages from folders, but I don't see anything about marking individual messages as deleted. What am I missing? 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 Skype: jwccsllc (206) 855-5792 Our Foreign dealings are an Open Book, generally a Check Book. Will Rogers From alan.gauld at btinternet.com Fri Feb 26 21:22:17 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 26 Feb 2010 20:22:17 -0000 Subject: [Tutor] Help me understand this tkinter related code References: <4B86F39B.5010108@howlermonkey.net> Message-ID: Please don't hijack an old message to create a new subject. Those of us using threaded readers might not see it and you lose potential answers. "Robert DeLaurentis" wrote > The local function change_volume(v) requires the argument v to operate > properly, > but I'm unclear where the value of that argument is being set or why the > code fails > without it. > def change_volume(v): > track.set_volume(volume.get()) > > volume_scale = Scale(app, > variable = volume, > from_ = 0.0, > to = 1.0, > resolution = 0.1, > command = change_volume, > label = "Volume", > orient = HORIZONTAL) I'm not familiar with the wodget in question but it looks like the command callback expects to pass a parameter to the callback function. Therefore the function needs to provide a placeholder even though it doesn't use it! You would need to find the documentation for the widget to confirm that theory however. A Google seartch threw up this: http://infohost.nmt.edu/tcc/help/pubs/tkinter/scale.html Which seems to confirm my theory :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From karim.liateni at free.fr Sat Feb 27 01:09:54 2010 From: karim.liateni at free.fr (karim.liateni at free.fr) Date: Sat, 27 Feb 2010 01:09:54 +0100 (CET) Subject: [Tutor] Removing redundant parameters in a models file having include files. In-Reply-To: <18558536.16993131267229341903.JavaMail.root@spooler2-g27.priv.proxad.net> Message-ID: <21826548.16993151267229394589.JavaMail.root@spooler2-g27.priv.proxad.net> Hello All, This is my first program in python. I am doing electrical simulation in spectre (spice like). I have a models file which holds many parameters and include files of parameters. But in batch mode the automatic construction (by the simulator) of this file is not correct. It concatenates both parameters and include files with the same parameters definitions. That trigs errors during simulation and it complains about parameters double definition. The file format is shown below: // ------------------------------------------------------ // Mismatch Variations Selection // ------------------------------------------------------ parameters param1=0 parameters param2=0 parameters param3=0 parameters param4=0 // ------------------------------------------------------ // Global Flags Definition // ------------------------------------------------------ parameters gflag_param = 0 // ------------------------------------------------------ // Models Library Files References // ------------------------------------------------------ include "/project/hvt.scs" section=TT include "/project/lvt.scs" section=TT include "/project/svt.scs" section=TT include "/project/veriloga.scs" section=typ include "/project/switch_all.scs" section=no ------------------------------------------------------- Now my code is shown below: ___________________________ #!/usr/bin/env python # File: correctCorners K.Liateni 2010-02-25 import re # ------------------------------- # Functions Declaration # ------------------------------- def copy(infile, outfile): """Copy of the content of an input file to an outputfile.""" fout = open(outfile, 'w') fout.writelines(getLines(infile)) fout.close() def cat(lines, outfile): """Concat the content of a strings list to an outputfile.""" f = open(outfile, 'w') f.writelines(lines) f.close() def getLines(file): """Get the content of a file in a lines list form.""" f = open(file, 'r') lines = f.readlines() f.close() return lines def isParamExist(file, pattern, parameters): """Check if a particular regex pattern parameter is existing in a parameters file.""" lines = getLines(file) paramExpressions = [ e for e in lines if pattern.search(e) ] matchParam = [ e for e in paramExpressions if pattern.search(e).group(1) in parameters ] if matchParam: return True else: return False # ------------------------------- # Main Start here # ------------------------------- parRe = '^[ \t]*(parameters[ \t]+[^ \t]+)[ \t]*=' comRe = '^[ \t]*//' include = re.compile(incRe) param = re.compile(parRe) comment = re.compile(comRe) lines = getLines("models.scs") linesWithNoInclude = [ e for e in lines if not include.search(e) ] linesWithNoParam = [ e for e in lines if not param.search(e) and not comment.search(e) ] parameters = [ param.search(e).group(1) for e in linesWithNoInclude if param.search(e) ] includeFiles = [ include.search(e).group(1) for e in linesWithNoParam ] includeFilesToWrite = [ e for e in includeFiles if not isParamExist(e, param, parameters) ] includeFilesToWrite = [ e for e in linesWithNoParam if include.search(e).group(3) in includeFilesToWrite ] cat(linesWithNoInclude+includeFilesToWrite, "models_modified.scs") copy("models_modified.scs", "models.scs"): # ----------- end of file ----------- # The code works well but I am not fully happy with it. includeFilesToWrite is computed in 2 steps. I am pretty sure that it can be simplify by using a dictionnary with the full path file as the key and the string 'include' nominal line expression as the value to construct the final file with filtered include. I am using python 2.2 so I have not use latest feature I want my code to run on old Solaris too (linux user). I use as much as possible list comprehension following your advices. I don't like the part: if matchParam: return True else: return False Is there an easy way to do the same behavior. I am not sure but I saw one time something like using the int value of True (1) and False (0) to select return value in a list of 2 elements 'return [False,True](matchParam)' Is it correct? Thanks a lot Karim From karim.liateni at free.fr Sat Feb 27 01:19:19 2010 From: karim.liateni at free.fr (karim.liateni at free.fr) Date: Sat, 27 Feb 2010 01:19:19 +0100 (CET) Subject: [Tutor] Fwd: Removing redundant parameters in a models file having include files. In-Reply-To: <21826548.16993151267229394589.JavaMail.root@spooler2-g27.priv.proxad.net> Message-ID: <12896479.16993461267229959447.JavaMail.root@spooler2-g27.priv.proxad.net> Hello All, This is my first program in python. I am doing electrical simulation in spectre (spice like). I have a models file which holds many parameters and include files of parameters. But in batch mode the automatic construction (by the simulator) of this file is not correct. It concatenates both parameters and include files with the same parameters definitions. That trigs errors during simulation and it complains about parameters double definition. The file format is shown below: // ------------------------------------------------------ // Mismatch Variations Selection // ------------------------------------------------------ parameters param1=0 parameters param2=0 parameters param3=0 parameters param4=0 // ------------------------------------------------------ // Global Flags Definition // ------------------------------------------------------ parameters gflag_param = 0 // ------------------------------------------------------ // Models Library Files References // ------------------------------------------------------ include "/project/hvt.scs" section=TT include "/project/lvt.scs" section=TT include "/project/svt.scs" section=TT include "/project/veriloga.scs" section=typ include "/project/switch_all.scs" section=no ------------------------------------------------------- Now my code is shown below: ___________________________ #!/usr/bin/env python # File: correctCorners K.Liateni 2010-02-25 import re # ------------------------------- # Functions Declaration # ------------------------------- def copy(infile, outfile): """Copy of the content of an input file to an outputfile.""" fout = open(outfile, 'w') fout.writelines(getLines(infile)) fout.close() def cat(lines, outfile): """Concat the content of a strings list to an outputfile.""" f = open(outfile, 'w') f.writelines(lines) f.close() def getLines(file): """Get the content of a file in a lines list form.""" f = open(file, 'r') lines = f.readlines() f.close() return lines def isParamExist(file, pattern, parameters): """Check if a particular regex pattern parameter is existing in a parameters file.""" lines = getLines(file) paramExpressions = [ e for e in lines if pattern.search(e) ] matchParam = [ e for e in paramExpressions if pattern.search(e).group(1) in parameters ] if matchParam: return True else: return False # ------------------------------- # Main Start here # ------------------------------- parRe = '^[ \t]*(parameters[ \t]+[^ \t]+)[ \t]*=' comRe = '^[ \t]*//' include = re.compile(incRe) param = re.compile(parRe) comment = re.compile(comRe) lines = getLines("models.scs") linesWithNoInclude = [ e for e in lines if not include.search(e) ] linesWithNoParam = [ e for e in lines if not param.search(e) and not comment.search(e) ] parameters = [ param.search(e).group(1) for e in linesWithNoInclude if param.search(e) ] includeFiles = [ include.search(e).group(1) for e in linesWithNoParam ] includeFilesToWrite = [ e for e in includeFiles if not isParamExist(e, param, parameters) ] includeFilesToWrite = [ e for e in linesWithNoParam if include.search(e).group(3) in includeFilesToWrite ] cat(linesWithNoInclude+includeFilesToWrite, "models_modified.scs") copy("models_modified.scs", "models.scs"): # ----------- end of file ----------- # The code works well but I am not fully happy with it. includeFilesToWrite is computed in 2 steps. I am pretty sure that it can be simplify by using a dictionnary with the full path file as the key and the string 'include' nominal line expression as the value to construct the final file with filtered include. I am using python 2.2 so I have not use latest feature I want my code to run on old Solaris too (linux user). I use as much as possible list comprehension following your advices. I don't like the part: if matchParam: return True else: return False Is there an easy way to do the same behavior. I am not sure but I saw one time something like using the int value of True (1) and False (0) to select return value in a list of 2 elements 'return [False,True](matchParam)' Is it correct? Thanks a lot Karim From karim.liateni at free.fr Sat Feb 27 09:17:49 2010 From: karim.liateni at free.fr (Karim Liateni) Date: Sat, 27 Feb 2010 09:17:49 +0100 Subject: [Tutor] Removing redundant parameters in a models file having include files. In-Reply-To: <21826548.16993151267229394589.JavaMail.root@spooler2-g27.priv.proxad.net> References: <21826548.16993151267229394589.JavaMail.root@spooler2-g27.priv.proxad.net> Message-ID: <4B88D52D.1060402@free.fr> Ok I must add an explanation The program must removes includes files of already existing parameters in the models file. Karim karim.liateni at free.fr wrote: > Hello All, > > This is my first program in python. > > I am doing electrical simulation in spectre (spice like). > I have a models file which holds many parameters and > include files of parameters. But in batch mode the automatic > construction (by the simulator) of this file is not correct. > It concatenates both parameters and include files with the same > parameters definitions. That trigs errors during simulation and > it complains about parameters double definition. > The file format is shown below: > > // ------------------------------------------------------ > // Mismatch Variations Selection > // ------------------------------------------------------ > parameters param1=0 > parameters param2=0 > parameters param3=0 > parameters param4=0 > // ------------------------------------------------------ > // Global Flags Definition > // ------------------------------------------------------ > parameters gflag_param = 0 > // ------------------------------------------------------ > // Models Library Files References > // ------------------------------------------------------ > include "/project/hvt.scs" section=TT > include "/project/lvt.scs" section=TT > include "/project/svt.scs" section=TT > include "/project/veriloga.scs" section=typ > include "/project/switch_all.scs" section=no > ------------------------------------------------------- > > Now my code is shown below: > ___________________________ > > #!/usr/bin/env python > # File: correctCorners K.Liateni 2010-02-25 > > import re > > # ------------------------------- > # Functions Declaration > # ------------------------------- > > def copy(infile, outfile): > """Copy of the content of an input file to an outputfile.""" > fout = open(outfile, 'w') > fout.writelines(getLines(infile)) > fout.close() > > def cat(lines, outfile): > """Concat the content of a strings list to an outputfile.""" > f = open(outfile, 'w') > f.writelines(lines) > f.close() > > def getLines(file): > """Get the content of a file in a lines list form.""" > f = open(file, 'r') > lines = f.readlines() > f.close() > return lines > > def isParamExist(file, pattern, parameters): > """Check if a particular regex pattern parameter is existing in a parameters file.""" > lines = getLines(file) > paramExpressions = [ e for e in lines if pattern.search(e) ] > matchParam = [ e for e in paramExpressions if pattern.search(e).group(1) in parameters ] > if matchParam: > return True > else: > return False > > # ------------------------------- > # Main Start here > # ------------------------------- > > parRe = '^[ \t]*(parameters[ \t]+[^ \t]+)[ \t]*=' > comRe = '^[ \t]*//' > > include = re.compile(incRe) > param = re.compile(parRe) > comment = re.compile(comRe) > > lines = getLines("models.scs") > > linesWithNoInclude = [ e for e in lines if not include.search(e) ] > linesWithNoParam = [ e for e in lines if not param.search(e) and not comment.search(e) ] > > parameters = [ param.search(e).group(1) for e in linesWithNoInclude if param.search(e) ] > includeFiles = [ include.search(e).group(1) for e in linesWithNoParam ] > > includeFilesToWrite = [ e for e in includeFiles if not isParamExist(e, param, parameters) ] > includeFilesToWrite = [ e for e in linesWithNoParam if include.search(e).group(3) in includeFilesToWrite ] > > cat(linesWithNoInclude+includeFilesToWrite, "models_modified.scs") > copy("models_modified.scs", "models.scs"): > > # ----------- end of file ----------- # > > The code works well but I am not fully happy with it. includeFilesToWrite is computed in 2 steps. > I am pretty sure that it can be simplify by using a dictionnary with the full path file as the key > and the string 'include' nominal line expression as the value to construct the final file with filtered include. > I am using python 2.2 so I have not use latest feature I want my code to run on old Solaris too (linux user). > > I use as much as possible list comprehension following your advices. > > I don't like the part: > if matchParam: > return True > else: > return False > Is there an easy way to do the same behavior. I am not sure but I saw one time something like using > the int value of True (1) and False (0) to select return value in a list of 2 elements 'return [False,True](matchParam)' > Is it correct? > > Thanks a lot > Karim > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From lie.1296 at gmail.com Sat Feb 27 14:20:37 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 28 Feb 2010 00:20:37 +1100 Subject: [Tutor] wHY In-Reply-To: <4B8703BD.8010502@howlermonkey.net> References: <4B8703BD.8010502@howlermonkey.net> Message-ID: Why? That's a good philosophical question... hmm... why? Hmm.... From lie.1296 at gmail.com Sat Feb 27 14:29:11 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 28 Feb 2010 00:29:11 +1100 Subject: [Tutor] How to use pydoc In-Reply-To: <4B87CD1A.1080108@gmail.com> References: <4B87CD1A.1080108@gmail.com> Message-ID: On 02/27/10 00:31, Ricardo Ar?oz wrote: > Checked the manuals on pydoc and wanted to try it. Must certainly be > doing something wrong but I can't figure what. Here's my session : The pydoc command works from your system shell (e.g. bash), not python shell; if you want to get help inside python's shell, use the help() built-in function. $ pydoc itertools # showing itertools's doc on your default pager (usually `less`) # $ python Python 2.6.4 (r264:75706, Jan 12 2010, 05:24:27) [GCC 4.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help('itertools') # showing itertools's doc on your default pager (usually `less`) # >>> # you need to pass the module's name as a string to help() >>> # either that, or import the module first: >>> import itertools >>> help(itertools) # showing itertools's doc on your default pager (usually `less`) # >>> From emile at fenx.com Sat Feb 27 17:59:02 2010 From: emile at fenx.com (Emile van Sebille) Date: Sat, 27 Feb 2010 08:59:02 -0800 Subject: [Tutor] imaplib command to delete messages In-Reply-To: <20100226194849.GA31962@ayn.mi.celestial.com> References: <20100226194849.GA31962@ayn.mi.celestial.com> Message-ID: On 2/26/2010 11:48 AM Bill Campbell said... > I've written a script to go through varions Sent folders on > IMAP servers to archive the messages on a central server using > imaplib to do the heavy lifting. Perhaps I'm a bit thick, but I > have not been able to figure out how to delete messages in the > folders after processing them. The imaplib documentation as lots > of ways to delete mailboxes (folders) and expunge messages from > folders, but I don't see anything about marking individual > messages as deleted. I can't confirm it's still current, but this tip from Donn Cave might help: It's only a flag, to identify the message that as you noted will be actually deleted later by an expunge. ok, error = imapobject.store(number, 'FLAGS', '(\Deleted)') (from http://groups.google.com/group/comp.lang.python/browse_thread/thread/dfd041398e86c1fd/884359798ce1e025?q=python+imaplib+delete+message) Emile > > What am I missing? > > Bill From sierra_mtnview at sbcglobal.net Sat Feb 27 19:30:49 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 27 Feb 2010 10:30:49 -0800 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <4B84826B.7030204@ieee.org> References: <4B83ED4A.4040203@sbcglobal.net> <4B84826B.7030204@ieee.org> Message-ID: <4B8964D9.7040404@sbcglobal.net> Ok, I'm back after a three day trip. You are correct about the use of pronouns and a few misplaced words. I should have reread what I wrote. I had described this in better detail elsewhere, and followed that description with the request here probably thinking back to it. I think I was getting a bit weary of trying to find an answer. Try t;his. Folder1 track1.py data1.txt data2.txt data3.txt Folder2 track1.py dset1.txt dset2.txt ... dset8.txt data and dset files have the same record formats. track1.py was copied into Folder2 with ctrl-c + ctrl-v. When I run track1.py from folder1, it clearly has examined the data.txt files. If I run the copy of track1.py in folder2, it clearly operates on folder1 (one) data.txt files. This should not be. If I look at the properties of track1.py in folder2 (two), it is pointing back to the program in folder1 (one). I do not believe I've experienced this sort of linkage in any WinOS before. I believed I confirmed that the same behavior occurs using cmd prompt. I'll now head for Alan's reply. On 2/23/2010 5:35 PM, Dave Angel wrote: > > Wayne Watson wrote: >> A few days ago I posted a message titled ""Two" Card Monty. The >> problem I mentioned looks legitimate, and remains puzzling. I've >> probed this in a newsgroup, and no one has an explanation that fits. >> >> My claim is that if one creates a program in a folder that reads a >> file in the folder it ... then copies it to another folder, it will >> read the data file in the first folder, and not a changed file in >> the new folder. I'd appreciate it if some w7 users could try the >> program below, and let me know what they find. I'm using IDLE in >> Win7 with Py 2.5. >> >> My experience is that if one checks the properties of the copied >> file, it will point to the original py file and execute it and not >> the copy. If win7 is the culprit, I would think this is a somewhat >> serious problem. It may be the sample program is not representative >> of the larger program that has me stuck. If necessary I can provide >> it. It uses common modules. (Could this be something like the >> namespace usage of variables that share a common value?) >> >> # Test program. Examine strange link in Python under Win7 >> # when copying py file to another folder. >> # Call the program vefifywin7.py >> # To verify my situation use IDLE, save and run this program there. >> # Put this program into a folder along with a data file >> # called verify.txt. Create a single text line with a few characters >> in it >> # Run this program and note the output >> # Copy the program and txt file to another folder >> # Change the contents of the txt file >> # Run it again, and see if the output is the same as in the other folder >> track_file = open("verify.txt") >> aline = track_file.readline(); >> print aline >> track_file.close() >> > I find your English is very confusing. Instead of using so many > pronouns with confusing antecedents, try being explicit. > > >My claim is that if one creates a program in a folder that reads a > file in the folder > > Why not say that you created a program and a data file in the same > folder, and had the program read the data file? > > >...in the folder it and then copies it to another folder > > That first 'it' makes no sense, and the second 'it' probably is meant > to be "them". And who is it that does this copying? And using what > method? > > > ... it will read the data file in the first folder > > Who will read the data file? The first program, the second, or maybe > the operator? > > About now, I have to give up. I'm guessing that the last four lines > of your message were intended to be the entire program, and that that > same program is stored in two different folders, along with data files > having the same name but different first lines. When you run one of > these programs it prints the wrong version of the line. > > You have lots of variables here, Python version, program contents, > Idle, Windows version. Windows 7 doesn't do any mysterious "linking," > so I'd stop making that your working hypothesis. Your problem is most > likely the value of current directory ( os.getcwd() ). And that's set > according to at least three different rules, depending on what program > launches Python. If you insist on using Idle to launch it, then > you'll have to convince someone who uses Idle to tell you its > quirks. Most likely it has a separate menu for the starting > directory than for the script name & location. But if you're willing > to use the command line, then I could probably help, once you get a > clear statement of the problem. By default, CMD.EXE uses the current > directory as part of its prompt, and that's the current directory > Python will start in. > > But the first things to do are probably to print out the value of > os.getcwd(), and to add a slightly different print in each version of > the program so you know which one is running. > > Incidentally, I'd avoid ever opening a data file in "the current > directory." If I felt it important to use the current directory as an > implied parameter to the program, I'd save it in a string, and build > the full path to the desired file using os.path.join() or equivalent. > > DaveA > > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Sat Feb 27 19:42:33 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 27 Feb 2010 10:42:33 -0800 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <4B8964D9.7040404@sbcglobal.net> References: <4B83ED4A.4040203@sbcglobal.net> <4B84826B.7030204@ieee.org> <4B8964D9.7040404@sbcglobal.net> Message-ID: <4B896799.4090200@sbcglobal.net> I just referenced Alan to my response to you, and included this statement. Once you've both read the first reply to you and this, then you should both be in synch with where I'm at. ================To Alan=============== Oh, I also changed the name of folder1 in the reply to Dave to see what would happen with the "copied" py file in folder2 upon execution. It couldn't find the py file in folder1. -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From steve at pearwood.info Sat Feb 27 19:58:19 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 28 Feb 2010 05:58:19 +1100 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <4B8964D9.7040404@sbcglobal.net> References: <4B83ED4A.4040203@sbcglobal.net> <4B84826B.7030204@ieee.org> <4B8964D9.7040404@sbcglobal.net> Message-ID: <201002280558.20154.steve@pearwood.info> On Sun, 28 Feb 2010 05:30:49 am Wayne Watson wrote: > Ok, I'm back after a three day trip. You are correct about the use of > pronouns and a few misplaced words. I should have reread what I > wrote. I had described this in better detail elsewhere, and followed > that description with the request here probably thinking back to it. > I think I was getting a bit weary of trying to find an answer. Try > t;his. > > > Folder1 > track1.py > data1.txt > data2.txt > data3.txt > > Folder2 > track1.py > dset1.txt > dset2.txt > ... > dset8.txt > > data and dset files have the same record formats. track1.py was > copied into Folder2 with ctrl-c + ctrl-v. When I run track1.py from > folder1, it clearly has examined the data.txt files. If I run the > copy of track1.py in folder2, it clearly operates on folder1 (one) > data.txt files. This should not be. Without seeing the code in track1.py, we cannot judge whether it should be or not. I can think of lots of reasons why it should be. For example: if you have hard-coded the path to Folder1 if you call os.chdir(Folder1) if you have changed the PATH so that Folder1 gets searched before the current directory then the behaviour you describe theoretically could happen. How are you calling track1.py? Do you do this? cd Folder2 python track1.py What if you change the second line to: python ./track1.py Are you perhaps using this? python -m track1 If you change the name of the copy from track1.py to copy_of_track1.py, and then call this: python copy_of_track1.py how does the behaviour change? > If I look at the properties of track1.py in folder2 (two), it is > pointing back to the program in folder1 (one). What? "Pointing back", as in a Shortcut? Or a symlink? If you've created a shortcut instead of a copy, I'm not surprised you are executing it in the "wrong" folder. That's what shortcuts do. -- Steven D'Aprano From sierra_mtnview at sbcglobal.net Sat Feb 27 21:29:16 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 27 Feb 2010 12:29:16 -0800 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <201002280558.20154.steve@pearwood.info> References: <4B83ED4A.4040203@sbcglobal.net> <4B84826B.7030204@ieee.org> <4B8964D9.7040404@sbcglobal.net> <201002280558.20154.steve@pearwood.info> Message-ID: <4B89809C.8070304@sbcglobal.net> See below. On 2/27/2010 10:58 AM, Steven D'Aprano wrote: > On Sun, 28 Feb 2010 05:30:49 am Wayne Watson wrote: > >> Ok, I'm back after a three day trip. You are correct about the use of >> pronouns and a few misplaced words. I should have reread what I >> wrote. I had described this in better detail elsewhere, and followed >> that description with the request here probably thinking back to it. >> I think I was getting a bit weary of trying to find an answer. Try >> this. >> >> >> Folder1 >> track1.py >> data1.txt >> data2.txt >> data3.txt >> >> Folder2 >> track1.py >> dset1.txt >> dset2.txt >> ... >> dset8.txt >> >> data and dset files have the same record formats. track1.py was >> copied into Folder2 with ctrl-c + ctrl-v. When I run track1.py from >> folder1, it clearly has examined the data.txt files. If I run the >> copy of track1.py in folder2, it clearly operates on folder1 (one) >> data.txt files. This should not be. >> > Without seeing the code in track1.py, we cannot judge whether it should > be or not. I can think of lots of reasons why it should be. For > example: > I'll attach the code to this. However, I haven't had the best of luck getting attachments posted. Frankly, I think it's better to try the sample program I provided at the top of the thread. If you are not using Win7, I don't think this is going to work well, but maybe you'll see something that's a no-no in any OS. I have several data files, if anyone wants to go that far. I can supply a data file if necessary. Note this program is still in development. In fact, I was going to pull the debug "wtw" statements and wrap it all up when this problem occurred. > if you have hard-coded the path to Folder1 > > if you call os.chdir(Folder1) > Not to my knowledge. I just "assume" that the program will read the txt files in alpha order in the same folder as the program. > if you have changed the PATH so that Folder1 gets searched before the > current directory > > then the behaviour you describe theoretically could happen. > > How are you calling track1.py? Do you do this? > > cd Folder2 > python track1.py > Yes, I believe I've tried that. > What if you change the second line to: > > python ./track1.py > > Are you perhaps using this? > > python -m track1 > Don't even know what it means. > If you change the name of the copy from track1.py to copy_of_track1.py, > and then call this: > > python copy_of_track1.py > > how does the behaviour change? > I'll try it later. I probably have tried it already. See my "point" comments below. If Properties doesn't change, changing the name isn't going to work. > > >> If I look at the properties of track1.py in folder2 (two), it is >> pointing back to the program in folder1 (one). >> > What? "Pointing back", as in a Shortcut? Or a symlink? > Aren't symlinks Linux world? I know nothing about them. Windows7 Properties of track1.py in folder 2 (two) show the py file is really in folder1. > If you've created a shortcut instead of a copy, I'm not surprised you > are executing it in the "wrong" folder. That's what shortcuts do. > If I've created a shortcut, it wasn't by design. Ctrl-c to ctrl-v most likely. > > > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ReportingToolAww.py URL: From davea at ieee.org Sat Feb 27 21:38:58 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 27 Feb 2010 15:38:58 -0500 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <4B8964D9.7040404@sbcglobal.net> References: <4B83ED4A.4040203@sbcglobal.net> <4B84826B.7030204@ieee.org> <4B8964D9.7040404@sbcglobal.net> Message-ID: <4B8982E2.5020705@ieee.org> Wayne Watson wrote: > Ok, I'm back after a three day trip. You are correct about the use of > pronouns and a few misplaced words. I should have reread what I wrote. > I had described this in better detail elsewhere, and followed that > description with the request here probably thinking back to it. I > think I was getting a bit weary of trying to find an answer. Try t;his. > > > Folder1 > track1.py > data1.txt > data2.txt > data3.txt > > Folder2 > track1.py > dset1.txt > dset2.txt > ... > dset8.txt > So how do you know this is the structure? If there really are shortcuts or symbol links, why aren't you showing them? Did you do a DIR from the command line, to see what's there? Or are you looking in Explorer, which doesn't even show file extensions by default, and just guessing what's where ? > data and dset files have the same record formats. track1.py was copied > into Folder2 with ctrl-c + ctrl-v. Those keys don't work from a command prompt. From there, you'd use COPY or something similar. So I have to guess you were in an Explorer window, pointing to Folder 1, and you selected the python file, and pressed Ctrl-C. Then you navigated to Folder 2, and pressed Ctrl-V. If you did, Windows 7 wouldn't have created any kind of special file, any more than earlier ones did. Chances are you actually did something else. For example, you might have used a right-click drag, and answered "create shortcut" when it asked what you wanted to do. Or perhaps you did drag/drop with some ctrl-or alt-key modifier. Anyway, you need to be more explicit about what you did. If you had used a command prompt, you could at least have pasted the things you tried directly to your message, so we wouldn't have so much guessing to do. > When I run track1.py from folder1, it clearly has examined the > data.txt files. And how are you running track1.py ? And how do you really know that's what ran? The code you posted would display a string, then the window would immediately go away, so you couldn't read it anyway. > If I run the copy of track1.py in folder2, it clearly operates on > folder1 (one) data.txt files. This should not be. > > If I look at the properties of track1.py in folder2 (two), it is > pointing back to the program in folder1 (one). Exactly what do you mean by "pointing back" ? If you're getting icons in your Explorer view, is there a little arrow in the corner? When you did the properties, did you see a tab labeled "shortcut" ? > > > I do not believe I've experienced this sort of linkage in any WinOS > before. I believed I confirmed that the same behavior occurs using cmd > prompt. > Shortcuts have been in Windows for at least 20 years. But you still haven't given enough clues about what you're doing. > I'll now head for Alan's reply. > > On 2/23/2010 5:35 PM, Dave Angel wrote: >> >> Wayne Watson wrote: >>> A few days ago I posted a message titled ""Two" Card Monty. The >>> problem I mentioned looks legitimate, and remains puzzling. I've >>> probed this in a newsgroup, and no one has an explanation that fits. >>> >>> My claim is that if one creates a program in a folder that reads a >>> file in the folder it ... then copies it to another folder, it will >>> read the data file in the first folder, and not a changed file in >>> the new folder. I'd appreciate it if some w7 users could try the >>> program below, and let me know what they find. I'm using IDLE in >>> Win7 with Py 2.5. >>> >>> My experience is that if one checks the properties of the copied >>> file, it will point to the original py file and execute it and not >>> the copy. If win7 is the culprit, I would think this is a somewhat >>> serious problem. It may be the sample program is not representative >>> of the larger program that has me stuck. If necessary I can provide >>> it. It uses common modules. (Could this be something like the >>> namespace usage of variables that share a common value?) >>> >>> # Test program. Examine strange link in Python under Win7 >>> # when copying py file to another folder. >>> # Call the program vefifywin7.py >>> # To verify my situation use IDLE, save and run this program there. >>> # Put this program into a folder along with a data file >>> # called verify.txt. Create a single text line with a few characters >>> in it >>> # Run this program and note the output >>> # Copy the program and txt file to another folder >>> # Change the contents of the txt file >>> # Run it again, and see if the output is the same as in the other >>> folder >>> track_file = open("verify.txt") >>> aline = track_file.readline(); >>> print aline >>> track_file.close() >>> >> I find your English is very confusing. Instead of using so many >> pronouns with confusing antecedents, try being explicit. >> >> >My claim is that if one creates a program in a folder that reads a >> file in the folder >> >> Why not say that you created a program and a data file in the same >> folder, and had the program read the data file? >> >> >...in the folder it and then copies it to another folder >> >> That first 'it' makes no sense, and the second 'it' probably is meant >> to be "them". And who is it that does this copying? And using what >> method? >> >> > ... it will read the data file in the first folder >> >> Who will read the data file? The first program, the second, or maybe >> the operator? >> >> About now, I have to give up. I'm guessing that the last four lines >> of your message were intended to be the entire program, and that that >> same program is stored in two different folders, along with data >> files having the same name but different first lines. When you run >> one of these programs it prints the wrong version of the line. >> >> You have lots of variables here, Python version, program contents, >> Idle, Windows version. Windows 7 doesn't do any mysterious >> "linking," so I'd stop making that your working hypothesis. Your >> problem is most likely the value of current directory ( os.getcwd() >> ). And that's set according to at least three different rules, >> depending on what program launches Python. If you insist on using >> Idle to launch it, then you'll have to convince someone who uses Idle >> to tell you its quirks. Most likely it has a separate menu for the >> starting directory than for the script name & location. But if >> you're willing to use the command line, then I could probably help, >> once you get a clear statement of the problem. By default, CMD.EXE >> uses the current directory as part of its prompt, and that's the >> current directory Python will start in. >> >> But the first things to do are probably to print out the value of >> os.getcwd(), and to add a slightly different print in each version of >> the program so you know which one is running. >> >> Incidentally, I'd avoid ever opening a data file in "the current >> directory." If I felt it important to use the current directory as >> an implied parameter to the program, I'd save it in a string, and >> build the full path to the desired file using os.path.join() or >> equivalent. >> >> DaveA >> >> > From sierra_mtnview at sbcglobal.net Sat Feb 27 23:38:44 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 27 Feb 2010 14:38:44 -0800 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <4B8982E2.5020705@ieee.org> References: <4B83ED4A.4040203@sbcglobal.net> <4B84826B.7030204@ieee.org> <4B8964D9.7040404@sbcglobal.net> <4B8982E2.5020705@ieee.org> Message-ID: <4B899EF4.1030106@sbcglobal.net> On 2/27/2010 12:38 PM, Dave Angel wrote: > > > Wayne Watson wrote: >> Ok, I'm back after a three day trip. You are correct about the use of >> pronouns and a few misplaced words. I should have reread what I >> wrote. I had described this in better detail elsewhere, and followed >> that description with the request here probably thinking back to it. >> I think I was getting a bit weary of trying to find an answer. Try >> t;his. >> >> >> Folder1 >> track1.py >> data1.txt >> data2.txt >> data3.txt >> >> Folder2 >> track1.py >> dset1.txt >> dset2.txt >> ... >> dset8.txt >> > So how do you know this is the structure? If there really are > shortcuts or symbol links, why aren't you showing them? Did you do a > DIR from the command line, to see what's there? Or are you looking in > Explorer, which doesn't even show file extensions by default, and just > guessing what's where ? I can see it looking at the folder. I suppose one might call it Win Explorer. It doesn't show any links. If I pick a file and right click on it, then a number of menu items are shown. If I pick Properties, it shows the link. The only link I need to provide you for the above, I described below. Look at the properties of the py file in folder2. > >> data and dset files have the same record formats. track1.py was >> copied into Folder2 with ctrl-c + ctrl-v. > > Those keys don't work from a command prompt. From there, you'd use > COPY or something similar. So I have to guess you were in an Explorer > window, pointing to Folder 1, and you selected the python file, and > pressed Ctrl-C. Then you navigated to Folder 2, and pressed Ctrl-V. > If you did, Windows 7 wouldn't have created any kind of special file, > any more than earlier ones did. Chances are you actually did > something else. For example, you might have used a right-click drag, > and answered "create shortcut" when it asked what you wanted to do. > Or perhaps you did drag/drop with some ctrl-or alt-key modifier. You're right. I either dragged and dropped, or right clicked on the file and used the copy item. Similarly pasted, It's almost second nature to me. I'll do one right now using Explorer. I'm in a folder that I called folder1 here. It has lots of txt files. I selected one, and mouse clicked copy. I then created a sub folder called junk, and selected it's empty, as expected. Now a mouse click to paste. The txt file is there. I mouse click on properties and the "link" says it's right where I punt it. In junk. > > Anyway, you need to be more explicit about what you did. If you had > used a command prompt, you could at least have pasted the things you > tried directly to your message, so we wouldn't have so much guessing > to do. Well, I guess I could get out my video camera and make a video, which I say tongue-in-cheek, but I really can do that. >> When I run track1.py from folder1, it clearly has examined the >> data.txt files. > And how are you running track1.py ? And how do you really know that's > what ran? The code you posted would display a string, then the window > would immediately go away, so you couldn't read it anyway. Awhile ago I ran it from IDLE. I know it rain because it puts output on the shell window, and writes three files. >> If I run the copy of track1.py in folder2, it clearly operates on >> folder1 (one) data.txt files. This should not be. >> >> If I look at the properties of track1.py in folder2 (two), it is >> pointing back to the program in folder1 (one). > Exactly what do you mean by "pointing back" ? If you're getting icons > in your Explorer view, is there a little arrow in the corner? When > you did the properties, did you see a tab labeled "shortcut" ? I do not use shortcut. I really don't know about Explorer. I use what is probably Explorer. It works like this. Go to drive C:. It displays 15 folders. I click on the a folder until I get to my py programs. Once there, I see them and others all listed. >> >> >> I do not believe I've experienced this sort of linkage in any WinOS >> before. I believed I confirmed that the same behavior occurs using >> cmd prompt. >> > Shortcuts have been in Windows for at least 20 years. But you still > haven't given enough clues about what you're doing. > Video anyone? How about a live session? I have a tool made by Cisco that would allow us to look at either's screen Actually, I really don't plan to build a career out of finding out the cause of this, so let's forget that. I'm read to punt. I sent a copy of the program to Steven. I do not see it oisted. Possibly two reasons. It's stuck on my server, or the attachment is being held by the moderator. If someone cannot find the problem there, I think it's MS's problem, and I can probably finagle the code into folder in a way to test it in the "problem" folder. I'm the only user of these programs that is likely to use W7. I can also go back to my XP PC, and finish this off there. From steve at pearwood.info Sun Feb 28 02:24:03 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 28 Feb 2010 12:24:03 +1100 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <4B89809C.8070304@sbcglobal.net> References: <4B83ED4A.4040203@sbcglobal.net> <201002280558.20154.steve@pearwood.info> <4B89809C.8070304@sbcglobal.net> Message-ID: <201002281224.03955.steve@pearwood.info> Hello Wayne, I sympathise with your problem, but please understand you are not making it easy for us when you give us incoherent information. You tell us to "try this" and give a folder structure: Folder1 track1.py data1.txt data2.txt data3.txt Folder2 track1.py dset1.txt dset2.txt ... dset8.txt but then when you send a copy of the actual code you are running, it is called "ReportingToolAwww.py" and it is 417 lines long. What happened to track1.py? What is in that? Does track1.py reproduce the fault? There are five possible faults: 1 A problem in your Python code. 2 A serious bug in Python itself. 3 A serious bug in Windows file system. 4 Disk corruption making Windows confused. 5 A PEBCAK problem. I can confirm that ReportingToolAwww.py doesn't seem to contain any "funny" path manipulations that would cause the problem: it simply calls open on relative path names, which will open files in the current directory. The problem does NOT appear to be in your Python code. A serious bug in either Python or Windows is very unlikely. Not impossible, but unless somebody else reports that they too have seen the fault, we can dismiss them. Disk corruption is possible. If all else fails, you can run the Windows disk utility to see if it finds anything. But the most likely cause of the fault is that you aren't running what you think you are running. When you say: "If I've created a shortcut, it wasn't by design. Ctrl-c to ctrl-v most likely." "Most likely"? Meaning you're not sure? Given that you are talking about the Properties window talking about "pointing to" things, I think it is very likely that in fact you have created a shortcut, or a symlink, and when you think you are running a copy in Folder2 you are actually running a shortcut to Folder1. That would *exactly* explain the problem you are experiencing. Please take a screenshot of the Properties window showing the "pointing to" stuff. I think you will find that track1.py in Folder2 is a shortcut back to track1.py in Folder1. (For the record, Windows does in fact have symlinks, as well as hard links and a third type of link called junction points. They are undersupported by Explorer, and so people hardly every use them. Most people don't even know they exist, even though some of them go back all the way to Windows NT. But as far as I can tell, there is no way for you to have created a symlink from Explorer.) -- Steven D'Aprano From sierra_mtnview at sbcglobal.net Sun Feb 28 04:29:07 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 27 Feb 2010 19:29:07 -0800 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python andWin7 In-Reply-To: References: <4B83ED4A.4040203@sbcglobal.net> Message-ID: <4B89E303.9050204@sbcglobal.net> (Apparently, I did not send this about 6 hours ago. Anyway, here it is.) Let's start from the response I just made to Dave Angel minutes ago, or, at least very recently. I think I wrote a bit more accurately about matters. We'll continue as appropriate from that point. Let me answer some of your questions about the environment from below. I've dropped out of IDLE at times to see that made a difference. Windows 7. IDLE. Command Prompt window for verification. I'm pretty sure I did that once, but will verify it again. Got the same results. Oh, I also changed the name of folder1 in the reply to Dave to see what would happen with the "copied" py file in folder2 upon execution. It couldn't find the py file in folder1. Other questions about the environment? ... > -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Sun Feb 28 06:20:12 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 27 Feb 2010 21:20:12 -0800 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <201002281224.03955.steve@pearwood.info> References: <4B83ED4A.4040203@sbcglobal.net> <201002280558.20154.steve@pearwood.info> <4B89809C.8070304@sbcglobal.net> <201002281224.03955.steve@pearwood.info> Message-ID: <4B89FD0C.1010004@sbcglobal.net> On 2/27/2010 5:24 PM, Steven D'Aprano wrote: > Hello Wayne, > > I sympathise with your problem, but please understand you are not making > it easy for us when you give us incoherent information. > I hope the coherency has improved recently. :-) I think if you saw the cramped quarters I'm in that you might understand my supposed incoherency. For what it's worth, and that's about zero, I'm working with my old XP and W7 machine's keyboards, mice and monitors side-by-side. I have several times found my self using the wrong device. I'm steadily moving from programs and data from one to another. This weekend when I get a printer cable, the XP machine will be relegated to a distant table. > You tell us to "try this" and give a folder structure: > > Folder1 > track1.py > data1.txt > data2.txt > data3.txt > Folder2 > track1.py > dset1.txt > dset2.txt > ... > dset8.txt > > but then when you send a copy of the actual code you are running, it is > called "ReportingToolAwww.py" and it is 417 lines long. What happened > to track1.py? What is in that? Does track1.py reproduce the fault? > Yes, it's a lot easier to type track than the above. I invented fictitious names for the above to simplify it all. The program does indeed work on track data for meteor trails. > There are five possible faults: > > 1 A problem in your Python code. > 2 A serious bug in Python itself. > 3 A serious bug in Windows file system. > 4 Disk corruption making Windows confused. > 5 A PEBCAK problem. > I'd vote for a W7 problem. I think I mentioned that W7 will not even allow me to find all files in a folder with track in them. It's possible the new filter concept for files is at work. > I can confirm that ReportingToolAwww.py doesn't seem to contain > any "funny" path manipulations that would cause the problem: it simply > calls open on relative path names, which will open files in the current > directory. The problem does NOT appear to be in your Python code. > Good. > A serious bug in either Python or Windows is very unlikely. Not > impossible, but unless somebody else reports that they too have seen > the fault, we can dismiss them. > See above about W7. > Disk corruption is possible. If all else fails, you can run the Windows > disk utility to see if it finds anything. > Beats me. > But the most likely cause of the fault is that you aren't running what > you think you are running. When you say: > > "If I've created a shortcut, it wasn't by design. Ctrl-c to ctrl-v most > likely." > > "Most likely"? Meaning you're not sure? > Meaning I agree with you that it was not a use of ctrl-c/v. I offered the other only possibilities I know of. That's for programs likeWord. > Given that you are talking about the Properties window talking > about "pointing to" things, I think it is very likely that in fact you > have created a shortcut, or a symlink, and when you think you are > running a copy in Folder2 you are actually running a shortcut to > Folder1. That would *exactly* explain the problem you are experiencing. > > Please take a screenshot of the Properties window showing the "pointing > to" stuff. I think you will find that track1.py in Folder2 is a > shortcut back to track1.py in Folder1. > OK, I'll do that with SnagIt, and attach it. If it's too big, it will not make it on the list, but will make it to you.Geeze, I can't even do that. I had contacted HP tech support (1 year of free support), and went through this with a tech guy week ago. I gave him control of the machine, and he started messing with the py file.I stopped him before he changed anything, but copied the file somewhere, and renamed it, so he could do what he thought needed to be done. The "link" points to itself. I'm afraid after a week of dealing with this the trail is dead. Chalk it up to a mistake on my part if you will. I'm done. If somehow this magically revives itself in the next few days, I'll respond. It's time to move this program ahead to completion. > (For the record, Windows does in fact have symlinks, as well as hard > links and a third type of link called junction points. They are > undersupported by Explorer, and so people hardly every use them. Most > people don't even know they exist, even though some of them go back all > the way to Windows NT. But as far as I can tell, there is no way for > you to have created a symlink from Explorer.) > > So noted. The last time I had anything to do with the more esoteric links is a decade ago when I worked with Linux. -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From sierra_mtnview at sbcglobal.net Sun Feb 28 06:58:31 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 27 Feb 2010 21:58:31 -0800 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <4B89FD0C.1010004@sbcglobal.net> References: <4B83ED4A.4040203@sbcglobal.net> <201002280558.20154.steve@pearwood.info> <4B89809C.8070304@sbcglobal.net> <201002281224.03955.steve@pearwood.info> <4B89FD0C.1010004@sbcglobal.net> Message-ID: <4B8A0607.806@sbcglobal.net> Hang in there. My story about HP tech support took me a bit off course. I think I can provide a meaningful description from the stand point of the properties of each py file. I want to look at this carefully. -- "There is nothing so annoying as to have two people talking when you're busy interrupting." -- Mark Twain From alan.gauld at btinternet.com Sun Feb 28 10:01:29 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Feb 2010 09:01:29 -0000 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 References: <4B83ED4A.4040203@sbcglobal.net> <201002280558.20154.steve@pearwood.info> <4B89809C.8070304@sbcglobal.net><201002281224.03955.steve@pearwood.info> <4B89FD0C.1010004@sbcglobal.net> Message-ID: "Wayne Watson" wrote > incoherency. For what it's worth, and that's about zero, I'm working > with my old XP and W7 machine's keyboards, mice and monitors > side-by-side. I have several times found my self using the wrong device. In that situation I find it useful to make the old environment as hostile as possible. So I'd make the resolution on the XP box something like 800x600 and set the wallpaper to a garish colour like red. That way I never mistake which machine I'm on! FWIW I do the same with the root account on Unix boxes... That makes sure I spend as little time as possible in the environment that I don't want to stay in. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From anothernetfellow at gmail.com Sun Feb 28 11:56:13 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Sun, 28 Feb 2010 11:56:13 +0100 Subject: [Tutor] CGI File Uploads Message-ID: <23ce85921002280256h1af97a3ey8417a0979bdd6ae5@mail.gmail.com> Hi, today i need some help with the python manual. I've found this fileupload example http://webpython.codepoint.net/cgi_file_upload on that site. It's taking from fileitem attributes like filename and file. Where is the complete list of those attributes or methods? Thankyou -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Feb 28 12:46:58 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 28 Feb 2010 06:46:58 -0500 Subject: [Tutor] Verifying My Troublesome Linkage Claim between Python and Win7 In-Reply-To: <4B89FD0C.1010004@sbcglobal.net> References: <4B83ED4A.4040203@sbcglobal.net> <201002280558.20154.steve@pearwood.info> <4B89809C.8070304@sbcglobal.net> <201002281224.03955.steve@pearwood.info> <4B89FD0C.1010004@sbcglobal.net> Message-ID: <4B8A57B2.9030704@ieee.org> Wayne Watson wrote: > >> You tell us to "try this" and give a folder structure: >> >> Folder1 >> track1.py >> data1.txt >> data2.txt >> data3.txt >> Folder2 >> track1.py >> dset1.txt >> dset2.txt >> ... >> dset8.txt >> > Maybe one simple test at a time will get better responses. Since you wouldn't tell me what tabs you saw in Explorer when you did properties, maybe you'll tell me what you see in CMD. Go to a cmd prompt (DOS prompt), change to the Folder2 directory, and type dir. paste that result, all of it, into a message. I suspect you'll see that you don't have track1.py there at all, but track1.py.lnk If so, that's a shortcut. The only relevant change in Win7 that I know of is that Explorer shows shortcuts as "link" rather than "shortcut." From karim.liateni at free.fr Sun Feb 28 12:53:05 2010 From: karim.liateni at free.fr (Karim Liateni) Date: Sun, 28 Feb 2010 12:53:05 +0100 Subject: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files. Message-ID: <4B8A5921.5000008@free.fr> Hello Tutor, Since Friday I get no answers to my first post. So I re-post it was missed by the numerous arriving email: This is my first program in python. I am doing electrical simulation in spectre (spice like). I have a models file which holds many parameters and include files of parameters. But in batch mode the automatic construction (by the simulator) of this file is not correct. It concatenates both parameters and include files with the same parameters definitions. That trigs errors during simulation and it complains about parameters double definition. The program must removes includes files of already existing parameters in the models file. The file format is shown below: // ------------------------------------------------------ // Mismatch Variations Selection // ------------------------------------------------------ parameters param1=0 parameters param2=0 parameters param3=0 parameters param4=0 // ------------------------------------------------------ // Global Flags Definition // ------------------------------------------------------ parameters gflag_param = 0 // ------------------------------------------------------ // Models Library Files References // ------------------------------------------------------ include "/project/hvt.scs" section=TT include "/project/lvt.scs" section=TT include "/project/svt.scs" section=TT include "/project/veriloga.scs" section=typ include "/project/switch_all.scs" section=no ------------------------------------------------------- Now my code is shown below: ___________________________ #!/usr/bin/env python # File: correctCorners K.Liateni 2010-02-25 import re # ------------------------------- # Functions Declaration # ------------------------------- def copy(infile, outfile): """Copy of the content of an input file to an outputfile.""" fout = open(outfile, 'w') fout.writelines(getLines(infile)) fout.close() def cat(lines, outfile): """Concat the content of a strings list to an outputfile.""" f = open(outfile, 'w') f.writelines(lines) f.close() def getLines(file): """Get the content of a file in a lines list form.""" f = open(file, 'r') lines = f.readlines() f.close() return lines def isParamExist(file, pattern, parameters): """Check if a particular regex pattern parameter is existing in a parameters file.""" lines = getLines(file) paramExpressions = [ e for e in lines if pattern.search(e) ] matchParam = [ e for e in paramExpressions if pattern.search(e).group(1) in parameters ] if matchParam: return True else: return False # ------------------------------- # Main Start here # ------------------------------- parRe = '^[ \t]*(parameters[ \t]+[^ \t]+)[ \t]*=' comRe = '^[ \t]*//' include = re.compile(incRe) param = re.compile(parRe) comment = re.compile(comRe) lines = getLines("models.scs") linesWithNoInclude = [ e for e in lines if not include.search(e) ] linesWithNoParam = [ e for e in lines if not param.search(e) and not comment.search(e) ] parameters = [ param.search(e).group(1) for e in linesWithNoInclude if param.search(e) ] includeFiles = [ include.search(e).group(1) for e in linesWithNoParam ] includeFilesToWrite = [ e for e in includeFiles if not isParamExist(e, param, parameters) ] includeFilesToWrite = [ e for e in linesWithNoParam if include.search(e).group(3) in includeFilesToWrite ] cat(linesWithNoInclude+includeFilesToWrite, "models_modified.scs") copy("models_modified.scs", "models.scs"): # ----------- end of file ----------- # The code works well but I am not fully happy with it. includeFilesToWrite is computed in 2 steps. I am pretty sure that it can be simplify by using a dictionnary with the full path file as the key and the string 'include' nominal line expression as the value to construct the final file with filtered include. I am using python 2.2 so I have not use latest feature I want my code to run on old Solaris too (linux user). I use as much as possible list comprehension following your advices. I don't like the part: if matchParam: return True else: return False Is there an easy way to do the same behavior. I am not sure but I saw one time something like using the int value of True (1) and False (0) to select return value in a list of 2 elements 'return [False,True](matchParam)' Is it correct? Thanks a lot Karim _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From galaxywatcher at gmail.com Sun Feb 28 13:52:42 2010 From: galaxywatcher at gmail.com (galaxywatcher at gmail.com) Date: Sun, 28 Feb 2010 19:52:42 +0700 Subject: [Tutor] Omitting lines matching a list of strings from a file In-Reply-To: <4B86812C.2020902@compuscan.co.za> References: <86405F1B-54DF-422C-AC63-01D79B014FAA@gmail.com> <4B86812C.2020902@compuscan.co.za> Message-ID: >> One formatting detail: there is a blank line after each line >> printed, how do I ged rid of the extra blank lines? > lines = [line.strip() for line in infile if line[146:148] not in > omit_states] > print '\n'.join(lines) This approach stripped leading blank spaces introducing errors into my fixed width file. > or alternatively > > lines = [line for line in infile if line[146:148] not in omit_states] > print ''.join(lines) This works beautifully leaving leading blank spaces intact. Thanks. > Just remember that doing a list comprehension like that on a large > file will drastically reduce the speed of your application as well > as introduce memory bloat. Processing a file with well over 1 million records worked very quickly, several seconds. Did not notice excessive memory bloat. I do have 2 gigs of ram on my Macbook Pro however. From alan.gauld at btinternet.com Sun Feb 28 15:12:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Feb 2010 14:12:59 -0000 Subject: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files. References: <4B8A5921.5000008@free.fr> Message-ID: "Karim Liateni" wrote > It concatenates both parameters and include files with the same > parameters definitions. That trigs errors during simulation and > it complains about parameters double definition. I'd suggest you construct a dictionary based on the param names You can check before you add ca param if one already exists. Or alternatively make a Set of param names and check that for existence before adding a new one. > def copy(infile, outfile): > """Copy of the content of an input file to an outputfile.""" > fout = open(outfile, 'w') > fout.writelines(getLines(infile)) > fout.close() Its probably easier tyo use shutil.copyfile() > def cat(lines, outfile): > """Concat the content of a strings list to an outputfile.""" > f = open(outfile, 'w') > f.writelines(lines) > f.close() > def getLines(file): > """Get the content of a file in a lines list form.""" > f = open(file, 'r') > lines = f.readlines() > f.close() > return lines I'm not sure these functions add enough value to ghave them. I';d probably just use try: open(outfile,'w').writelines(lines) except IOError: #handle error try: lines = open(filename).readlines() except IOError: #handle error The close will be done automatically since you don't hold a reference to the file > def isParamExist(file, pattern, parameters): > """Check if a particular regex pattern parameter is existing in a > parameters file.""" > lines = getLines(file) > paramExpressions = [ e for e in lines if pattern.search(e) ] > matchParam = [ e for e in paramExpressions if > pattern.search(e).group(1) in parameters ] > if matchParam: > return True > else: > return False return bool(matchParam) instead of the if/else > I am pretty sure that it can be simplify by using a dictionnary with the > full path file as the key > and the string 'include' nominal line expression as the value to > construct the final file with filtered include. I think dictionaries or Sets could improve things > I don't like the part: > if matchParam: > return True > else: > return False See the note above. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Feb 28 15:14:51 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 28 Feb 2010 14:14:51 -0000 Subject: [Tutor] CGI File Uploads References: <23ce85921002280256h1af97a3ey8417a0979bdd6ae5@mail.gmail.com> Message-ID: "Giorgio" wrote > It's talking from fileitem attributes like filename and file. > > Where is the complete list of those attributes or methods? Probably on a web page somewhere but you are probably better using the help() function and dir() to examine an instance from the >>> prompt. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From anothernetfellow at gmail.com Sun Feb 28 15:28:33 2010 From: anothernetfellow at gmail.com (Giorgio) Date: Sun, 28 Feb 2010 15:28:33 +0100 Subject: [Tutor] CGI File Uploads In-Reply-To: References: <23ce85921002280256h1af97a3ey8417a0979bdd6ae5@mail.gmail.com> Message-ID: <23ce85921002280628h12c3e333o240af2edd68624be@mail.gmail.com> Alan, i don't know how to use it in this case. import cgi form = cgi.FieldStorage() fileitem = form['file'] fileitem.file.read() Function dir() lists all functions in a module, i could only use it for "cgi" O_O. Thankyou 2010/2/28 Alan Gauld > > "Giorgio" wrote > > It's talking from fileitem attributes like filename and file. >> >> >> Where is the complete list of those attributes or methods? >> > > Probably on a web page somewhere but you are probably better using the > help() function and dir() to examine an instance from the >>> prompt. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- -- AnotherNetFellow Email: anothernetfellow at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Feb 28 16:38:58 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 01 Mar 2010 02:38:58 +1100 Subject: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files. In-Reply-To: References: <4B8A5921.5000008@free.fr> Message-ID: On 03/01/10 01:12, Alan Gauld wrote: > >> def getLines(file): >> """Get the content of a file in a lines list form.""" >> f = open(file, 'r') >> lines = f.readlines() >> f.close() >> return lines > > I'm not sure these functions add enough value to ghave them. I';d > probably just use > > try: open(outfile,'w').writelines(lines) > except IOError: #handle error > > try: lines = open(filename).readlines() > except IOError: #handle error > > The close will be done automatically since you don't hold a reference to > the file Remember why we have the new with-block? It's precisely because files will be automagically closed only if we're running on CPython; Python the language and thus alternative implementations doesn't guarantee automatic closing. I'd agree with the function having minimal utility value though: with open(file) as f: lines = f.readlines() # f.close() will be called by the context manager and if you're just copying to another file: from contextlib import nested with nested(open(infile), open(outfile, 'w')) as (fin, fout): fout.write(fin.read()) or even better, as Alan suggested, using shutil.copyfile(). From karim.liateni at free.fr Sun Feb 28 16:40:56 2010 From: karim.liateni at free.fr (Karim Liateni) Date: Sun, 28 Feb 2010 16:40:56 +0100 Subject: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files. In-Reply-To: References: <4B8A5921.5000008@free.fr> Message-ID: <4B8A8E88.7050707@free.fr> Hello Alan, Alan Gauld wrote: > "Karim Liateni" wrote > >> It concatenates both parameters and include files with the same >> parameters definitions. That trigs errors during simulation and >> it complains about parameters double definition. > > I'd suggest you construct a dictionary based on the param names > You can check before you add ca param if one already exists. > Or alternatively make a Set of param names and check that > for existence before adding a new one. Yes if I made it with Awk I would definitely use dictionary. I was focused on list comprehension...First I wanted it to work even if the method is 'awkward'. Now I will improve it for efficiency. > >> def copy(infile, outfile): >> """Copy of the content of an input file to an outputfile.""" >> fout = open(outfile, 'w') >> fout.writelines(getLines(infile)) >> fout.close() > > Its probably easier tyo use shutil.copyfile(). Thank you I was certain the function already exist! But I did not know in which package. > >> def cat(lines, outfile): >> """Concat the content of a strings list to an outputfile.""" >> f = open(outfile, 'w') >> f.writelines(lines) >> f.close() > > >> def getLines(file): >> """Get the content of a file in a lines list form.""" >> f = open(file, 'r') >> lines = f.readlines() >> f.close() >> return lines > > I'm not sure these functions add enough value to have them. I';d > probably just use > > try: open(outfile,'w').writelines(lines) > except IOError: #handle error > > try: lines = open(filename).readlines() > except IOError: #handle error > > The close will be done automatically since you don't hold a reference > to the file > I don't like to repeat code. Is it ok to take your corrections and write something like (not exactly the final code but approaching: def cat(lines, outfile): """Concat the content of a strings list to an outputfile.""" try: open(outfile,'w').writelines(lines) except IOError: #handle error def getLines(file): """Get the content of a file in a lines list form.""" try: lines = open(filename).readlines() ; return lines except IOError: #handle error But In the first form I understand the close is not needed but in the second 'lines = open(filename).readlines()' I don't hold indirectly a reference to the file? Please, could you explain more this point? >> def isParamExist(file, pattern, parameters): >> """Check if a particular regex pattern parameter is existing in a >> parameters file.""" >> lines = getLines(file) >> paramExpressions = [ e for e in lines if pattern.search(e) ] >> matchParam = [ e for e in paramExpressions if >> pattern.search(e).group(1) in parameters ] >> if matchParam: >> return True >> else: >> return False > > return bool(matchParam) instead of the if/else One more times thanks! That was I have been searching for. > > >> I am pretty sure that it can be simplify by using a dictionnary with >> the full path file as the key >> and the string 'include' nominal line expression as the value to >> construct the final file with filtered include. > > I think dictionaries or Sets could improve things My next goal. > >> I don't like the part: >> if matchParam: >> return True >> else: >> return False > > See the note above. > > HTH, > Alan, I am your oblig?. Your remarks are very instructive. Regards Karim From karim.liateni at free.fr Sun Feb 28 16:49:11 2010 From: karim.liateni at free.fr (Karim Liateni) Date: Sun, 28 Feb 2010 16:49:11 +0100 Subject: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files. In-Reply-To: References: <4B8A5921.5000008@free.fr> Message-ID: <4B8A9077.3060303@free.fr> Lie Ryan wrote: > On 03/01/10 01:12, Alan Gauld wrote: > >>> def getLines(file): >>> """Get the content of a file in a lines list form.""" >>> f = open(file, 'r') >>> lines = f.readlines() >>> f.close() >>> return lines >>> >> I'm not sure these functions add enough value to ghave them. I';d >> probably just use >> >> try: open(outfile,'w').writelines(lines) >> except IOError: #handle error >> >> try: lines = open(filename).readlines() >> except IOError: #handle error >> >> The close will be done automatically since you don't hold a reference to >> the file >> > > Remember why we have the new with-block? It's precisely because files > will be automagically closed only if we're running on CPython; Python > the language and thus alternative implementations doesn't guarantee > automatic closing. I'd agree with the function having minimal utility > value though: > > with open(file) as f: > lines = f.readlines() > # f.close() will be called by the context manager > > and if you're just copying to another file: > > from contextlib import nested > with nested(open(infile), open(outfile, 'w')) as (fin, fout): > fout.write(fin.read()) > > or even better, as Alan suggested, using shutil.copyfile(). > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Thank you Lie but I have a restriction on the python version I must use v2.2. This feature is available only on later version 2.5 I believe. Regards Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 28 16:53:56 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 28 Feb 2010 15:53:56 +0000 (GMT) Subject: [Tutor] CGI File Uploads In-Reply-To: <23ce85921002280628h12c3e333o240af2edd68624be@mail.gmail.com> References: <23ce85921002280256h1af97a3ey8417a0979bdd6ae5@mail.gmail.com> <23ce85921002280628h12c3e333o240af2edd68624be@mail.gmail.com> Message-ID: <851503.78274.qm@web86706.mail.ird.yahoo.com> > Alan, i don't know how to use it in this case. > > import cgi > form = cgi.FieldStorage() > fileitem = form['file'] > Function dir() lists all functions in a module, i could only use it for "cgi" It will list all the names in any kind of object not just a module. If you type the code above at the >>> prompt you should be able to do: >>> import cgi >>> form = cgi.FieldStorage() >>> help(form) OR, You could go more directly using >>> import cgi >>> help(cgi.FieldStorage) HTH Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Feb 28 17:07:44 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 01 Mar 2010 03:07:44 +1100 Subject: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files. In-Reply-To: <4B8A9077.3060303@free.fr> References: <4B8A5921.5000008@free.fr> <4B8A9077.3060303@free.fr> Message-ID: On 03/01/10 02:49, Karim Liateni wrote: > Lie Ryan wrote: >> On 03/01/10 01:12, Alan Gauld wrote: >> >>>> def getLines(file): >>>> """Get the content of a file in a lines list form.""" >>>> f = open(file, 'r') >>>> lines = f.readlines() >>>> f.close() >>>> return lines >>>> >>> I'm not sure these functions add enough value to ghave them. I';d >>> probably just use >>> >>> try: open(outfile,'w').writelines(lines) >>> except IOError: #handle error >>> >>> try: lines = open(filename).readlines() >>> except IOError: #handle error >>> >>> The close will be done automatically since you don't hold a reference to >>> the file >>> >> >> Remember why we have the new with-block? It's precisely because files >> will be automagically closed only if we're running on CPython; Python >> the language and thus alternative implementations doesn't guarantee >> automatic closing. I'd agree with the function having minimal utility >> value though: >> >> with open(file) as f: >> lines = f.readlines() >> # f.close() will be called by the context manager >> >> and if you're just copying to another file: >> >> from contextlib import nested >> with nested(open(infile), open(outfile, 'w')) as (fin, fout): >> fout.write(fin.read()) >> >> or even better, as Alan suggested, using shutil.copyfile(). >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > Thank you Lie but I have a restriction on the python version I must use > v2.2. > This feature is available only on later version 2.5 I believe. Then you should at the least use the try-finally block, I think that one has been there since 2.2? If you didn't use try-finally, there is no guarantee that f.close() would be called if an exception happened in the middle of reading/writing (e.g. KeyboardInterrupt, or perhaps user plugging off the thumbdrive, or bit more realistic having a full harddisk or exceeded some disk quota) From karim.liateni at free.fr Sun Feb 28 17:38:09 2010 From: karim.liateni at free.fr (Karim Liateni) Date: Sun, 28 Feb 2010 17:38:09 +0100 Subject: [Tutor] Any Tutor there ? Removing redundant parameters in a models file having include files. In-Reply-To: References: <4B8A5921.5000008@free.fr> <4B8A9077.3060303@free.fr> Message-ID: <4B8A9BF1.7040203@free.fr> Lie Ryan wrote: > On 03/01/10 02:49, Karim Liateni wrote: > >> Lie Ryan wrote: >> >>> On 03/01/10 01:12, Alan Gauld wrote: >>> >>> >>>>> def getLines(file): >>>>> """Get the content of a file in a lines list form.""" >>>>> f = open(file, 'r') >>>>> lines = f.readlines() >>>>> f.close() >>>>> return lines >>>>> >>>>> >>>> I'm not sure these functions add enough value to ghave them. I';d >>>> probably just use >>>> >>>> try: open(outfile,'w').writelines(lines) >>>> except IOError: #handle error >>>> >>>> try: lines = open(filename).readlines() >>>> except IOError: #handle error >>>> >>>> The close will be done automatically since you don't hold a reference to >>>> the file >>>> >>>> >>> Remember why we have the new with-block? It's precisely because files >>> will be automagically closed only if we're running on CPython; Python >>> the language and thus alternative implementations doesn't guarantee >>> automatic closing. I'd agree with the function having minimal utility >>> value though: >>> >>> with open(file) as f: >>> lines = f.readlines() >>> # f.close() will be called by the context manager >>> >>> and if you're just copying to another file: >>> >>> from contextlib import nested >>> with nested(open(infile), open(outfile, 'w')) as (fin, fout): >>> fout.write(fin.read()) >>> >>> or even better, as Alan suggested, using shutil.copyfile(). >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> Thank you Lie but I have a restriction on the python version I must use >> v2.2. >> This feature is available only on later version 2.5 I believe. >> > > Then you should at the least use the try-finally block, I think that one > has been there since 2.2? If you didn't use try-finally, there is no > guarantee that f.close() would be called if an exception happened in the > middle of reading/writing (e.g. KeyboardInterrupt, or perhaps user > plugging off the thumbdrive, or bit more realistic having a full > harddisk or exceeded some disk quota) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Thank you Lie. Yes, in fact I did it all the time during my years of Java development. In perl I used or open() or die( "msg" ) structure. I bypassed it because I wanted to construct the blocs very quickly like a 'beginner'. I was excited to make it work as fast as ossible to see if I can program something decent in Python. (gaining confidence? haaa human nature!). I definitely enjoy python (and not very far in spirit my loving Lisp). I definitely HATE tcl, java. Now I will improve quality and robustness. Thanks a lot! Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From computing.account at googlemail.com Sun Feb 28 20:39:10 2010 From: computing.account at googlemail.com (AG) Date: Sun, 28 Feb 2010 19:39:10 +0000 Subject: [Tutor] Over-riding radians as default for trig calculations Message-ID: <4B8AC65E.8080407@gmail.com> After importing the math module and running math.cos( x ) the result is in radians. Is there a way of setting this so that it results in degrees? I don't want to over-ride this permanently for my Python settings, so am happy to specifically do it per equation or per program. Thanks in advance. AG From hugo.yoshi at gmail.com Sun Feb 28 21:07:58 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 28 Feb 2010 21:07:58 +0100 Subject: [Tutor] Over-riding radians as default for trig calculations In-Reply-To: <4B8AC65E.8080407@gmail.com> References: <4B8AC65E.8080407@gmail.com> Message-ID: <29179d161002281207n46fe4c5ct500fb42793ffd6d2@mail.gmail.com> On Sun, Feb 28, 2010 at 8:39 PM, AG wrote: > After importing the math module and running > > math.cos( x ) > > the result is in radians. > > Is there a way of setting this so that it results in degrees? ?I don't want > to over-ride this permanently for my Python settings, so am happy to > specifically do it per equation or per program. > > Thanks in advance. > There is no setting to override, but you could easily define your own function to do a conversion for you. The wikipedia page on radians explains how to convert between the two, and writing a function to do that should be quite trivial. Hugo From steve at pearwood.info Sun Feb 28 23:47:32 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 1 Mar 2010 09:47:32 +1100 Subject: [Tutor] Over-riding radians as default for trig calculations In-Reply-To: <4B8AC65E.8080407@gmail.com> References: <4B8AC65E.8080407@gmail.com> Message-ID: <201003010947.32450.steve@pearwood.info> On Mon, 1 Mar 2010 06:39:10 am AG wrote: > After importing the math module and running > > math.cos( x ) > > the result is in radians. It certainly is not. The *result* of cos is a unitless number, not an angle. What you mean is that the *input* to cos, x, has to be supplied in radians. No, you can't change that anywhere, but you can do this: >>> math.cos(math.radians(45)) 0.70710678118654757 So of course you can write your own function: def cos(x): return math.cos(math.radians(x)) and call that. -- Steven D'Aprano