From alan.gauld at btinternet.com Fri Jan 1 07:05:47 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 1 Jan 2010 06:05:47 +0000 (GMT) Subject: [Tutor] printing xps or gif In-Reply-To: References: Message-ID: <809341.79004.qm@web86703.mail.ird.yahoo.com> > Well I have a folder with some sub folders that have a combo of xps and gif > files I want to be able to point the program to it and have it print the > contents of each sub folder. In that case I'd use os.walk to traverse the folders and find the files. I'd then use os.system() (or the subprocess module for more control) and call whatever program you would use to print the files from the command line. ghostscript may do it for the xps files, for example. HTH, Alan G. http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From eldonjr at hotmail.com Fri Jan 1 11:17:00 2010 From: eldonjr at hotmail.com (Eldon L Mello Jr) Date: Fri, 1 Jan 2010 08:17:00 -0200 Subject: [Tutor] 'Hello world' Message-ID: Hi there, I must say I'm quite embarrassed about my issue. Ok, I'm a 101% newbie in programming and all but I honestly didn't expect I would have problems in my very first step which was just to print 'hello world'. Despite some idiot little thing I might be overlooking I wonder if Python 3.1.1 was properly installed in my machine. I got a AMD Turion X2 64 processor and Win7 Pro-64 so I suppose the Python 3.1.1 AMD64 version I got was the best pick right? here it comes: Python 3.1.1 (r311:74483, Aug 17 2009, 16:45:59) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> print 'hello world!' SyntaxError: invalid syntax (, line 1) >>> print "hello world!" SyntaxError: invalid syntax (, line 1) >>> Thanks a million, Eldon. From andreengels at gmail.com Fri Jan 1 11:31:17 2010 From: andreengels at gmail.com (Andre Engels) Date: Fri, 1 Jan 2010 11:31:17 +0100 Subject: [Tutor] 'Hello world' In-Reply-To: References: Message-ID: <6faf39c91001010231v15fb5246s79e2a31b96df8f35@mail.gmail.com> On Fri, Jan 1, 2010 at 11:17 AM, Eldon L Mello Jr wrote: > Hi there, > > I must say I'm quite embarrassed about my issue. Ok, I'm a 101% newbie in > programming and all but I honestly didn't expect I would have problems in my > very first step which was just to print 'hello world'. > > Despite some idiot little thing I might be overlooking I wonder if Python > 3.1.1 was properly installed in my machine. I got a AMD Turion X2 64 > processor and Win7 Pro-64 so I suppose the Python 3.1.1 AMD64 version I got > was the best pick right? > > here it comes: > > Python 3.1.1 (r311:74483, Aug 17 2009, 16:45:59) [MSC v.1500 64 bit (AMD64)] > on win32 > Type "copyright", "credits" or "license()" for more information. >>>> >>>> print 'hello world!' > > SyntaxError: invalid syntax (, line 1) >>>> >>>> print "hello world!" > > SyntaxError: invalid syntax (, line 1) >>>> > > Thanks a million, This is something that has changed between Python 2 and Python 3. In Python 2 what you tried is perfectly valid, but in Python 3 print has become a function, so you have to write: print("hello world!") or print('hello world!') Happy New Year! -- Andr? Engels, andreengels at gmail.com From norman at khine.net Fri Jan 1 12:14:19 2010 From: norman at khine.net (Norman Khine) Date: Fri, 1 Jan 2010 12:14:19 +0100 Subject: [Tutor] using re to match text and extract info In-Reply-To: <4B3CEB27.2090805@ieee.org> References: <9c2c8ffb0912310549u102d7224v556cd818633db113@mail.gmail.com> <4B3CEB27.2090805@ieee.org> Message-ID: <9c2c8ffb1001010314t3cfe9f3cl4da8e773da7f85f7@mail.gmail.com> Thank you for the replies and Happy New Year! On Thu, Dec 31, 2009 at 7:19 PM, Dave Angel wrote: > Norman Khine wrote: >> >> hello, >> >> >>>>> >>>>> import re >>>>> line = "ALSACE 67000 Strasbourg 24 rue de la Division Leclerc 03 88 23 >>>>> 05 66 strasbourg at artisansdumonde.org" >>>>> m = re.search('[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}', line) >>>>> emailAddress .search(r"(\d+)", line) >>>>> phoneNumber = re.compile(r'(\d{2}) (\d{2}) (\d{2}) (\d{2}) (\d{2})') >>>>> phoneNumber.search(line) >>>>> >> >> but this jumbles the phone number and also includes the 67000. >> >> how can i split the 'line' into a list? >> >> thanks >> norman >> >> > > lst = line.split() ? ?will split the line strictly by whitespace. > > Before you can write code to parse a line, you have to know for sure the > syntax of that line. ?This particular one has 15 fields, delimited by > spaces. ?So you can parse it with str.split(), and use slices to get the > particular set of numbers representing the phone number. ?(elements 9-14) > > If the address portion might be a variable number of words, then you could > still use split and slice, but use negative slice parameters to get the > phone number relative to the end. (elements -6 to -2) > > If the email address might have a space within it, then you have to get > fancier. > > If the phone number might have more or less than 5 "words", you have to get > fancier. > > Without a spec, all the regular expressions in the world are just noise. > > DaveA > > -- %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From alan.gauld at btinternet.com Fri Jan 1 20:18:03 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 1 Jan 2010 19:18:03 -0000 Subject: [Tutor] 'Hello world' References: Message-ID: "Eldon L Mello Jr" wrote > programming and all but I honestly didn't expect I would have problems in > my very first step which was just to print 'hello world'. >>>> print "hello world!" > SyntaxError: invalid syntax (, line 1) Looks like you are using a v2 tutorial, you need to find a v3 one. There are several around, including my own - although it is not fully complete all the basic topics are there now. If you have experience in any other language the official one is probably the best. v3 of Python is a major rewrite and although largely backwardws compatible there are a number of new features that are not. One of the most important is print, but there are several others that will trip you up if you use a v2 tutorial. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lopoff at gmx.net Sat Jan 2 00:53:53 2010 From: lopoff at gmx.net (MK) Date: Sat, 02 Jan 2010 00:53:53 +0100 Subject: [Tutor] find() doesnt work as expected Message-ID: <1262390033.19454.9.camel@Lnx64> At first, happy new year to all of you. I am trying to write a little script which uses one file as input and looks if the string from this file are in target file. And if not prints out that line/string so that i know which strings must be added to complete the target file. The format of the target file is different as the source/string query file. I tried this but it gives nothing out: # ------------------------- rom optparse import OptionParser import os #import re # ------------------------------ def help_here(): print """ I need the input file and the file to check. Both files must exist. Try --help. """ exit() # ------------------------------ parser = OptionParser() parser.add_option("-i", "--input-file", type="string", dest="input_file", help="input file with querys to check") parser.add_option("-f", "--file-to-check", type="string", dest="file_to_check", help="file which will be checked with querys from input file") (options, args) = parser.parse_args() input_file=options.input_file file_to_check=options.file_to_check infi = open(input_file,"r") ftck = open(file_to_check,"r") ftck_datei=ftck.read() ftck.close() for a in infi: found = ftck_datei.find(a) if found==-1: print a infi.close() # ------------------------------ And here some source file/querys and an target file: #-------------------------------- Colorful Tabs Cookie Monster Download Statusbar DownThemAll FoxyProxy NoScript ScrapBook TrackMeNot Adblock Plus Tab Mix Plus gTranslate #---------------------------------- #--------------------------------- Firefox AddOns which are useful Colorful Tabs Cookie Monster Download Statusbar DownThemAll FoxyProxy NoScript ScrapBook TrackMeNot Adblock Plus Tab Mix Plus gTranslate UserAgentSwitcher Greasemonkey Greasefire DOM Inspector Firebug RefControl #------------------------------------ The thing is that the target file could be a XML file or something so that it looks if the query is in the line of the targetfile. Else i could use diff but my files are not the exact text but have strings in it which i want to query. Thank you. From bermanrl at cfl.rr.com Sat Jan 2 03:01:13 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Fri, 01 Jan 2010 21:01:13 -0500 Subject: [Tutor] Finding a repeating sequence of digits Message-ID: <1262397673.18289.15.camel@bermanrl-desktop> Hi, I am trying to build an algorithm or methodology which will let me tell if a decimal has a repeating sequence of digits and if it does have that attribute, what is the sequence of digits. For example, 1/3.0 = 0.333333333..By eyeballing we know it has a repeating sequence and we know that the sequence is .3333.....A little more complex is 1/7.0 = 0.142857142857 but still is equivalent. A harder example is 45/56.0 = 0.8035714285714286. Here we have a repeating sequence but it comes after the first three digits. What I am looking for are ideas and suggestions looking for patterns. I do know I should use a relatively large precision as repeating values may constitute a rather long sequence. I did see, on Google, a suggestion to use a precision of 1000. Thank you for any and all ideas and suggestions. Robert Berman From alan.gauld at btinternet.com Sat Jan 2 10:22:18 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Jan 2010 09:22:18 -0000 Subject: [Tutor] find() doesnt work as expected References: <1262390033.19454.9.camel@Lnx64> Message-ID: "MK" wrote > I tried this but it gives nothing out: Try putting some debug print statements in - for example print the option filenames to prove you got them ok, print progress markers like adfter opening the files Then print a message for each string found.. > for a in infi: > found = ftck_datei.find(a) One thing you probably need to do is strip() the newline character from the end of a. Otherwise you will be searching for strings ending in newline. But if that were the problem all the tests should fail and you should get a lot of output! > if found==-1: It is more readable if you put some spaces in! if found == -1: HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From denis.spir at free.fr Sat Jan 2 11:00:50 2010 From: denis.spir at free.fr (spir) Date: Sat, 2 Jan 2010 11:00:50 +0100 Subject: [Tutor] find() doesnt work as expected In-Reply-To: <1262390033.19454.9.camel@Lnx64> References: <1262390033.19454.9.camel@Lnx64> Message-ID: <20100102110050.6dfa67e5@o> MK dixit: > At first, happy new year to all of you. > > I am trying to write a little script which uses one file > as input and looks if the string from this file are in target file. And > if not prints out that line/string so that i know which strings must > be added to complete the target file. The format of the target file > is different as the source/string query file. > > I tried this but it gives nothing out: > > # ------------------------- > rom optparse import OptionParser > import os > #import re > > # ------------------------------ > > def help_here(): > print """ > I need the input file and the file to check. > Both files must exist. Try --help. > """ > exit() > > # ------------------------------ > parser = OptionParser() > parser.add_option("-i", "--input-file", type="string", > dest="input_file", > help="input file with querys to check") > parser.add_option("-f", "--file-to-check", type="string", > dest="file_to_check", > help="file which will be checked with querys from input file") > > (options, args) = parser.parse_args() > input_file=options.input_file > file_to_check=options.file_to_check > > infi = open(input_file,"r") > ftck = open(file_to_check,"r") > ftck_datei=ftck.read() > ftck.close() > > for a in infi: > found = ftck_datei.find(a) > if found==-1: > print a > > infi.close() [...] > The thing is that the target file could be a XML file or something so > that it looks if the query is in the line of the targetfile. > Else i could use diff but my files are not the exact text but have > strings in it which i want to query. > > Thank you. I don't know exactly why your version does not work. Just 3 side notes: 1. Your naming is IMO rather confusing. For instance, "input_file" is actually a _name_, not a object that represents a file. Calling "infi" a file that actually holds reference data while another file is your real input also makes your code hard to follow. 2. Your test data does hold any missing expression! 3. You don't need the find method to check a substring existence, if the actual position is not needed: use the 'in' operator instead. I first thought that you forgot / did not know that file.readline(s) (implicitely called by "for a in infi") keeps newlines. But your test case should work anyway. But a real case with XML data would probably not. Maybe your real test case is not the one you published? See http://docs.python.org/library/stdtypes.html#file-objects for details. Below a version that works with text input instead of files (added Test* expressions): expressions = reference.split('\n') for expression in expressions: # print (expression in input) # debug if expression not in input: print expression ==>: Test1 Test2 Test3 Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Sat Jan 2 11:22:09 2010 From: denis.spir at free.fr (spir) Date: Sat, 2 Jan 2010 11:22:09 +0100 Subject: [Tutor] Finding a repeating sequence of digits In-Reply-To: <1262397673.18289.15.camel@bermanrl-desktop> References: <1262397673.18289.15.camel@bermanrl-desktop> Message-ID: <20100102112209.2487a084@o> Robert Berman dixit: > Hi, > > I am trying to build an algorithm or methodology which will let me tell > if a decimal has a repeating sequence of digits and if it does have that > attribute, what is the sequence of digits. For example, 1/3.0 = > 0.333333333..By eyeballing we know it has a repeating sequence and we > know that the sequence is .3333.....A little more complex is 1/7.0 = > 0.142857142857 but still is equivalent. A harder example is 45/56.0 = > 0.8035714285714286. Here we have a repeating sequence but it comes after > the first three digits. > > What I am looking for are ideas and suggestions looking for patterns. I > do know I should use a relatively large precision as repeating values > may constitute a rather long sequence. I did see, on Google, a > suggestion to use a precision of 1000. > > Thank you for any and all ideas and suggestions. > > > Robert Berman Well, I'm not sure of what you want. An algorithm able to _guess_ whether a fraction like 1/3 is infinitely repetitive, or just to observe it? For the former, no clue. For the latter, here are some random thoughts. (0. I guess from your words you noted that this depends on the base: 1/3 reads 0.1 in base 3.) 1. You'll need to work on the _representation_ (string), actually only on the fractional part, not on the python numbers themselves. 2. Decimals allow adjusting precision. 3. You'll need at least 2 config parameters: one to limit the size of the repetitive scheme, one to limit the position at which this scheme may start. 4. From how many repetitions on do you consider a repetitive scheme is found? (eg 0.333 is enough?) 5. At first sight, I cannot find any other method as brute force: at each pos, try each sequence size. When a repetition is found, check it repetes further, up to the number you chose at point 4. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From anand.shashwat at gmail.com Sat Jan 2 11:33:48 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sat, 2 Jan 2010 16:03:48 +0530 Subject: [Tutor] Finding a repeating sequence of digits In-Reply-To: <20100102112209.2487a084@o> References: <1262397673.18289.15.camel@bermanrl-desktop> <20100102112209.2487a084@o> Message-ID: What you are searching for is sheer bruteforce however if I'm guessing it right then you are solving Project Euler and you are thinking in wrong direction. On Sat, Jan 2, 2010 at 3:52 PM, spir wrote: > Robert Berman dixit: > > > Hi, > > > > I am trying to build an algorithm or methodology which will let me tell > > if a decimal has a repeating sequence of digits and if it does have that > > attribute, what is the sequence of digits. For example, 1/3.0 = > > 0.333333333..By eyeballing we know it has a repeating sequence and we > > know that the sequence is .3333.....A little more complex is 1/7.0 = > > 0.142857142857 but still is equivalent. A harder example is 45/56.0 = > > 0.8035714285714286. Here we have a repeating sequence but it comes after > > the first three digits. > > > > What I am looking for are ideas and suggestions looking for patterns. I > > do know I should use a relatively large precision as repeating values > > may constitute a rather long sequence. I did see, on Google, a > > suggestion to use a precision of 1000. > > > > Thank you for any and all ideas and suggestions. > > > > > > Robert Berman > > Well, I'm not sure of what you want. An algorithm able to _guess_ whether a > fraction like 1/3 is infinitely repetitive, or just to observe it? For the > former, no clue. For the latter, here are some random thoughts. > > (0. I guess from your words you noted that this depends on the base: 1/3 > reads 0.1 in base 3.) > > 1. You'll need to work on the _representation_ (string), actually only on > the fractional part, not on the python numbers themselves. > 2. Decimals allow adjusting precision. > 3. You'll need at least 2 config parameters: one to limit the size of the > repetitive scheme, one to limit the position at which this scheme may start. > 4. From how many repetitions on do you consider a repetitive scheme is > found? (eg 0.333 is enough?) > 5. At first sight, I cannot find any other method as brute force: at each > pos, try each sequence size. When a repetition is found, check it repetes > further, up to the number you chose at point 4. > > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Sat Jan 2 12:57:41 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 2 Jan 2010 03:57:41 -0800 Subject: [Tutor] Finding a repeating sequence of digits In-Reply-To: References: <1262397673.18289.15.camel@bermanrl-desktop> <20100102112209.2487a084@o> Message-ID: On Sat, Jan 2, 2010 at 02:33, Shashwat Anand wrote: > > What you are searching for is sheer bruteforce however if I'm guessing it right then you are solving Project Euler and you are thinking in wrong direction. Well, going with brute force, I'm amazed at how long some strings of repeating digits can be. For example, for the fairly simple fraction, 21/94, here's the mantissa to 1199 places: "22340425531914893617021276595744680851063829787234042553191489361702127659574468085106382978723404255319148936170212765957446808510638297872340425531914893617021276595744680851063829787234042553191489361702127659574468085106382978723404255319148936170212765957446808510638297872340425531914893617021276595744680851063829787234042553191489361702127659574468085106382978723404255319148936170212765957446808510638297872340425531914893617021276595744680851063829787234042553191489361702127659574468085106382978723404255319148936170212765957446808510638297872340425531914893617021276595744680851063829787234042553191489361702127659574468085106382978723404255319148936170212765957446808510638297872340425531914893617021276595744680851063829787234042553191489361702127659574468085106382978723404255319148936170212765957446808510638297872340425531914893617021276595744680851063829787234042553191489361702127659574468085106382978723404255319148936170212765957446808510638297872340425531914893617021276595744680851063829787234042553191489361702127659574468085106382978723404255319148936170212765957446808510638297872340425531914893617021276595744680851063829787234042553191489361702127659574468085106382978723". If I've done it correctly, the repeating sequence is "234042553191489361702127659574468085106382978", which has 45 digits! Dick Moores From davea at ieee.org Sat Jan 2 13:54:57 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 02 Jan 2010 07:54:57 -0500 Subject: [Tutor] Finding a repeating sequence of digits In-Reply-To: <1262397673.18289.15.camel@bermanrl-desktop> References: <1262397673.18289.15.camel@bermanrl-desktop> Message-ID: <4B3F4221.7050708@ieee.org> Robert Berman wrote: > Hi, > > I am trying to build an algorithm or methodology which will let me tell > if a decimal has a repeating sequence of digits and if it does have that > attribute, what is the sequence of digits. For example, 1/3.0 = > 0.333333333..By eyeballing we know it has a repeating sequence and we > know that the sequence is .3333.....A little more complex is 1/7.0 = > 0.142857142857 but still is equivalent. A harder example is 45/56.0 = > 0.8035714285714286. Here we have a repeating sequence but it comes after > the first three digits. > > What I am looking for are ideas and suggestions looking for patterns. I > do know I should use a relatively large precision as repeating values > may constitute a rather long sequence. I did see, on Google, a > suggestion to use a precision of 1000. > > Thank you for any and all ideas and suggestions. > > > Robert Berman > > > Exactly what is your real goal? Are you explicitly starting with fractions, and want to know what the repeat cycle is when that fraction is expressed in base 10 ? (All rational numbers have repeating cycles, in any given base, but the cycle size can vary depending on the base) Or are you starting with decimal.Decimal values, and need to investigate their characteristics? Or are you really just trying to analyze strings, and looking for repeating patterns in them? If this is the case, you need to define how many repeats constitutes "proof" that you have a cycle. Suppose you have a precision of 1000, and after 995 digits, you discover the first five are appearing again? That's not necessarily a cycle. But what if you have 400 arbitrary digits, followed by two copies of 300 digits? Is that a cycle of 300, or just a coincidence? In any case, don't get trapped by the rounding at the end of the decimal value. Your example of 45/56.0 has the last digit rounded from 5 to 6, so it could fool a naive implementation. Finally, do you need better than brute force performance? Then we need to know what information you really can assume. Does the number #26 mean anything to you? DaveA From kent37 at tds.net Sat Jan 2 14:46:48 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Jan 2010 08:46:48 -0500 Subject: [Tutor] Finding a repeating sequence of digits In-Reply-To: <1262397673.18289.15.camel@bermanrl-desktop> References: <1262397673.18289.15.camel@bermanrl-desktop> Message-ID: <1c2a2c591001020546s3a842dd7x48ed730721764ccd@mail.gmail.com> On Fri, Jan 1, 2010 at 9:01 PM, Robert Berman wrote: > Hi, > > I am trying to build an algorithm or methodology which will let me tell > if a decimal has a repeating sequence of digits and if it does have that > attribute, what is the sequence of digits. For example, 1/3.0 = > 0.333333333..By eyeballing we know it has a repeating sequence and we > know that the sequence is .3333.....A little more complex is 1/7.0 = > 0.142857142857 but still is equivalent. A harder example is 45/56.0 = > 0.8035714285714286. Here we have a repeating sequence but it comes after > the first three digits. > > What I am looking for are ideas and suggestions looking for patterns. I > do know I should use a relatively large precision as repeating values > may constitute a rather long sequence. I did see, on Google, a > suggestion to use a precision of 1000. > > Thank you for any and all ideas and suggestions. I would write a program that emulates long division "by hand". At each step of the division you get a remainder; if the remainder is 0, you are done. If the remainder is one you have seen before, but not 0, the fraction has started to repeat. The remainder must always be smaller than the denominator of the original fraction so by the pigeonhole principle the result must either terminate or repeat with length no longer than the value of the denominator (plus a fudge for initial conditions). Kent From eike.welk at gmx.net Sat Jan 2 16:09:05 2010 From: eike.welk at gmx.net (Eike Welk) Date: Sat, 02 Jan 2010 16:09:05 +0100 Subject: [Tutor] Finding a repeating sequence of digits In-Reply-To: <1262397673.18289.15.camel@bermanrl-desktop> References: <1262397673.18289.15.camel@bermanrl-desktop> Message-ID: <201001021609.07123.eike.welk@gmx.net> Hello Robert! On Saturday 02 January 2010, Robert Berman wrote: > Hi, > > I am trying to build an algorithm or methodology which will let me > tell if a decimal has a repeating sequence of digits If you are starting from fractions, I think you have to find the prime factors of the denominator. If the denominator contains other prime factors than 2 and 5, the fractional part has an infinite number of digits. I can't prove it, but here is an illustration: The fractional part of a decimal number always has the following form: x/10, x/100, x/1000, ... If you express them as prime factors it looks like this: x/(2*5), x/(2*5 * 2*5), x/(2*5 * 2*5 * 2*5), ... If you have for example: 1/30 = 1/(2*3*5) There is no way to remove the prime factor 3 from the denominator. Therefore 1/30 can't be expressed with decimal numbers, it can only be approximated. > and if it does > have that attribute, what is the sequence of digits. For example, > 1/3.0 = 0.333333333..By eyeballing we know it has a repeating > sequence and we know that the sequence is .3333.....A little more > complex is 1/7.0 = 0.142857142857 but still is equivalent. A harder > example is 45/56.0 = 0.8035714285714286. Here we have a repeating > sequence but it comes after the first three digits. I believe you have to generate the sequences for all prime factors and go from there: 45/56 = 45 / (2*2*2*7) = 45/8 * 1/7 = 5.625 * 1/7 However I have no mathematical background, so I can't be very helpful here. Eike. From lie.1296 at gmail.com Sat Jan 2 16:10:03 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 03 Jan 2010 02:10:03 +1100 Subject: [Tutor] Finding a repeating sequence of digits In-Reply-To: <1262397673.18289.15.camel@bermanrl-desktop> References: <1262397673.18289.15.camel@bermanrl-desktop> Message-ID: On 1/2/2010 1:01 PM, Robert Berman wrote: > Hi, > > I am trying to build an algorithm or methodology which will let me tell > if a decimal has a repeating sequence of digits and if it does have that > attribute, what is the sequence of digits. For example, 1/3.0 = > 0.333333333..By eyeballing we know it has a repeating sequence and we > know that the sequence is .3333.....A little more complex is 1/7.0 = > 0.142857142857 but still is equivalent. A harder example is 45/56.0 = > 0.8035714285714286. Here we have a repeating sequence but it comes after > the first three digits. > > What I am looking for are ideas and suggestions looking for patterns. I > do know I should use a relatively large precision as repeating values > may constitute a rather long sequence. I did see, on Google, a > suggestion to use a precision of 1000. > > Thank you for any and all ideas and suggestions. Does this gives you any idea? 1 / 3 = 0 rem 1 10 / 3 = 3 rem 1 <- we've encountered '1' in "1 / 3 = 0 rem 1" ... sequence "3" repeats 1 / 7 = 0 rem 1 10 / 7 = 1 rem 3 30 / 7 = 4 rem 2 20 / 7 = 2 rem 6 60 / 7 = 8 rem 4 40 / 7 = 5 rem 5 50 / 7 = 7 rem 1 <- we've encountered '1' in "1 / 7 = 0 rem 1" ... sequence "142857" repeats 45 / 56 = 0 rem 45 450 / 56 = 8 rem 2 20 / 56 = 0 rem 20 200 / 56 = 3 rem 32 320 / 56 = 5 rem 40 400 / 56 = 7 rem 8 80 / 56 = 1 rem 24 240 / 56 = 4 rem 16 160 / 56 = 2 rem 48 480 / 56 = 8 rem 32 <- we've encountered '32' in "200 / 56 = 3 rem 32" ... sequence "571428" repeats From roadierich at googlemail.com Sat Jan 2 16:31:02 2010 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 2 Jan 2010 15:31:02 +0000 Subject: [Tutor] Finding a repeating sequence of digits In-Reply-To: <1262397673.18289.15.camel@bermanrl-desktop> References: <1262397673.18289.15.camel@bermanrl-desktop> Message-ID: 2010/1/2 Robert Berman : > Hi, > > I am trying to build an algorithm or methodology which will let me tell > if a decimal has a repeating sequence of digits and if it does have that > attribute, what is the sequence of digits. For example, 1/3.0 = > 0.333333333..By eyeballing we know it has a repeating sequence and we > know that the sequence is .3333.....A little more complex is 1/7.0 = > 0.142857142857 but still is equivalent. A harder example is 45/56.0 = > 0.8035714285714286. Here we have a repeating sequence but it comes after > the first three digits. > > What I am looking for are ideas and suggestions looking for patterns. I > do know I should use a relatively large precision as repeating values > may constitute a rather long sequence. I did see, on Google, a > suggestion to use a precision of 1000. > > Thank you for any and all ideas and suggestions. > > > Robert Berman > > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > When it comes to number theory, I always turn first of all to wikipedia. http://en.wikipedia.org/wiki/Repeating_decimal If that doesn't help, I usually turn to Wolfram: http://mathworld.wolfram.com/RepeatingDecimal.html Between the two, and the links therefrom, there's probably all the information you need. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From beachkid at insightbb.com Sat Jan 2 19:46:52 2010 From: beachkid at insightbb.com (Ken G.) Date: Sat, 02 Jan 2010 13:46:52 -0500 Subject: [Tutor] Printing data to a printer... Message-ID: <4B3F949C.9030706@insightbb.com> Wow, I looked and looked. I can print out my program listing but can not print the resulted data produced by the program. How do I print out on my USB printer the data output of my Python program I ran in my Ubuntu terminal via Geany IDE? I already wrote several programs using raw_input, files, sort, list, tuple and I like Python! Currently, I'm using Python 2.6. In Liberty Basic, the command was lprint. For example: print 2 + 2 # display in terminal lprint 2 + 2 # print result to printer TIA, Ken From roadierich at googlemail.com Sat Jan 2 21:19:16 2010 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 2 Jan 2010 20:19:16 +0000 Subject: [Tutor] Printing data to a printer... In-Reply-To: <4B3F949C.9030706@insightbb.com> References: <4B3F949C.9030706@insightbb.com> Message-ID: 2010/1/2 Ken G. : > Wow, I looked and looked. ?I can print out my program listing but can not > print the resulted data produced by the program. > > How do I print out on my USB printer the data output of my Python program I > ran in my Ubuntu terminal via Geany IDE? > I already wrote several programs using raw_input, files, sort, list, tuple > and I like Python! ?Currently, I'm using Python 2.6. ?In Liberty Basic, the > command was lprint. ?For example: > > ? print 2 + 2 ? ?# ? ?display in terminal > > ? lprint 2 + 2 ? ?# ? print result to printer > TIA, > > Ken > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > There doesn't appear to be anything builtin to make it easy - on Linux, at least. There are three options, as far as I can see. I don't have a printer, so can't test either. First is to pipe the output from the program to a command line printing program. This will mean that all of the data written to stdout is sent straight to the printer. This can only be done at the command line, and will look something like $ python your_program.py | lpr Using this method, you can still send output to the console using sys.stderr.write() This is the traditional unix method, but is only really appropriate for your own scripts. The second option is to open a pipe to a program such as lpr from within python, using the subprocess module: import subprocess lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE) lpr.stdin.write(data_to_print) The third option is to use a third party library. The current linux printing system is called CUPS, so you can try searching the cheeseshop (pypi.python.org) or google for python cups packages. The pypi gives one possibility: http://www.pykota.com/software/pkipplib There is a fourth option, which might not even work: opening the printer device as a file-like object (I don't recommend trying this without doing a lot of research first): lp = open("/dev/lp0", "w") lp.write(data_to_print) Of course, all of this is very much os specific. The first option will work in linux, osx and windows, but two and three will only work in linux and osx, however printing is considerably easier on windows, there is the win32print package that does (most of) the heavy lifting for you. To be honest, I'm not even sure if option four will work _at_all_. -- 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. From bermanrl at cfl.rr.com Sat Jan 2 21:58:46 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sat, 02 Jan 2010 15:58:46 -0500 Subject: [Tutor] Finding a repeating sequence of digits In-Reply-To: <1c2a2c591001020546s3a842dd7x48ed730721764ccd@mail.gmail.com> References: <1262397673.18289.15.camel@bermanrl-desktop> <1c2a2c591001020546s3a842dd7x48ed730721764ccd@mail.gmail.com> Message-ID: <1262465926.18289.55.camel@bermanrl-desktop> Thank to everyone who contributed to this thread. I did have the horrible feeling this would probably end up as either total brute force or brute force perhaps with a twist. It was in the hopes of finding a twist I requested comments and suggestions from people whose opinions and suggestions are almost always elucidating and extremely helpful. A number of people have suggested I am attempting a Euler problem. This problem is from the Rosecode series problem 8; http://javaist.com/rosecode/show.php?no=8 Again, thank you for all the suggestions and ideas. Robert Berman -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkid at insightbb.com Sat Jan 2 22:24:24 2010 From: beachkid at insightbb.com (Ken G.) Date: Sat, 02 Jan 2010 16:24:24 -0500 Subject: [Tutor] Printing data to a printer... In-Reply-To: References: <4B3F949C.9030706@insightbb.com> Message-ID: <4B3FB988.8060902@insightbb.com> Rich Lovely wrote: > 2010/1/2 Ken G. : > >> Wow, I looked and looked. I can print out my program listing but can not >> print the resulted data produced by the program. >> >> How do I print out on my USB printer the data output of my Python program I >> ran in my Ubuntu terminal via Geany IDE? >> I already wrote several programs using raw_input, files, sort, list, tuple >> and I like Python! Currently, I'm using Python 2.6. In Liberty Basic, the >> command was lprint. For example: >> >> print 2 + 2 # display in terminal >> >> lprint 2 + 2 # print result to printer >> TIA, >> >> Ken >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > There doesn't appear to be anything builtin to make it easy - on > Linux, at least. There are three options, as far as I can see. I > don't have a printer, so can't test either. > > First is to pipe the output from the program to a command line > printing program. This will mean that all of the data written to > stdout is sent straight to the printer. This can only be done at the > command line, and will look something like > $ python your_program.py | lpr > > Using this method, you can still send output to the console using > sys.stderr.write() > > This is the traditional unix method, but is only really appropriate > for your own scripts. > > The second option is to open a pipe to a program such as lpr from > within python, using the subprocess module: > > import subprocess > lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE) > lpr.stdin.write(data_to_print) > > The third option is to use a third party library. The current linux > printing system is called CUPS, so you can try searching the > cheeseshop (pypi.python.org) or google for python cups packages. The > pypi gives one possibility: http://www.pykota.com/software/pkipplib > > There is a fourth option, which might not even work: opening the > printer device as a file-like object (I don't recommend trying this > without doing a lot of research first): > > lp = open("/dev/lp0", "w") > lp.write(data_to_print) > > Of course, all of this is very much os specific. The first option > will work in linux, osx and windows, but two and three will only work > in linux and osx, however printing is considerably easier on windows, > there is the win32print package that does (most of) the heavy lifting > for you. To be honest, I'm not even sure if option four will work > _at_all_. > > I found a roundabout way of doing it. Using IDLE, I ran the program as it is in the new "untitled window", resulting in having the output in the Python Shell window. I use the Print command from that shell window. Thanks for your input. It is much appreciated and I am printing it out for reference. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 2 23:18:36 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Jan 2010 22:18:36 -0000 Subject: [Tutor] Printing data to a printer... References: <4B3F949C.9030706@insightbb.com> Message-ID: "Ken G." wrote > Wow, I looked and looked. I can print out my program listing but can > not print the resulted data produced by the program. Printing is always difficult in a modern OS because your program and Python cannot be sure of what kind of device it is going to print on. Unix traditionally did printing by creating a temporary file with markup - usually roff markup - and then sending that file through the text processor (eg [gtn]roff) and hence to the print spool for processing by lp or lpr. You can still do that although nowadays I tend to use HTML as the formatting language and print via a browser. For simple text output you can of course bypass the formatting step and just send it straight to lpr, possibly via fmt. > In Liberty Basic, the command was lprint. In the days of standard BASIC the printer was almost certainly an Epson compatible ASCII printer which made it pretty easier for the interpreter to send output directly. Those days are long gone :-( Its the same with input - there is no direct equivalent to inkey$, although curses comes close, because again we now have a huge variety of input devices. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Sun Jan 3 06:58:18 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 3 Jan 2010 11:28:18 +0530 Subject: [Tutor] extract meaningful data from garbage Message-ID: I need to extract some meaningful data from grabages. Here are four examples. I need to get date, company name and address from these. For date i used regex but I'm unable to find any definite pattern for address and company name the format is more or less : garbage id - date garbage company name garbage company address garbage How should I parse info if I'm not certain of any definite rules. This is my first time dealing with real-life data. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Sun Jan 3 07:00:27 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 3 Jan 2010 11:30:27 +0530 Subject: [Tutor] extract meaningful data from garbage In-Reply-To: References: Message-ID: here are the examples : http://codepad.org/wF8APZV3 sorry i missed it to post earlier On Sun, Jan 3, 2010 at 11:28 AM, Shashwat Anand wrote: > I need to extract some meaningful data from grabages. > Here are four examples. I need to get date, company name and address from > these. > For date i used regex but I'm unable to find any definite pattern for > address and company name > the format is more or less : > garbage > id - date > garbage > company name > garbage > company address > garbage > > How should I parse info if I'm not certain of any definite rules. This is > my first time dealing with real-life data. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 3 09:56:22 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Jan 2010 08:56:22 -0000 Subject: [Tutor] extract meaningful data from garbage References: Message-ID: "Shashwat Anand" wrote > here are the examples : http://codepad.org/wF8APZV3 > >> I need to extract some meaningful data from grabages. >> How should I parse info if I'm not certain of any definite rules. This is >> my first time dealing with real-life data. Unfortunarely to parse it you will need to define a set of rules. The company name seems to consistently follow a line like 1511261 - 08/12/2006 So that should be relatively easy to extract. However the address data seems much more random. Also you don't say how you want to trweat the alternative names/addresses (eg "trading as...") As a first attempt the address follows immediately after the company name except 1) when the next line begins with "trading as" or 2) the next line begins with "(" in which case the address follows the closing "(" Those two rules are sufficient for the 4 examples you posted. You may have other cases where they break down. The address seems to consistently stop on theline above MANUFACTURER...But again other data samples may show cases where that breaks down. You will need to create more rulesto cover those cases.Unfortunately the address data itself is not consistentwhich makes it difficult to define a rule to recognise it in its own right.HTH-- Alan GauldAuthor of the Learn to Program web sitehttp://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Jan 3 10:23:18 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 03 Jan 2010 20:23:18 +1100 Subject: [Tutor] extract meaningful data from garbage In-Reply-To: References: Message-ID: On 1/3/2010 4:58 PM, Shashwat Anand wrote: > I need to extract some meaningful data from grabages. > Here are four examples. I need to get date, company name and address > from these. > For date i used regex but I'm unable to find any definite pattern for > address and company name > the format is more or less : > garbage > id - date > garbage > company name > garbage > company address > garbage > > How should I parse info if I'm not certain of any definite rules. This > is my first time dealing with real-life data. Other than the "id - date"; it seems quite difficult to reliably extract the company names and addresses. Extracting the company names and addresses appears to be based on a best-effort basis. Tips: look for clue keywords; company names often ends with ltd/sdn/bhd/berhad; lines that starts with "address" often is followed by the actual addresses; etc. Tips: this is a good showcase for TDD; pick twenty-or-so cases and manually extract the information and write your program to match as much of these test cases as possible (while manually extracting you should be able to notice additional patterns that you can use later on while writing your program). From anand.shashwat at gmail.com Sun Jan 3 12:46:21 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 3 Jan 2010 17:16:21 +0530 Subject: [Tutor] extract meaningful data from garbage In-Reply-To: References: Message-ID: @Alan, @Lie thanks The approach which I am taking right now is taking some test-cases, and creating rules for them. Later on after expanding the cases there aroused some cases which didn't followed earlier pattern so I tweaked some rules so as to match all of them. The task is time-consuming but with every new test-sets exceptions are becoming less and less. (There are .2 million such pages) PS. The task is to create a trademark-database which stores ID, company name, date, address, and trademarks from the original set and later matches with the given trademarks to disqualify similar trademarks. On Sun, Jan 3, 2010 at 2:53 PM, Lie Ryan wrote: > On 1/3/2010 4:58 PM, Shashwat Anand wrote: > >> I need to extract some meaningful data from grabages. >> Here are four examples. I need to get date, company name and address >> from these. >> For date i used regex but I'm unable to find any definite pattern for >> address and company name >> the format is more or less : >> garbage >> id - date >> garbage >> company name >> garbage >> company address >> garbage >> >> How should I parse info if I'm not certain of any definite rules. This >> is my first time dealing with real-life data. >> > > Other than the "id - date"; it seems quite difficult to reliably extract > the company names and addresses. Extracting the company names and addresses > appears to be based on a best-effort basis. > > Tips: look for clue keywords; company names often ends with > ltd/sdn/bhd/berhad; lines that starts with "address" often is followed by > the actual addresses; etc. > > Tips: this is a good showcase for TDD; pick twenty-or-so cases and manually > extract the information and write your program to match as much of these > test cases as possible (while manually extracting you should be able to > notice additional patterns that you can use later on while writing your > program). > > _______________________________________________ > 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 Sun Jan 3 15:54:35 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Jan 2010 14:54:35 -0000 Subject: [Tutor] extract meaningful data from garbage References: Message-ID: "Shashwat Anand" wrote > as to match all of them. The task is time-consuming but with every new > test-sets exceptions are becoming less and less. (There are .2 million > such > pages) One final thing to try is to identify records where you *failed* to find a match and re write them into an error file. The error file can then be manually processed if need be. You might also be able to clean up the error file by not writing lines that you know to be non-useful. The resultant error file might then show up some further patterns that you can exploit. Its all about eliminating as much manual effort as possible and making the manual work that is left over as easy as possible. ie Accept that you won't ever get 100% success and aim to minimise the pain as much as possible. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From anand.shashwat at gmail.com Sun Jan 3 16:33:33 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 3 Jan 2010 21:03:33 +0530 Subject: [Tutor] extract meaningful data from garbage In-Reply-To: References: Message-ID: I am almost doing same thing i.e. to give the values left unparsed a certain name - 'NIL', and currently I'm redirecting output to a text file. Searching for 'NIL' tells me where my match failed, although writing it seperately to a different file dint occurred to me. And yes the job is to reduce as much manual work as possible, I got it now. Thanks for the help :) ~Shashwat On Sun, Jan 3, 2010 at 8:24 PM, Alan Gauld wrote: > "Shashwat Anand" wrote > > as to match all of them. The task is time-consuming but with every new >> test-sets exceptions are becoming less and less. (There are .2 million >> such >> pages) >> > > One final thing to try is to identify records where you *failed* to find > a match and re write them into an error file. The error file can then > be manually processed if need be. > > You might also be able to clean up the error file by not writing lines > that you know to be non-useful. The resultant error file might then > show up some further patterns that you can exploit. > > Its all about eliminating as much manual effort as possible and > making the manual work that is left over as easy as possible. > ie Accept that you won't ever get 100% success and aim to > minimise the pain as much as possible. > > > > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 3 17:02:54 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 3 Jan 2010 16:02:54 +0000 (GMT) Subject: [Tutor] extract meaningful data from garbage In-Reply-To: References: Message-ID: <503516.25499.qm@web86704.mail.ird.yahoo.com> The other advantage of an error file is that if your rules become very complex it's a lot faster to only apply them to the entries that didn't match the simpler rules. In other words instead of applying a complex set of rules to every one of 2 million entries you might only have to apply them to 200 thousand... much faster to process. You might well wind up with several processing runs before spitting out the final human readable error file for hand processing. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: Shashwat Anand To: Alan Gauld Cc: tutor at python.org Sent: Sunday, 3 January, 2010 15:33:33 Subject: Re: [Tutor] extract meaningful data from garbage I am almost doing same thing i.e. to give the values left unparsed a certain name - 'NIL', and currently I'm redirecting output to a text file. Searching for 'NIL' tells me where my match failed, although writing it seperately to a different file dint occurred to me. And yes the job is to reduce as much manual work as possible, I got it now. Thanks for the help :) ~Shashwat On Sun, Jan 3, 2010 at 8:24 PM, Alan Gauld wrote: "Shashwat Anand" wrote > > >>>as to match all of them. The task is time-consuming but with every new >>>>test-sets exceptions are becoming less and less. (There are .2 million such >>>>pages) >> > >One final thing to try is to identify records where you *failed* to find >>a match and re write them into an error file. The error file can then >>be manually processed if need be. > >>You might also be able to clean up the error file by not writing lines >>that you know to be non-useful. The resultant error file might then >>show up some further patterns that you can exploit. > >>Its all about eliminating as much manual effort as possible and >>making the manual work that is left over as easy as possible. >>ie Accept that you won't ever get 100% success and aim to >>minimise the pain as much as possible. > > > >>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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sun Jan 3 18:47:52 2010 From: denis.spir at free.fr (spir) Date: Sun, 3 Jan 2010 18:47:52 +0100 Subject: [Tutor] extract meaningful data from garbage In-Reply-To: References: Message-ID: <20100103184752.1c486738@o> Shashwat Anand dixit: > @Alan, @Lie thanks > The approach which I am taking right now is taking some test-cases, and > creating rules for them. Later on after expanding the cases there aroused > some cases which didn't followed earlier pattern so I tweaked some rules so > as to match all of them. The task is time-consuming but with every new > test-sets exceptions are becoming less and less. (There are .2 million such > pages) > > PS. The task is to create a trademark-database which stores ID, company > name, date, address, and trademarks from the original set and later matches > with the given trademarks to disqualify similar trademarks. Sometimes it is worthful to note patterns for not-to-be-kept parts of source (garbage). Esp. if you can find patterns for start/end of garbage parts. Eg if address end is hard, look whether it's easier to find a pattern for the start of the following garbage. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From zhuchunml at gmail.com Tue Jan 5 09:24:15 2010 From: zhuchunml at gmail.com (=?GB2312?B?1uy0vg==?=) Date: Tue, 5 Jan 2010 16:24:15 +0800 Subject: [Tutor] How to open the closed file again? Message-ID: Hi all, I put files in a list, just like this module: #! /usr/bin/python # -*- coding=utf-8 -*- fileList = [] def openFiles(): for i in range(0,2): fname = "file%s"%i f = open(fname,"a") fileList.append(f) def closeFiles(): for f in fileList: f.close() if __name__=="__main__": openFiles() print "fileList closeFiles() print fileList openFiles() print fileList I found that after closing files some closed files were left in the list: open files:[, ] close files:[, ] open files again:[, , , ] After I call openFiles() and closeFiles() many times, the list will become fatter and fatter, filled with valueless closed file object. How could I open the closed file? I can't find the way in python document. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 5 09:46:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Jan 2010 08:46:59 -0000 Subject: [Tutor] How to open the closed file again? References: Message-ID: "??" wrote > fileList = [] > > def openFiles(): > for i in range(0,2): > fname = "file%s"%i > f = open(fname,"a") > fileList.append(f) > > def closeFiles(): > for f in fileList: > f.close() > > if __name__=="__main__": > openFiles() > print "fileList > closeFiles() > print fileList > openFiles() > print fileList > > I found that after closing files some closed files were left in the > list: Yes, because you never remove them they will stay there. If you want to remove them from the list you need you del() them as part of your close method. > After I call openFiles() and closeFiles() many times, the list will > become fatter and fatter, filled with valueless closed file object. How > could I open the closed file? I can't find the way in python document. I don't know of a way to open a closed file object, you might want to store the filename along with the file. Then if you discover it is closed you can use the name to reopen it. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.plum at uni-koeln.de Tue Jan 5 11:34:52 2010 From: alan.plum at uni-koeln.de (Alan Plum) Date: Tue, 05 Jan 2010 11:34:52 +0100 Subject: [Tutor] How to open the closed file again? In-Reply-To: References: Message-ID: <1262687692.3696.5.camel@kallisti> On Di, 2010-01-05 at 16:24 +0800, ?? wrote: > I found that after closing files some closed files were left in the > list: Why don't you use a dictionary mapping filenames to open file objects instead? files = {'/path/to/file1': None, '/path/to/file2': None} def openFiles(): for f in files.keys(): if files[f] is not None: continue files[f] = open(f) def closeFiles(): for f in files.keys(): if files[f] is None: continue files[f].close() files[f] = None Although you'll probably want to refactor this into an object. Cheers, Alan Plum From davea at ieee.org Tue Jan 5 12:31:51 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 05 Jan 2010 06:31:51 -0500 Subject: [Tutor] How to open the closed file again? In-Reply-To: References: Message-ID: <4B432327.40005@ieee.org> Alan Gauld wrote: >
> "??" wrote > >> fileList = [] >> >> def openFiles(): >> for i in range(0,2): >> fname = "file%s"%i >> f = open(fname,"a") >> fileList.append(f) >> >> def closeFiles(): >> for f in fileList: >> f.close() >> >> if __name__=="__main__": >> openFiles() >> print "fileList >> closeFiles() >> print fileList >> openFiles() >> print fileList >> >> I found that after closing files some closed files were left in the >> list: > > Yes, because you never remove them they will stay there. > If you want to remove them from the list you need you del() them > as part of your close method. > >> After I call openFiles() and closeFiles() many times, the list will >> become fatter and fatter, filled with valueless closed file object. How >> could I open the closed file? I can't find the way in python document. > > I don't know of a way to open a closed file object, you might want > to store the filename along with the file. Then if you discover it is > closed you can use the name to reopen it. > You could probably just open it again, with: f = open(f.name, f.mode) This gives you a new object, which looks like the original one. Notice that you still have to remove the old object. But that happens automatically, if you bind the new object to the same name as the old, or to the same list location. So you could write a reopenfiles() function, like (untested): def reopenfiles(fileList): for i, f in enumerate(fileList): f = open(f.name, f.mode) fileList[i] = f DaveA From zhuchunml at gmail.com Tue Jan 5 13:46:15 2010 From: zhuchunml at gmail.com (=?GB2312?B?1uy0vg==?=) Date: Tue, 5 Jan 2010 20:46:15 +0800 Subject: [Tutor] How to open the closed file again? In-Reply-To: <4B432327.40005@ieee.org> References: <4B432327.40005@ieee.org> Message-ID: I've token a dictionary to save filenames, and write it into "constant.py". And I think it's a good method to create a class as Andre wrote. Thank you all! By the way, if I close a open file object, will the closed file object still occupy the memory ? As I saw in a list, this kind of unusable file object wasn't cleaned by GC. What will happen if there's no list? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 5 13:59:11 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 5 Jan 2010 07:59:11 -0500 Subject: [Tutor] How to open the closed file again? In-Reply-To: <1c2a2c591001050447h5d805de0l25628efa3c7ee3d6@mail.gmail.com> References: <1c2a2c591001050447h5d805de0l25628efa3c7ee3d6@mail.gmail.com> Message-ID: <1c2a2c591001050459v103e4f41i1627bfae2075f807@mail.gmail.com> > 2010/1/5 ?? : >> Hi all, >> ??? I put files in a list, just like this module: >> >> #! /usr/bin/python >> # -*- coding=utf-8 -*- >> >> >> fileList = [] >> >> def openFiles(): >> ??? for i in range(0,2): >> ??????? fname = "file%s"%i >> ??????? f = open(fname,"a") >> ??????? fileList.append(f) >> >> def closeFiles(): >> ??? for f in fileList: >> ??????? f.close() >> >> if __name__=="__main__": >> ??? openFiles() >> ??? print "fileList >> ??? closeFiles() >> ??? print fileList >> ??? openFiles() >> ??? print fileList > > As others have explained, the problem is that you keep adding new file > objects to fileList. I would make openFiles() return the list of files > that it opened and pass that as a parameter to closeFiles(): > > def openFiles(): > ? ?fileList = [] > ? ?for i in range(0,2): > ? ? ? ?fname = "file%s"%i > ? ? ? ?f = open(fname,"a") > ? ? ? ?fileList.append(f) > ? ?return fileList > > def closeFiles(fileList): > ? ?for f in fileList: > ? ? ? ?f.close() > > if __name__=="__main__": > ? ?fileList = openFiles() > ? ?print fileList > ? ?closeFiles(fileList) > ? ?print fileList > ? ?fileList = openFiles() > ? ?print fileList > > Kent > From andreengels at gmail.com Tue Jan 5 14:55:28 2010 From: andreengels at gmail.com (Andre Engels) Date: Tue, 5 Jan 2010 14:55:28 +0100 Subject: [Tutor] How to open the closed file again? In-Reply-To: References: <4B432327.40005@ieee.org> Message-ID: <6faf39c91001050555g37a1fa17s2dc1e0c38ac1fd6b@mail.gmail.com> On Tue, Jan 5, 2010 at 1:46 PM, ?? wrote: > I've token a dictionary to save filenames, and write it into "constant.py". > And I think it's a good method to create a class as Andre wrote.? Thank you > all! > By the way, if I close a open file object, will the closed file object still > occupy the memory ? As I saw in a list, this kind of unusable file object > wasn't cleaned by GC. What will happen if there's no list? In general, when an object is not referred any more in Python code, it will be garbage collected (and thus the memory it occupies will become free); however, this is not robust nor fully consistent over implementation, and it is therefore unadvisable to write code that relies too heavily on this. -- Andr? Engels, andreengels at gmail.com From davea at ieee.org Tue Jan 5 15:41:12 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 05 Jan 2010 09:41:12 -0500 Subject: [Tutor] How to open the closed file again? In-Reply-To: <6faf39c91001050555g37a1fa17s2dc1e0c38ac1fd6b@mail.gmail.com> References: <4B432327.40005@ieee.org> <6faf39c91001050555g37a1fa17s2dc1e0c38ac1fd6b@mail.gmail.com> Message-ID: <4B434F88.5020601@ieee.org> Andre Engels wrote: > On Tue, Jan 5, 2010 at 1:46 PM, ?? wrote: > >> I've token a dictionary to save filenames, and write it into "constant.py". >> And I think it's a good method to create a class as Andre wrote. Thank you >> all! >> By the way, if I close a open file object, will the closed file object still >> occupy the memory ? As I saw in a list, this kind of unusable file object >> wasn't cleaned by GC. What will happen if there's no list? >> > > In general, when an object is not referred any more in Python code, it > will be garbage collected (and thus the memory it occupies will become > free); however, this is not robust nor fully consistent over > implementation, and it is therefore unadvisable to write code that > relies too heavily on this. > > > If I believed that, clearly I would not use Python for anything real. I think you're confusing the issue of things like file objects automatically closing their resources when they go out of scope. That's not guaranteed to happen in any reasonable time. And you should use a context manager such as *with* or do explicit close in a try/finally situation. However, although garbage collection may be lazier in one implementation than another, if you attempt to program explicit del for all allocated objects, you might as well use C. Further, there are more invisible objects being created and destroyed than the ones you have control over. You have to trust the mechanism, whether it's ref counting or gc. Incidentally, del doesn't free the object. It just removes one reference to it. It still may be gc'ed now, or later, and of course not at all if there are other references to it. In other words, when an object holds a scarce resource, do some explicit boxing on it to assure the resource is released. If it's memory, ignore it. Back to ?? : Those objects still existed because they were referenced in the list. You could del them from the list, or replace them with different objects. Same is true for "scalar variables" (to borrow a term from other languages). If you say X = obj then the object will exist at least as long as X is unchanged. If you say X = otherobj or X = None (which is another singleton object) then the reference to the original object goes away. And sooner or later, it'll get gc'ed. If you say del X, then not only the reference goes away, but X is no longer in the namespace. DaveA From lie.1296 at gmail.com Tue Jan 5 16:10:21 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 06 Jan 2010 02:10:21 +1100 Subject: [Tutor] How to open the closed file again? In-Reply-To: References: <4B432327.40005@ieee.org> Message-ID: On 1/5/2010 11:46 PM, ?? wrote: > I've token a dictionary to save filenames, and write it into > "constant.py". And I think it's a good method to create a class as Andre > wrote. Thank you all! > By the way, if I close a open file object, will the closed file object > still occupy the memory? Any python object occupies a certain baseline amount of memory. > As I saw in a list, this kind of unusable file > object wasn't cleaned by GC. The file object wasn't cleaned by the GC since you're still holding a reference to the file object (inside your list or any other variables currently referencing to it). > What will happen if there's no list? Python makes a guarantee that object will never be GC-ed as long as there is more than one variable referencing the object[1]. If you want to make sure that an (file) object gets GC-ed you have to delete all references to it, that is, you have to remove the file object from the list and delete or reassign all variables currently referencing to the file object or make the variables out-of-scope. This kind of micro-management is generally discouraged in python[2]. [1] weak references does not count [2] it's better to make it so that you don't need to manually delete variables in the first place and rely on the refcount/GC to delete variables/object references automatically when they're out of scope From bgailer at gmail.com Tue Jan 5 16:57:45 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 05 Jan 2010 10:57:45 -0500 Subject: [Tutor] How to open the closed file again? In-Reply-To: References: Message-ID: <4B436179.9020706@gmail.com> It might help us help you if you tell us a bit more about what you want to accomplish. -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Tue Jan 5 17:52:40 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 5 Jan 2010 16:52:40 +0000 (GMT) Subject: [Tutor] How to open the closed file again? In-Reply-To: <4B432327.40005@ieee.org> References: <4B432327.40005@ieee.org> Message-ID: <722162.12136.qm@web86703.mail.ird.yahoo.com> > > I don't know of a way to open a closed file object, you might want > > to store the filename along with the file. Then if you discover it is > > closed you can use the name to reopen it. > >You could probably just open it again, with: > > f = open(f.name, f.mode) Ah, good point. I had forgotten that the file object had a name attribute so yes that should work. Although personally I'd probably go with the custom fileobject approach just for the improved readability. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From luhmann_br at yahoo.com Tue Jan 5 22:06:51 2010 From: luhmann_br at yahoo.com (Luhmann) Date: Tue, 5 Jan 2010 13:06:51 -0800 (PST) Subject: [Tutor] How to open the closed file again? In-Reply-To: <6faf39c91001050555g37a1fa17s2dc1e0c38ac1fd6b@mail.gmail.com> Message-ID: <793186.18036.qm@web30907.mail.mud.yahoo.com> When there are no more references to an open file object, will it close, or the file will just remain open, forever unreachable? D?couvrez les styles qui font sensation sur Yahoo! Qu?bec Avatars. http://cf.avatars.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 5 23:11:04 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 5 Jan 2010 17:11:04 -0500 Subject: [Tutor] How to open the closed file again? In-Reply-To: <793186.18036.qm@web30907.mail.mud.yahoo.com> References: <6faf39c91001050555g37a1fa17s2dc1e0c38ac1fd6b@mail.gmail.com> <793186.18036.qm@web30907.mail.mud.yahoo.com> Message-ID: <1c2a2c591001051411y6fd68b41q544ea5b2be809da6@mail.gmail.com> On Tue, Jan 5, 2010 at 4:06 PM, Luhmann wrote: > > When there are no more references to an open file object, will it close, or the file will just remain open, forever unreachable? When an open file object is garbage-collected it will be closed. In current versions of CPython GC happens when there are no more references to an object but other versions of Python (Jython, IronPython) have different behaviour. There is no guarantee that an object will ever be GDed. My recommendation: for production code, explicitly close files. A 'with' block is the easiest way to do this. For quick-and-dirty code running under CPython, don't worry about it. (Though I admit to being paranoid enough to always explicitly close a file that is open for writing.) Kent From alan.gauld at btinternet.com Wed Jan 6 01:11:20 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Jan 2010 00:11:20 -0000 Subject: [Tutor] How to open the closed file again? References: <6faf39c91001050555g37a1fa17s2dc1e0c38ac1fd6b@mail.gmail.com> <793186.18036.qm@web30907.mail.mud.yahoo.com> Message-ID: "Luhmann" wrote > When there are no more references to an open file object, > will it close, or the file will just remain open, forever unreachable? Even if Python didn't close the file it would effectively be closed when the process stopped running. The OS should see to that. (If it doesn't its not a very good OS! But there are a few bad OS out there...) So you shouldn't really ever wind up with a completely unreachable file due to it not being closed. Although it has happened to me in the past, I think most common OS should prevent that. Alan G. From michael.fourman at ed.ac.uk Wed Jan 6 12:40:39 2010 From: michael.fourman at ed.ac.uk (Michael Fourman) Date: Wed, 6 Jan 2010 03:40:39 -0800 (PST) Subject: [Tutor] Example of use of (?P) and (?P=name) in Python regular expressions? In-Reply-To: <401609.96855.qm@web38805.mail.mud.yahoo.com> References: <401609.96855.qm@web38805.mail.mud.yahoo.com> Message-ID: <27026833.post@talk.nabble.com> I've used (?P=name) recently in an implementation of the porter2 stemming algorithm from http://snowball.tartarus.org/algorithms/english/stemmer.html This includes the rule: ## if the word ends with a double remove the last letter (so hopp -> hop) where we ## Define a double as one of ## bb dd ff gg mm nn pp rr tt re.sub("^(?P.*?[aeiouy].*?(?P
[bdfgmnprt]?))(?P=dd)$", "\g", word) implements this rule. Best, Michael Michael Hannon-2 wrote: > > Greetings. While looking into the use of regular expressions in Python, I > saw that it's possible to name match groups using: > > (?P...) > > and then refer to them using: > > (?P=name) > > I was able to get this to work in the following, nonsensical, example: > > >>> x = 'Free Fri Fro From' > >>> y = re.sub(r'(?P\bFro\b)', r'Frodo (--matched from > \g)', x) > >>> y > 'Free Fri Frodo (--matched from Fro) From' > >>> > > But, as you can see, to refer to the match I used the "\g" notation (that > I found some place on the web). > > I wasn't able to find a way to use the "P=" syntax, and I wasn't able to > find any working examples of this syntax on the web. > > If you have a working example of the use of the "P=" syntax, will you > please send it to me? > > Thanks. > > -- Mike > _______________________________________________ > 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/Example-of-use-of-%28-P%3Cname%3E%29-and-%28-P%3Dname%29-in-Python-regular-expressions--tp26557967p27026833.html Sent from the Python - tutor mailing list archive at Nabble.com. From denis.spir at free.fr Wed Jan 6 15:54:14 2010 From: denis.spir at free.fr (spir) Date: Wed, 6 Jan 2010 15:54:14 +0100 Subject: [Tutor] list.insert() Message-ID: <20100106155414.53c39cfd@o> Hello, Just found something rather misleading with negative indices: s = [1,2,3,4,5,6,7,8,9] print s, s[-3], s[-4] # [1, 2, 3, 4, 5, 6, 7, 8, 9] 7 6 s.insert(-3, 0) print s, s[-3], s[-4] # [1, 2, 3, 4, 5, 6, 0, 7, 8, 9] 7 0 So, I did insert 0 at index -3, but s[-3] is still 7, & 0 is in fact at index -4. Well, this can be explained: insertion adds an index, there are now 10, so when counting backwards a given index does not point to the same position/item anymore than before insertion. Still, it's a bit disturbing. What do you think? (And: should insert behave so that 0 actually is at index -3, meaning insert it after 7?) (No issue with positive indices, indeed.) Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From waynejwerner at gmail.com Wed Jan 6 16:45:43 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 6 Jan 2010 09:45:43 -0600 Subject: [Tutor] list.insert() In-Reply-To: <20100106155414.53c39cfd@o> References: <20100106155414.53c39cfd@o> Message-ID: <333efb451001060745w5d38f4q3350ec3af057685e@mail.gmail.com> On Wed, Jan 6, 2010 at 8:54 AM, spir wrote: > Hello, > > Just found something rather misleading with negative indices: > > s = [1,2,3,4,5,6,7,8,9] > print s, s[-3], s[-4] # [1, 2, 3, 4, 5, 6, 7, 8, 9] 7 6 > s.insert(-3, 0) > print s, s[-3], s[-4] # [1, 2, 3, 4, 5, 6, 0, 7, 8, 9] 7 0 > > So, I did insert 0 at index -3, but s[-3] is still 7, & 0 is in fact at > index -4. Well, this can be explained: insertion adds an index, there are > now 10, so when counting backwards a given index does not point to the same > position/item anymore than before insertion. Still, it's a bit disturbing. > What do you think? > (And: should insert behave so that 0 actually is at index -3, meaning > insert it after 7?) > > (No issue with positive indices, indeed.) > I think it may just be an issue with misunderstanding what the insert does: >>> help(list.insert) insert(...) L.insert(index, object) -- insert object before index When you insert(-3, 0) you are inserting 0 before index -3. When it says "before" it has nothing to do with the direction of travel. And when you say there's no issue with positive indices, take a look at this case: In [6]: s = [1,2,3] In [7]: s[0] Out[7]: 1 In [8]: s.insert(0,0) In [9]: s[0] Out[9]: 0 (ignoring mathematical considerations about the sign of 0) You get a different value at the same position. It seems that your confusion lies with this statement: "insertion adds an index" which it doesn't - insertion adds an object to your list. It's a fundamental difference - the computer stores objects, and if we want to access that object we have to know where it's stored. In your first case, 7 and 6 are stored in the positions 3 and 4 from the end of the list. When you insert(-3, 0) you're shifting everything before -3 and putting 0 in the spot before (at least that's how I think of it. How python actually implements lists is probably different.). Does that make sense? (and if I've explained it incorrectly, feel free to correct me!) 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 alan.gauld at btinternet.com Wed Jan 6 20:25:17 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Jan 2010 19:25:17 -0000 Subject: [Tutor] list.insert() References: <20100106155414.53c39cfd@o> Message-ID: "spir" wrote > s = [1,2,3,4,5,6,7,8,9] > print s, s[-3], s[-4] # [1, 2, 3, 4, 5, 6, 7, 8, 9] 7 6 > s.insert(-3, 0) > print s, s[-3], s[-4] # [1, 2, 3, 4, 5, 6, 0, 7, 8, 9] 7 0 > > So, I did insert 0 at index -3, but s[-3] is still 7, & 0 is in fact at > index -4. Seems reasonable. insert() inserts before the referenced item so I would expect it to appear at -4. If it did otherwise you would get a different result depending on whether you used positive or negative indexing - which would be really wierd! > Well, this can be explained: insertion adds an index, It doesn't so much add an index - there are no such things as indexes per se they are just references into the list - as insert an item before the item referenced. As a consequence all subsequent items will inevitably acquire a new relative position so the index used to locate them will change. But the index is not a property opf the list item, it is simple a location indicator. > when counting backwards a given index does not point > to the same position/item anymore than before insertion. The same applies when using positive indexes: >>> L = [0,1,2,3,4,5,6] >>> L.insert(4,9) >>> L [0, 1, 2, 3, 9, 4, 5, 6] 4 is now at index 5 and 9 is at 4. But that is not because we asked the list to create an item with an index of 4, rather we asked it to insert an item before the item at position 4. That accidentally leaves it with an index of 4. It might seem like a philospohical point but it is the explanation that makes insert consistent for positive and negative indexes. And its how help() describes the action: >>> help(L.insert) Help on built-in function insert: insert(...) L.insert(index, object) -- insert object before index -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Wed Jan 6 20:29:25 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 6 Jan 2010 11:29:25 -0800 Subject: [Tutor] need help with 3.1's fraction module Message-ID: >>> from fractions import Fraction >>> Fraction('.83452345').limit_denominator(100) Fraction(81, 97) I'd like to know how to do that in a script, where numbers like .83452345 are the output of random.random(). >>> Fraction(random()).limit_denominator(100) Doesn't work, nor did I really expect it to: >>> Fraction(random()).limit_denominator(100) Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 3.2\src\debug\tserver\_sandbox.py", line 1, in # Used internally for debug sandbox under external interpreter File "C:\Python31\Lib\fractions.py", line 100, in __new__ raise TypeError("argument should be a string " builtins.TypeError: argument should be a string or a Rational instance >>> But what does work? Thanks, Dick Moores From bgailer at gmail.com Wed Jan 6 20:59:03 2010 From: bgailer at gmail.com (bob gailer) Date: Wed, 06 Jan 2010 14:59:03 -0500 Subject: [Tutor] need help with 3.1's fraction module In-Reply-To: References: Message-ID: <4B44EB87.9060801@gmail.com> Richard D. Moores wrote: >>>> from fractions import Fraction >>>> Fraction('.83452345').limit_denominator(100) >>>> > Fraction(81, 97) > > I'd like to know how to do that in a script, where numbers like > .83452345 are the output of random.random(). > >>>> Fraction(random()).limit_denominator(100) >>>> > > Doesn't work, nor did I really expect it to: > >>>> Fraction(random()).limit_denominator(100) >>>> > Traceback (most recent call last): > File "C:\Program Files (x86)\Wing IDE > 3.2\src\debug\tserver\_sandbox.py", line 1, in > # Used internally for debug sandbox under external interpreter > File "C:\Python31\Lib\fractions.py", line 100, in __new__ > raise TypeError("argument should be a string " > builtins.TypeError: argument should be a string or a Rational instance > > > But what does work? > Fraction(str(random())).limit_denominator(100) -- Bob Gailer Chapel Hill NC 919-636-4239 From rdmoores at gmail.com Wed Jan 6 23:41:54 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 6 Jan 2010 14:41:54 -0800 Subject: [Tutor] need help with 3.1's fraction module In-Reply-To: <4B44EB87.9060801@gmail.com> References: <4B44EB87.9060801@gmail.com> Message-ID: On Wed, Jan 6, 2010 at 11:59, bob gailer wrote: > Fraction(str(random())).limit_denominator(100) Thanks! So here's what I wanted to do, or its beginning: ====================== from fractions import Fraction from random import random r = random() print(r) f = str(Fraction(str(r)).limit_denominator(100)) print(f) n, d = f.split('/') num, denom = int(n), int(d) fraction = num/denom error = abs(r - fraction)/r print(error*100, "percent") ======================== Several outputs are 0.744931449894 73/98 0.00449581106515 percent and 0.139041980606 5/36 0.110104672465 percent and 0.577608333884 41/71 0.0248516413283 percent Dick From lisaniel27 at gmail.com Wed Jan 6 23:55:11 2010 From: lisaniel27 at gmail.com (lisaniel) Date: Wed, 6 Jan 2010 14:55:11 -0800 (PST) Subject: [Tutor] Tracking time In-Reply-To: <20070124223414.20530.qmail@web82509.mail.mud.yahoo.com> References: <20070124223414.20530.qmail@web82509.mail.mud.yahoo.com> Message-ID: <27026982.post@talk.nabble.com> are you going to track the time of the employees or to track the work flow of yours.. it will be quite easier if you specify your query a clear one. Michael Key wrote: > > I am trying to develop a project tracking program that would allow you to > track hours and minutes spent on several different projects and store he > data in a database for printing. Any help would be appreciated. > > Mike > > http://www.labortimetracker.com/ Online Timecard -- View this message in context: http://old.nabble.com/Tracking-time-tp8592772p27026982.html Sent from the Python - tutor mailing list archive at Nabble.com. From rdmoores at gmail.com Thu Jan 7 13:43:26 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 7 Jan 2010 04:43:26 -0800 Subject: [Tutor] question about for loops Message-ID: On p. 162 of "Programming In Python", 2nd ed., by Summerfield, the section entitled "for Loops" begins: ========================================= for expression in iterable: for_suite else: else_suite The expression is normally either a single variable or a sequence of variables, usually in the form of a tuple. If a tuple or list is used for the expression, each item is unpacked into the expression's items. ====================================== I thought I was quite familiar with for loops, but I don't understand how the expression can be a sequence of variables, nor what unpacking into the expression's items means. Could someone explain this, preferably with an example? Thanks, Dick Moores From galaxywatcher at gmail.com Thu Jan 7 14:15:46 2010 From: galaxywatcher at gmail.com (galaxywatcher at gmail.com) Date: Thu, 7 Jan 2010 20:15:46 +0700 Subject: [Tutor] Greetings Pythonistas Message-ID: This is my first post to the Python tutor list and I just wanted to introduce myself and give a little background on my skill level prior to asking for Python advice and programming tips. I am relatively new to Python, but I have been dabbling with unix shell scripting for at least 10 years. I can construct powerful one liners using awk, sed, cut, uniq, sort, grep, etc. I definitely know my way around the unix file system. I use vim with various plugins, and I feel like I am the eternal unix student, constantly evolving my skills, but never reaching mastery. I have worked my way slightly past the novice level with Perl, but I never felt that I made the breakthrough that I needed to feel proficient enough to do anything serious with it. Python feels different. I have the gut instinct that I can really develop my skill set to do great things with the language. By great, I mean, that I can take an idea, a big idea even, and efficiently transform that idea into a software reality. I really want to master this language. I am reading two books at the moment and working through the exercises: Dive into Python by Mark Pilgrim, and Python Programming - An Introduction to Computer Science by Zelle. I have ideas that I want to develop, I put the books down and start scripting, but I always seem to hit a wall based on my lack of knowledge, so I pick up the books again and continue reading. I often wish that I had a private tutor or a Python guru that I could just ask how to get past a certain wall. Perhaps this list has that person or people on it. With that said, I look forward to participating with the Python tutors here. Thanks Blake From eike.welk at gmx.net Thu Jan 7 14:39:55 2010 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 7 Jan 2010 14:39:55 +0100 Subject: [Tutor] question about for loops In-Reply-To: References: Message-ID: <201001071439.55665.eike.welk@gmx.net> Hello Richard! On Thursday January 7 2010 13:43:26 Richard D. Moores wrote: > On p. 162 of "Programming In Python", 2nd ed., by Summerfield, the > section entitled "for Loops" begins: > > ========================================= > for expression in iterable: > for_suite > else: > else_suite > > The expression is normally either a single variable or a sequence of > variables, usually in the form of a tuple. If a tuple or list is used > for the expression, each item is unpacked into the expression's items. > ====================================== > > I thought I was quite familiar with for loops, but I don't understand > how the expression can be a sequence of variables, nor what unpacking > into the expression's items means. Could someone explain this, > preferably with an example? Your book seems to be a bit sloppy with the terms it chooses for describing the syntax. Look at the official syntax description section 7.3: http://docs.python.org/reference/compound_stmts.html#the-for-statement After the for statement there is no expression, but something called target_list. This target_list normally contains unknown variables, which are illegal in expressions. The whole complicated wording refers to this case: >>> for a,b,c in ((1,2,3), (4,5,6), (10,20,30)): ... print a,b,c ... 1 2 3 4 5 6 10 20 30 Unpacking is the operation done in: a,b,b = (2,4,5) The "a,b,c" on the left side of the assignment operator is also a target list. See section 6.2: http://docs.python.org/reference/simple_stmts.html#assignment-statements Eike. From taserian at gmail.com Thu Jan 7 14:46:01 2010 From: taserian at gmail.com (taserian) Date: Thu, 7 Jan 2010 08:46:01 -0500 Subject: [Tutor] question about for loops In-Reply-To: References: Message-ID: <70dbc4d41001070546j697dc051jdbfe21ab187e8f5d@mail.gmail.com> On Thu, Jan 7, 2010 at 7:43 AM, Richard D. Moores wrote: > On p. 162 of "Programming In Python", 2nd ed., by Summerfield, the > section entitled "for Loops" begins: > > ========================================= > for expression in iterable: > for_suite > else: > else_suite > > The expression is normally either a single variable or a sequence of > variables, usually in the form of a tuple. If a tuple or list is used > for the expression, each item is unpacked into the expression's items. > ====================================== > > I thought I was quite familiar with for loops, but I don't understand > how the expression can be a sequence of variables, nor what unpacking > into the expression's items means. Could someone explain this, > preferably with an example? > > Thanks, > > Dick Moores > > As an example, think of a list of tuples, similar to the following: tuplelist = [ (1, "a"), (2, "b"), (3, "c") ] To process them and handle each tuples elements individually, you can have the for statement: for (a, b) in tuplelist: -------------- next part -------------- An HTML attachment was scrubbed... URL: From garry.bettle at gmail.com Thu Jan 7 14:51:36 2010 From: garry.bettle at gmail.com (Garry Bettle) Date: Thu, 7 Jan 2010 14:51:36 +0100 Subject: [Tutor] Help with a Dictionary Message-ID: Howdy all, I hope this message finds you all well. I have a list that I output in the following order: 2010-01-07 1103 Sund A7 450m 2010-01-07 1111 Sheff A7 500m 2010-01-07 1119 Sund A6 450m 2010-01-07 1128 Sheff A6 500m 2010-01-07 1134 Sund A5 450m 2010-01-07 1142 Sheff A7 500m 2010-01-07 1148 Sund A5 450m 2010-01-07 1157 Sheff A6 500m 2010-01-07 1204 Sund A4 450m 2010-01-07 1212 Sheff A5 500m 2010-01-07 1218 Sund A4 450m 2010-01-07 1227 Sheff A3 500m 2010-01-07 1232 Sund A4 450m 2010-01-07 1242 Sheff A4 500m 2010-01-07 1247 Sund A4 450m 2010-01-07 1258 Sheff A3 500m 2010-01-07 1304 Sund A3 450m 2010-01-07 1312 Sheff A4 500m 2010-01-07 1319 Sund HC 640m 2010-01-07 1327 Sheff A5 500m 2010-01-07 1333 Sund A3 450m 2010-01-07 1344 Sheff A3 500m 2010-01-07 1351 Sund A2 450m 2010-01-07 1403 Sheff A2 500m 2010-01-07 1408 Romfd A7 400m 2010-01-07 1418 Crayfd S8 540m 2010-01-07 1427 Romfd A6 400m 2010-01-07 1437 Crayfd H3 380m ... etc. The above are RaceDate + RaceTime + Fixture + RaceDetails, and are output in RaceTime order. What I'd like to do, is output a transposed-like summary of just the Fixture + RaceTime. i.e. Sund 1103 1119 1134 1148 1204 1218 1232 1247 1304 1319 1333 1351 Sheff 1111 1128 1142 1157 1212 1227 1242 1258 1312 1327 1344 1403 Romfd 1408 1427 ... Crayfd 1418 1437 ... Do I need to use a Dictionary? Many thanks! Cheers, Garry From rdmoores at gmail.com Thu Jan 7 15:25:27 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 7 Jan 2010 06:25:27 -0800 Subject: [Tutor] question about for loops In-Reply-To: <70dbc4d41001070546j697dc051jdbfe21ab187e8f5d@mail.gmail.com> References: <70dbc4d41001070546j697dc051jdbfe21ab187e8f5d@mail.gmail.com> Message-ID: Now I have a nice collection of examples, which to me are worth more than the sometimes inscrutable docs. My thanks to you three for taking the time to create the examples, and accompany them with understandable explanations. BTW I like Summerfield's book a lot, but he let me down on p.162. Dick Moores From transmogribenno at gmail.com Thu Jan 7 15:26:31 2010 From: transmogribenno at gmail.com (Benno Lang) Date: Thu, 7 Jan 2010 23:26:31 +0900 Subject: [Tutor] Help with a Dictionary In-Reply-To: References: Message-ID: <9b00d1a91001070626o2576157ekdedfa75358084f70@mail.gmail.com> On Thu, Jan 7, 2010 at 10:51 PM, Garry Bettle wrote: > I have a list that I output in the following order: > > 2010-01-07 1103 Sund A7 450m > 2010-01-07 1111 Sheff A7 500m > 2010-01-07 1119 Sund A6 450m > 2010-01-07 1128 Sheff A6 500m > 2010-01-07 1134 Sund A5 450m > 2010-01-07 1142 Sheff A7 500m > 2010-01-07 1148 Sund A5 450m > 2010-01-07 1157 Sheff A6 500m > 2010-01-07 1204 Sund A4 450m > 2010-01-07 1212 Sheff A5 500m > 2010-01-07 1218 Sund A4 450m > 2010-01-07 1227 Sheff A3 500m > 2010-01-07 1232 Sund A4 450m > 2010-01-07 1242 Sheff A4 500m > 2010-01-07 1247 Sund A4 450m > 2010-01-07 1258 Sheff A3 500m > 2010-01-07 1304 Sund A3 450m > 2010-01-07 1312 Sheff A4 500m > 2010-01-07 1319 Sund HC 640m > 2010-01-07 1327 Sheff A5 500m > 2010-01-07 1333 Sund A3 450m > 2010-01-07 1344 Sheff A3 500m > 2010-01-07 1351 Sund A2 450m > 2010-01-07 1403 Sheff A2 500m > 2010-01-07 1408 Romfd A7 400m > 2010-01-07 1418 Crayfd S8 540m > 2010-01-07 1427 Romfd A6 400m > 2010-01-07 1437 Crayfd H3 380m > ... etc. > > The above are RaceDate + RaceTime + Fixture + RaceDetails, and are > output in RaceTime order. > > What I'd like to do, is output a transposed-like summary of just the > Fixture + RaceTime. > > i.e. > > Sund ? 1103 1119 1134 1148 1204 1218 1232 1247 1304 1319 1333 1351 > Sheff ? 1111 1128 1142 1157 1212 1227 1242 1258 1312 1327 1344 1403 > Romfd 1408 1427 ... > Crayfd 1418 1437 ... > > Do I need to use a Dictionary? Not necessarily, but it would seem illogical not to do so. HTH, benno. From rdmoores at gmail.com Thu Jan 7 15:32:20 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 7 Jan 2010 06:32:20 -0800 Subject: [Tutor] question about for loops In-Reply-To: References: <1262869381.3029.7.camel@kallisti> Message-ID: On Thu, Jan 7, 2010 at 05:03, Alan Plum wrote: > Variable unpacking works like this: > > points = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)] > > for (x,y) in points: > ? ?print 'x: %d, y: %d' % (x, y) > > Without unpacking: > > for point in points: > ? ?print 'x: %d, y: %d' % (point[0], point[1]) # point is a tuple > > Similarly consider this expression: > > (a, b) = (50, 100) # a = 50, b = 100 > c = (a, b) # c[0] = a, c[1] = b > > It's a really useful language feature if you're ever dealing with tuples > that carry certain semantics (e.g. x, y and z coordinates in a point > tuple) but don't want to create a new type. > > > Hope that helps, Certainly does. Thank you. I did something like your 3rd example, in these lines from the script I posted yesterday in the thread about the fractions module. f = str(Fraction(str(r)).limit_denominator(100)) n, d = f.split('/') num, denom = int(n), int(d) fraction = num/denom Dick Moores From zstumgoren at gmail.com Thu Jan 7 16:34:29 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 7 Jan 2010 10:34:29 -0500 Subject: [Tutor] Greetings Pythonistas In-Reply-To: References: Message-ID: Welcome! You've come to the right place. > books at the moment and working through the exercises: Dive into Python by > Mark Pilgrim, and Python Programming - An Introduction to Computer Science > by Zelle. Those are both great books to start with, IMHO. You might want to also check out Beginning Python, which has a number project chapters at the end that go beyond the traditional toy examples. That might give you some ideas on how to develop a larger project. And of course, as recommended by others many times on this list, reading the source code for an open source project is a great way to learn. HTH and welcome to the list! Serdar From garry.bettle at gmail.com Thu Jan 7 17:12:32 2010 From: garry.bettle at gmail.com (Garry Bettle) Date: Thu, 7 Jan 2010 17:12:32 +0100 Subject: [Tutor] Help with a Dictionary Message-ID: On Thu, Jan 7, 2010 at 15:26, Garry Bettle wrote: > > Howdy all, > > I hope this message finds you all well. > > I have a list that I output in the following order: > > 2010-01-07 1103 Sund A7 450m > 2010-01-07 1111 Sheff A7 500m > 2010-01-07 1119 Sund A6 450m > 2010-01-07 1128 Sheff A6 500m > 2010-01-07 1134 Sund A5 450m > 2010-01-07 1142 Sheff A7 500m > 2010-01-07 1148 Sund A5 450m > 2010-01-07 1157 Sheff A6 500m > 2010-01-07 1204 Sund A4 450m > 2010-01-07 1212 Sheff A5 500m > 2010-01-07 1218 Sund A4 450m > 2010-01-07 1227 Sheff A3 500m > 2010-01-07 1232 Sund A4 450m > 2010-01-07 1242 Sheff A4 500m > 2010-01-07 1247 Sund A4 450m > 2010-01-07 1258 Sheff A3 500m > 2010-01-07 1304 Sund A3 450m > 2010-01-07 1312 Sheff A4 500m > 2010-01-07 1319 Sund HC 640m > 2010-01-07 1327 Sheff A5 500m > 2010-01-07 1333 Sund A3 450m > 2010-01-07 1344 Sheff A3 500m > 2010-01-07 1351 Sund A2 450m > 2010-01-07 1403 Sheff A2 500m > 2010-01-07 1408 Romfd A7 400m > 2010-01-07 1418 Crayfd S8 540m > 2010-01-07 1427 Romfd A6 400m > 2010-01-07 1437 Crayfd H3 380m > ... etc. > > The above are RaceDate + RaceTime + Fixture + RaceDetails, and are > output in RaceTime order. > > What I'd like to do, is output a transposed-like summary of just the > Fixture + RaceTime. > > i.e. > > Sund ? 1103 1119 1134 1148 1204 1218 1232 1247 1304 1319 1333 1351 > Sheff ? 1111 1128 1142 1157 1212 1227 1242 1258 1312 1327 1344 1403 > Romfd 1408 1427 ... > Crayfd 1418 1437 ... > > Do I need to use a Dictionary? > > Many thanks! > > Cheers, > > Garry This is what I've come up with. Sorry, python is something I touch on occasionally: must do more! As the races are output, I build a dictionary of key=FixtureName and value=RaceTimes: RaceTime = marketResp.market.displayTime.time() cRaceTime = RaceTime.strftime("%H%M") FixtureName = MarketSummary.marketName.strip() MarketName = marketResp.market.name if FixtureName not in FixtureList: FixtureList[FixtureName] = cRaceTime else: FixtureList[FixtureName]+= " " + cRaceTime And then, when I want the summary to be printed: for fixture in FixtureList: print fixture.ljust(6), FixtureList[fixture] It works, but have I done it the "python" way? Can't I unpack both the key and value from FixtureList? This doesn't work: for fixture, racetimes in FixtureList: print fixture, racetimes Traceback (most recent call last): File "", line 1, in for fixture, racetimes in FixtureList: ValueError: too many values to unpack Another thing I'd like to change is the ljust(). I believe it's depreciated later in 3.0+, so I should really find an alternative. Cheers, G. From lie.1296 at gmail.com Thu Jan 7 17:21:08 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 08 Jan 2010 03:21:08 +1100 Subject: [Tutor] Greetings Pythonistas In-Reply-To: References: Message-ID: On 1/8/2010 12:15 AM, galaxywatcher at gmail.com wrote: > This is my first post to the Python tutor list and I just wanted to > introduce myself and give a little background on my skill level prior to > asking for Python advice and programming tips. I am relatively new to > Python, but I have been dabbling with unix shell scripting for at least > 10 years. I can construct powerful one liners using awk, sed, cut, uniq, > sort, grep, etc. I definitely know my way around the unix file system. I > use vim with various plugins, and I feel like I am the eternal unix > student, constantly evolving my skills, but never reaching mastery. I > have worked my way slightly past the novice level with Perl, but I never > felt that I made the breakthrough that I needed to feel proficient > enough to do anything serious with it. > > Python feels different. I have the gut instinct that I can really > develop my skill set to do great things with the language. By great, I > mean, that I can take an idea, a big idea even, and efficiently > transform that idea into a software reality. I really want to master > this language. I am reading two books at the moment and working through > the exercises: Dive into Python by Mark Pilgrim, and Python Programming > - An Introduction to Computer Science by Zelle. I have ideas that I want > to develop, I put the books down and start scripting, but I always seem > to hit a wall based on my lack of knowledge, so I pick up the books > again and continue reading. I suggest you read the official tutorial: http://docs.python.org/tutorial/ Since you have prior experience, you should be able to finish the tutorial in a 2-3 days or less. Don't start having any fancy ideas at first, at least not until you finished chapter 9; where you will have been fully introduced to most of python's core features. Chapter 10 and 11 is an introduction for the most commonly used standard libraries; you could save a lot of time from having to reinvent the wheel just by reading the standard modules described there. Don't forget about the built-in help() and the REPL shell. > I often wish that I had a private tutor or a > Python guru that I could just ask how to get past a certain wall. > Perhaps this list has that person or people on it. With that said, I > look forward to participating with the Python tutors here. No, this list does not "have that person"; the list is "that person". Just write about the wall you've just stumbled upon. From alan.gauld at btinternet.com Thu Jan 7 17:38:13 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Jan 2010 16:38:13 -0000 Subject: [Tutor] Help with a Dictionary References: Message-ID: "Garry Bettle" wrote > What I'd like to do, is output a transposed-like summary of just the > Fixture + RaceTime. > Sund 1103 1119 1134 1148 1204 1218 1232 1247 1304 1319 1333 1351 > Sheff 1111 1128 1142 1157 1212 1227 1242 1258 1312 1327 1344 1403 > As the races are output, I build a dictionary of key=FixtureName and > value=RaceTimes: Good start although I'd probably have just built a list rather than building a long string. > if FixtureName not in FixtureList: > FixtureList[FixtureName] = cRaceTime > else: > FixtureList[FixtureName]+= " " + cRaceTime if FixtureName not in FixtureList: FixtureList[FixtureName] = [cRaceTime] else: FixtureList[FixtureName].append(cRaceTime) > And then, when I want the summary to be printed: > > for fixture in FixtureList: > print fixture.ljust(6), FixtureList[fixture] for fixture, fixtures in FixtureList:.iteritems() print "%s\t%s" % (fixture, " ".join(fixtures)) > It works, but have I done it the "python" way? > Can't I unpack both the key and value from FixtureList? iteritems() as above. > Another thing I'd like to change is the ljust(). I believe it's > depreciated later in 3.0+, so I should really find an alternative. Using a format string you can control justification and total space, however I just added a tab character. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From grflanagan at gmail.com Thu Jan 7 17:41:44 2010 From: grflanagan at gmail.com (Gerard Flanagan) Date: Thu, 07 Jan 2010 16:41:44 +0000 Subject: [Tutor] Help with a Dictionary In-Reply-To: References: Message-ID: Garry Bettle wrote: > Howdy all, > > I hope this message finds you all well. > > I have a list that I output in the following order: > > 2010-01-07 1103 Sund A7 450m > 2010-01-07 1111 Sheff A7 500m > 2010-01-07 1119 Sund A6 450m > 2010-01-07 1128 Sheff A6 500m > 2010-01-07 1134 Sund A5 450m > 2010-01-07 1142 Sheff A7 500m > 2010-01-07 1148 Sund A5 450m > 2010-01-07 1157 Sheff A6 500m > 2010-01-07 1204 Sund A4 450m > 2010-01-07 1212 Sheff A5 500m > 2010-01-07 1218 Sund A4 450m > 2010-01-07 1227 Sheff A3 500m > 2010-01-07 1232 Sund A4 450m > 2010-01-07 1242 Sheff A4 500m > 2010-01-07 1247 Sund A4 450m > 2010-01-07 1258 Sheff A3 500m > 2010-01-07 1304 Sund A3 450m > 2010-01-07 1312 Sheff A4 500m > 2010-01-07 1319 Sund HC 640m > 2010-01-07 1327 Sheff A5 500m > 2010-01-07 1333 Sund A3 450m > 2010-01-07 1344 Sheff A3 500m > 2010-01-07 1351 Sund A2 450m > 2010-01-07 1403 Sheff A2 500m > 2010-01-07 1408 Romfd A7 400m > 2010-01-07 1418 Crayfd S8 540m > 2010-01-07 1427 Romfd A6 400m > 2010-01-07 1437 Crayfd H3 380m > ... etc. > > The above are RaceDate + RaceTime + Fixture + RaceDetails, and are > output in RaceTime order. > > What I'd like to do, is output a transposed-like summary of just the > Fixture + RaceTime. > > i.e. > > Sund 1103 1119 1134 1148 1204 1218 1232 1247 1304 1319 1333 1351 > Sheff 1111 1128 1142 1157 1212 1227 1242 1258 1312 1327 1344 1403 > Romfd 1408 1427 ... > Crayfd 1418 1437 ... > A defaultdict may help. --------------------------------------------------- rawdata = """ 2010-01-07 1103 Sund A7 450m 2010-01-07 1111 Sheff A7 500m 2010-01-07 1119 Sund A6 450m 2010-01-07 1128 Sheff A6 500m 2010-01-07 1134 Sund A5 450m 2010-01-07 1142 Sheff A7 500m 2010-01-07 1148 Sund A5 450m 2010-01-07 1157 Sheff A6 500m 2010-01-07 1204 Sund A4 450m 2010-01-07 1212 Sheff A5 500m 2010-01-07 1218 Sund A4 450m 2010-01-07 1227 Sheff A3 500m 2010-01-07 1232 Sund A4 450m 2010-01-07 1242 Sheff A4 500m 2010-01-07 1247 Sund A4 450m 2010-01-07 1258 Sheff A3 500m 2010-01-07 1304 Sund A3 450m 2010-01-07 1312 Sheff A4 500m 2010-01-07 1319 Sund HC 640m 2010-01-07 1327 Sheff A5 500m 2010-01-07 1333 Sund A3 450m 2010-01-07 1344 Sheff A3 500m 2010-01-07 1351 Sund A2 450m 2010-01-07 1403 Sheff A2 500m 2010-01-07 1408 Romfd A7 400m 2010-01-07 1418 Crayfd S8 540m 2010-01-07 1427 Romfd A6 400m 2010-01-07 1437 Crayfd H3 380m """ from collections import defaultdict data = defaultdict(list) for line in rawdata.splitlines(): if line: parts = line.split() data[parts[2]].append(parts[1]) for item in data.iteritems(): print item ---------------------------------------------- If you have multiple dates, then itertools.groupby may be of use. G. From lie.1296 at gmail.com Thu Jan 7 18:09:24 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 08 Jan 2010 04:09:24 +1100 Subject: [Tutor] Help with a Dictionary In-Reply-To: References: Message-ID: On 1/8/2010 3:12 AM, Garry Bettle wrote: > This is what I've come up with. Sorry, python is something I touch on > occasionally: must do more! > > As the races are output, I build a dictionary of key=FixtureName and > value=RaceTimes: > > RaceTime = marketResp.market.displayTime.time() > cRaceTime = RaceTime.strftime("%H%M") > FixtureName = MarketSummary.marketName.strip() > MarketName = marketResp.market.name > if FixtureName not in FixtureList: > FixtureList[FixtureName] = cRaceTime > else: > FixtureList[FixtureName]+= " " + cRaceTime > > And then, when I want the summary to be printed: > > for fixture in FixtureList: > print fixture.ljust(6), FixtureList[fixture] > > It works, but have I done it the "python" way? In general, you should keep all data in object format and convert it to string just before printing it (except for data that is inherently a text). You can have FixtureList as a dict mapping FixtureName to a list of datetime objects. Tips: you may want to see defaultdict from the collections module. >>> import collections >>> from datetime import datetime >>> a = collections.defaultdict(list) >>> fmt = '%Y-%m-%d %H%M' >>> a['Sund'].append(datetime.strptime('2010-01-07 1103', fmt)) >>> a['Sheff'].append(datetime.strptime('2010-01-07 1111', fmt)) >>> a['Sund'].append(datetime.strptime('2010-01-07 1119', fmt)) >>> a defaultdict(, {'Sund': [datetime.datetime(2010, 1, 7, 11, 3), datetime.datetime(2010, 1, 7, 11, 19)], 'Sheff': [datetime.datetime(2010, 1, 7, 11, 11)]}) It's much more versatile than keeping the time as a string; though for quick and dirty scripts keeping everything as a string may not be so much of a problem > Can't I unpack both > the key and value from FixtureList? Assuming that FixtureList is a dict (why name it List?), you can use: #python 2.0 for fixture, ractimes in FixtureList.iteritems(): print fixture, racetimes #python 3.0 for fixture, ractimes in FixtureList.items(): print(fixture, racetimes) > Another thing I'd like to change is the ljust(). I believe it's > depreciated later in 3.0+, so I should really find an alternative. No it isn't. What is deprecated is the 'string' module, in favor of "string method". i.e. instead of: import string s = 'abc' t = string.ljust(s, 10) you should use s = 'abc' t = s.ljust(10) And the last tips: http://www.python.org/dev/peps/pep-0008/ From lowelltackett at yahoo.com Thu Jan 7 19:26:18 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Thu, 7 Jan 2010 10:26:18 -0800 (PST) Subject: [Tutor] manipulting CSV files Message-ID: <536293.90502.qm@web110102.mail.gq1.yahoo.com> Displayed below is an extract from a CSV file that displays some [land surveying] coordinates: 1001, 342821.71900, 679492.08300,????? 0.00000, 1002, 342838.55786, 679909.81375,????? 0.00000, 1003, 342965.61860, 679911.34762,????? 0.00000, 1004, 343012.82497, 680338.36624,????? 0.00000, 1005, 342783.08155, 680347.62727,????? 0.00000, 1006, 342623.01979, 679547.20429,????? 0.00000, I intend to use data such as this along with my Mandrake 10.1 OS and Python 2.5.1 to create some apps that will manipulate coordinate data as I wish.? Obviously, one of my first steps is to be able to discriminatingly access and use the available file data.? (As a reference point of knowledge....I am grasping this effort as a way to introduce myself to programming in general, and Python in particular.? Whatever I absorb/display/offer here will be for the first time ever, and each step will "push my envelop".) Had originally intended to unpack the data such as: pt_no, north, east, elev = ('blah, blah') until I ran across the csv module.? Had accomplished this: >> coord = csv.reader(open('true_coord')) >>> for line in coord: ....? print line .... [' 1001', ' 342821.71900', ' 679492.08300', '????? 0.00000', '?????????????? '] [' 1002', ' 342838.55786', ' 679909.81375', '????? 0.00000', '?????????????? '] [' 1003', ' 342965.61860', ' 679911.34762', '????? 0.00000', '?????????????? '] [' 1004', ' 343012.82497', ' 680338.36624', '????? 0.00000', '?????????????? '] [' 1005', ' 342783.08155', ' 680347.62727', '????? 0.00000', '?????????????? '] [' 1006', ' 342623.01979', ' 679547.20429', '????? 0.00000', '?????????????? '] >>> when I realized that the procedure had included leading white space.? Attempting to remedy that, I found the Python documentation (on line} and came across--'csv.Dialect.skipinitialspace' which I believe is the answer to my dilemma.? However, my effort to implement that detail, based on interpreting the skimpy examples in the documentation: >>> coord = csv.reader(open('true_coord'),csv.Dialect.skipinitialspace = True) got me roundly shot down with: ? File "", line 1 SyntaxError: keyword can't be an expression My seemingly endless stabs at attempting variations on that code line are going nowhere, so I lay my case before the "Council of Coders". >From the virtual desk of Lowell Tackett? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lowelltackett at yahoo.com Thu Jan 7 20:12:01 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Thu, 7 Jan 2010 11:12:01 -0800 (PST) Subject: [Tutor] formatting* Message-ID: <433782.60696.qm@web110113.mail.gq1.yahoo.com> *No, not in Python...in this Tutor format.? How do I include line breaks in text so the lines in the Tutor Archives wrap (as opposed to stretching halfway to Idaho)? >From the virtual desk of Lowell Tackett? -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Jan 7 22:30:39 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 07 Jan 2010 13:30:39 -0800 Subject: [Tutor] manipulting CSV files In-Reply-To: <536293.90502.qm@web110102.mail.gq1.yahoo.com> References: <536293.90502.qm@web110102.mail.gq1.yahoo.com> Message-ID: On 1/7/2010 10:26 AM Lowell Tackett said... I suspect using csv is overkill, but you'd need to be working with Dialects by first creating a Dialect, then applying the Dialect to your source data. I've not done that, and for your use case, I think I'd do something like: filedata = '''1001, 342821.71900, 679492.08300, 0.00000, 1002, 342838.55786, 679909.81375, 0.00000, 1003, 342965.61860, 679911.34762, 0.00000, 1004, 343012.82497, 680338.36624, 0.00000, 1005, 342783.08155, 680347.62727, 0.00000, 1006, 342623.01979, 679547.20429, 0.00000,'''.split('\n') for ii in filedata: print [ jj.strip() for jj in ii.split(',')[:4]] HTH, Emile > Displayed below is an extract from a CSV file that displays some [land > surveying] coordinates: > > 1001, 342821.71900, 679492.08300, 0.00000, > 1002, 342838.55786, 679909.81375, 0.00000, > 1003, 342965.61860, 679911.34762, 0.00000, > 1004, 343012.82497, 680338.36624, 0.00000, > 1005, 342783.08155, 680347.62727, 0.00000, > 1006, 342623.01979, 679547.20429, 0.00000, > > I intend to use data such as this along with my Mandrake 10.1 OS and > Python 2.5.1 to create some apps that will manipulate coordinate data as > I wish. Obviously, one of my first steps is to be able to > discriminatingly access and use the available file data. (As a reference > point of knowledge...I am grasping this effort as a way to introduce > myself to programming in general, and Python in particular. Whatever I > absorb/display/offer here will be for the first time ever, and each step > will "push my envelop".) > > Had originally intended to unpack the data such as: > > pt_no, north, east, elev = ('blah, blah') > > until I ran across the csv module. Had accomplished this: > > >> coord = csv.reader(open('true_coord')) > >>> for line in coord: > ... print line > ... > [' 1001', ' 342821.71900', ' 679492.08300', ' 0.00000', ' '] > [' 1002', ' 342838.55786', ' 679909.81375', ' 0.00000', ' '] > [' 1003', ' 342965..61860', ' 679911.34762', ' 0.00000', ' '] > [' 1004', ' 343012.82497', ' 680338.36624', ' 0.00000', ' '] > [' 1005', ' 342783.08155', ' 680347.62727', ' 0.00000', ' '] > [' 1006', ' 342623.01979', ' 679547.20429', ' 0.00000', ' '] > >>> > > when I realized that the procedure had included leading white space. > Attempting to remedy that, I found the Python documentation (on line} > and came across--'csv.Dialect.skipinitialspace' which I believe is the > answer to my dilemma. However, my effort to implement that detail, based > on interpreting the skimpy examples in the documentation: > > >>> coord = csv.reader(open('true_coord'),csv.Dialect.skipinitialspace > = True) > > got me roundly shot down with: > > File "", line 1 > SyntaxError: keyword can't be an expression > > My seemingly endless stabs at attempting variations on that code line > are going nowhere, so I lay my case before the "Council of Coders". > > > From the virtual desk of Lowell Tackett > > > > > _______________________________________________ > 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 Thu Jan 7 22:59:27 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Jan 2010 21:59:27 -0000 Subject: [Tutor] formatting* References: <433782.60696.qm@web110113.mail.gq1.yahoo.com> Message-ID: "Lowell Tackett" wrote > *No, not in Python...in this Tutor format. > How do I include line breaks in text so the lines in > the Tutor Archives wrap (as opposed to stretching halfway to Idaho)? How are you viewing the messages? I have never seen that problem. Are you using a web browser or a newsreader? Which OS, which site? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jan 7 23:07:42 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Jan 2010 22:07:42 -0000 Subject: [Tutor] manipulting CSV files References: <536293.90502.qm@web110102.mail.gq1.yahoo.com> Message-ID: "Lowell Tackett" wrote > until I ran across the csv module. Had accomplished this: > >>> coord = csv.reader(open('true_coord')) >>> for line in coord: .... print line .... [' 1001', ' 342821.71900', ' 679492.08300', ' 0.00000', ' '] [' 1002', ' 342838.55786', ' 679909.81375', ' 0.00000', ' '] > when I realized that the procedure had included leading white space. > ...came across--'csv.Dialect.skipinitialspace' which I believe > is the answer to my dilemma. However, my effort to implement > that detail, based on interpreting the skimpy examples in > the documentation: > >>> coord = csv.reader(open('true_coord'),csv.Dialect.skipinitialspace = >>> True) > File "", line 1 > SyntaxError: keyword can't be an expression Reading the module it looks like the dialect is an attribute of the reader so I would try something like: >>> coord = csv.reader(open('true_coord')) >>> coord.dialect.skipinitialspace = True >>> for line in coord..... But I've never used dialect so am guessing based on my reading of the docs. HTH, Alan G. From ps_python at yahoo.com Thu Jan 7 23:08:15 2010 From: ps_python at yahoo.com (kumar s) Date: Thu, 7 Jan 2010 14:08:15 -0800 (PST) Subject: [Tutor] (no subject) Message-ID: <290423.62804.qm@web112519.mail.gq1.yahoo.com> dear tutors: I have two files. I want to take coordiates of an row in fileA and find if they are in the range of coordinates in fileB. If they are, I want to be able to map else, pass. thanks kumar file a: name loc x y a 4 40811596 40811620 b 4 40811619 40811643 c 4 40811649 40811673 d 4 40811734 40811758 e 4 40811797 40811821 f 4 40811817 40811841 g 4 40811895 40811919 h 4 40811938 40811962 file b: zx zy z1 4 + 40810323 40812000 z2 4 + 40810323 40812000 z3 4 + 40810323 40812000 z4 4 + 40810323 40812000 z5 4 + 40810323 40812000 z6 4 + 40810323 40812000 z7 4 + 40810323 40812000 z8 4 + 40810323 40812000 I want to take coordiates x and y from each row in file a, and check if they are in range of zx and zy. If they are in range then I want to be able to write both matched rows in a tab delim single row. my code: f1 = open('fileA','r') f2 = open('fileB','r') da = f1.read().split('\n') dat = da[:-1] ba = f2.read().split('\n') bat = ba[:-1] for m in dat: col = m.split('\t') for j in bat: cols = j.split('\t') if col[1] == cols[1]: xc = int(cols[2]) yc = int(cols[3]) if int(col[2]) in xrange(xc,yc): if int(col[3]) in xrange(xc,yc): print m+'\t'+j output: a 4 40811596 40811620 z1 4 + 40810323 40812000 This code is too slow. Could you experts help me speed the script a lot faster. In each file I have over 50K rows and the script runs very slow. Please help. thanks Kumar From lowelltackett at yahoo.com Thu Jan 7 23:28:51 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Thu, 7 Jan 2010 14:28:51 -0800 (PST) Subject: [Tutor] formatting* In-Reply-To: Message-ID: <166676.20228.qm@web110110.mail.gq1.yahoo.com> I'm using Mandrake 10.1 [Linux] OS to view the internet thru Firefox.? In my mailbox, everything is fine--my stuff formats well (and when it comes back to me as Tutor 'mail' it also formats correctly). The problem is over at the Tutor Archives (mail.python.org/pipermail/tutor), i.e., the Tutor forum site.? That's where whatever I composed formats out with no line wrap, and a paragraph becomes a single line, stretching out however far it needs to.? In all the time I've been perusing the forum (before jumping in to participate) I have seen "occasionally" a contributor's offering will suffer the same fate.? Now my entries are doing so as well.? I don't know if everybody who goes to the forum site sees these format problems as I do (apparently not--from your response), but there they are on my screen. Hope I've answered your questions with some degree of understandability. >From the virtual desk of Lowell Tackett? --- On Thu, 1/7/10, Alan Gauld wrote: From: Alan Gauld Subject: Re: [Tutor] formatting* To: tutor at python.org Date: Thursday, January 7, 2010, 4:59 PM "Lowell Tackett" wrote > *No, not in Python...in this Tutor format. How do I include line breaks in text so the lines in the Tutor Archives wrap (as opposed to stretching halfway to Idaho)? How are you viewing the messages? I have never seen that problem. Are you using a web browser or a newsreader? Which OS, which site? -- 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 alan.gauld at btinternet.com Thu Jan 7 23:36:17 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 7 Jan 2010 22:36:17 +0000 (GMT) Subject: [Tutor] formatting* In-Reply-To: <166676.20228.qm@web110110.mail.gq1.yahoo.com> References: <166676.20228.qm@web110110.mail.gq1.yahoo.com> Message-ID: <953934.25790.qm@web86708.mail.ird.yahoo.com> > I'm using Mandrake 10.1 [Linux] OS to view the internet thru Firefox. > In my mailbox, everything is fine--my stuff formats well (and when it > comes back to me as Tutor 'mail' it also formats correctly). > > The problem is over at the Tutor Archives (mail.python.org/pipermail/tutor), > i.e., the Tutor forum site. That's where whatever I composed formats > out with no line wrap, and a paragraph becomes a single line, Yes I see that. I don't use that archive I normally use gmane... However that is probably down to whatever mail program you are using to post with. Is it a web client or a full blown thick client mail tool like Thunderbird? Whichever, it probably has an option to automatically wrap sent text and I suspect you have that turned off. A good value is usually around 70 or 80 chars. FWIW I have the opposite problem using gmail, it consistently wraps my text prematurely leaving my paragraphs badly formatted. And I can't find where to change the setting! HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 7 23:47:16 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Jan 2010 22:47:16 -0000 Subject: [Tutor] (no subject) References: <290423.62804.qm@web112519.mail.gq1.yahoo.com> Message-ID: "kumar s" wrote > f1 = open('fileA','r') > f2 = open('fileB','r') > da = f1.read().split('\n') > dat = da[:-1] > ba = f2.read().split('\n') > bat = ba[:-1] You could replace all that with dat = open('fileA.dat').readlines() bat = open('fileB').readlines() > for m in dat: > col = m.split('\t') > for j in bat: This means that for every line in dat you are reading every line in bat. For 2 50k line files that is 50K x 50K = 2500 million reads and splits Thats why its slow! If you have the data sorted you can process it much more effectively because you can keep a marker in bat to see where to start searching Thats one option. > cols = j.split('\t') > if col[1] == cols[1]: > xc = int(cols[2]) > yc = int(cols[3]) > if int(col[2]) in xrange(xc,yc): This is generating a list then checking your cvalue against each member, again thats slow. You could do a direct comparison with upper/lower boundaries: if xc < int(col[2]) < yc: That will be much faster. > if int(col[3]) in xrange(xc,yc): Same here. > This code is too slow. Could you experts help me speed the script a lot > faster. > In each file I have over 50K rows and the script runs very slow. If you have the two files sorted you only need to step through the values in bat until you reach invalid values, that should be faster still. You can never be 100% sure with these kinds of tasks but I'd expect it to be faster to sort both data sets and then compare than to do what you are doing. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Fri Jan 8 00:00:33 2010 From: bgailer at gmail.com (bob gailer) Date: Thu, 07 Jan 2010 18:00:33 -0500 Subject: [Tutor] (no subject) In-Reply-To: <290423.62804.qm@web112519.mail.gq1.yahoo.com> References: <290423.62804.qm@web112519.mail.gq1.yahoo.com> Message-ID: <4B466791.7050309@gmail.com> kumar s wrote: > dear tutors: > I have two files. I want to take coordiates of an row in fileA and find if they are in the range of coordinates in fileB. If they are, I want to be able to map else, pass. > thanks > kumar > > file a: > name loc x y > a 4 40811596 40811620 > b 4 40811619 40811643 > c 4 40811649 40811673 > d 4 40811734 40811758 > e 4 40811797 40811821 > f 4 40811817 40811841 > g 4 40811895 40811919 > h 4 40811938 40811962 > > > > file b: > > zx zy > z1 4 + 40810323 40812000 > z2 4 + 40810323 40812000 > z3 4 + 40810323 40812000 > z4 4 + 40810323 40812000 > z5 4 + 40810323 40812000 > z6 4 + 40810323 40812000 > z7 4 + 40810323 40812000 > z8 4 + 40810323 40812000 > > > > > I want to take coordiates x and y from each row in file a, and check if they are in range of zx and zy. If they are in range then I want to be able to write both matched rows in a tab delim single row. > > > my code: > > f1 = open('fileA','r') > f2 = open('fileB','r') > da = f1.read().split('\n') > dat = da[:-1] > ba = f2.read().split('\n') > bat = ba[:-1] > > > for m in dat: > col = m.split('\t') > for j in bat: > cols = j.split('\t') > if col[1] == cols[1]: > xc = int(cols[2]) > yc = int(cols[3]) > if int(col[2]) in xrange(xc,yc): > if int(col[3]) in xrange(xc,yc): > print m+'\t'+j > > output: > a 4 40811596 40811620 z1 4 + 40810323 40812000 > > > > This code is too slow. Could you experts help me speed the script a lot faster. > In each file I have over 50K rows and the script runs very slow. > Suggestions: Translate the values to integer outside the comparison loop. Test for >= lower value and <= upper value. xrange is overkill. Be aware of Python's shortcut: lower <= x <= upper. Use: for m in f1: ... for j in f2: -- Bob Gailer Chapel Hill NC 919-636-4239 From lowelltackett at yahoo.com Fri Jan 8 00:47:46 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Thu, 7 Jan 2010 15:47:46 -0800 (PST) Subject: [Tutor] formatting* In-Reply-To: <953934.25790.qm@web86708.mail.ird.yahoo.com> Message-ID: <721535.20681.qm@web110108.mail.gq1.yahoo.com> Well, not a lot of luck.? What I use is Yahoo mail (whatever that is---a "thick" client??), and thus far I can't find any tool bars that offer help. An odd aside, however--I went into the Tutor Archives forum and pulled up the Page Source (HTML formatting template) and lo and behold all my paragraphs were correctly formatted (i.e. page-wrapped just as they had been when they left my mail notepad) and displayed correctly--on the source page.? So,who knows...(?) >From the virtual desk of Lowell Tackett? --- On Thu, 1/7/10, ALAN GAULD wrote: From: ALAN GAULD Subject: Re: [Tutor] formatting* To: "Lowell Tackett" , tutor at python.org Date: Thursday, January 7, 2010, 5:36 PM > I'm using Mandrake 10.1 [Linux] OS to view the internet thru Firefox.? > In my mailbox, everything is fine--my stuff formats well (and when it > comes back to me as Tutor 'mail' it also formats correctly). > > The problem is over at the Tutor Archives (mail.python.org/pipermail/tutor), > i.e., the Tutor forum site.? That's where whatever I composed formats > out with no line wrap, and a paragraph becomes a single line, Yes I see that. I don't use that archive I normally use gmane... However that is probably down to whatever mail program you are using to post with. Is it a web client or a full blown thick client mail tool like Thunderbird? Whichever, it probably has an option to automatically wrap sent text and I suspect you have that turned off. A good value is usually around 70 or 80 chars. FWIW I have the opposite problem using gmail, it consistently wraps my text prematurely leaving my paragraphs badly formatted. And I can't find where to change the setting! HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jan 8 01:25:04 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Jan 2010 00:25:04 -0000 Subject: [Tutor] formatting* References: <953934.25790.qm@web86708.mail.ird.yahoo.com> <721535.20681.qm@web110108.mail.gq1.yahoo.com> Message-ID: "Lowell Tackett" wrote > Well, not a lot of luck. What I use is Yahoo mail (whatever that is---a > "thick" client??), > and thus far I can't find any tool bars that offer help. A thick client is an application that runs on your desktop with built in intelligence. A thin client is a GUI within a browser that has all the intelligence on a server - typically a web app. Yahoo is a thin client. As it happens I use it too. You should find at the end of the subject line on outgoing messages an option to switch to plain text. Select that and you should find your line breaks are recognised. (HTML does not recognise your line breaks and tries to leave formatting to the browser. The archive page obviously gets confused by this! But using HTML to a mailing list causes other problems too so its best to send as plain text) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lowelltackett at yahoo.com Fri Jan 8 02:30:31 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Thu, 7 Jan 2010 17:30:31 -0800 (PST) Subject: [Tutor] formatting* Message-ID: <346338.20406.qm@web110115.mail.gq1.yahoo.com> Well, Ok then, I have switched to plain text to transmit this response. I will follow it over to the archive forum to see how the difference works. In the meantime...this back-and-forth dialog has at least made me aware of gmane, a website I had not been aware of. Interesting place. I was over there, looking around, and trying to figure it out. Found some of this correspondence "set" there, pretty much in isolation. It's a quirky place that I'm trying to figure out. Only a few of the most current items seem to be available (unlike the Tutor Archive forum, where an entire month's submittals are all lined up and available for sequential reading). Does one need to "sign up" in someway or another to make the entire site available? Thanks for your help and input with all of this. >From the virtual desk of Lowell Tackett --- On Thu, 1/7/10, Alan Gauld wrote: From: Alan Gauld Subject: Re: [Tutor] formatting* To: tutor at python.org Date: Thursday, January 7, 2010, 7:25 PM "Lowell Tackett" wrote > Well, not a lot of luck. What I use is Yahoo mail (whatever that is---a "thick" client??), > and thus far I can't find any tool bars that offer help. A thick client is an application that runs on your desktop with built in intelligence. A thin client is a GUI within a browser that has all the intelligence on a server - typically a web app. Yahoo is a thin client. As it happens I use it too. You should find at the end of the subject line on outgoing messages an option to switch to plain text. Select that and you should find your line breaks are recognised. (HTML does not recognise your line breaks and tries to leave formatting to the browser. The archive page obviously gets confused by this! But using HTML to a mailing list causes other problems too so its best to send as plain text) 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 From galaxywatcher at gmail.com Fri Jan 8 08:24:47 2010 From: galaxywatcher at gmail.com (galaxywatcher at gmail.com) Date: Fri, 8 Jan 2010 14:24:47 +0700 Subject: [Tutor] Expanding a Python script to include a zcat and awk pre-process Message-ID: <5DFF81F3-A087-41F2-984B-914A08E2B2FC@gmail.com> I wrote a simple Python script to process a text file, but I had to run a shell one liner to get the text file primed for the script. I would much rather have the Python script handle the whole task without any pre-processing at all. I will show 1) a small sample of the text file, 2) my script, 3) the one liner that I want to fold into the script, and 4) the task at hand. 1) $ zcat textfile.txt.zip | head -5 134873600, 134873855, "32787 Protex Technologies, Inc." 135338240, 135338495, 40597 135338496, 135338751, 40993 201720832, 201721087, "12838 HFF Infrastructure & Operations" 202739456, 202739711, "1623 Beseau Regional de la Region Languedoc Roussillon" 2) $ cat getranges.py #!/usr/bin/env python import string highflag = flagcount = sum = sumtotal = 0 infile = open("textfile.txt", "r") # Find the range by subtracting column 1 from column 2 for line in infile: num1, num2 = string.split(line) sum = int(num2) - int(num1) if sum > 10000000: flag1 = " !!!!" flagcount += 1 if sum > highflag: highflag = sum else: flag1 = "" print str(num2) + " - " + str(num1) + " = " + str(sum) + flag1 sumtotal = sumtotal + sum print "Total ranges = ", sumtotal print "Total # of ranges over 10 million: ", flagcount print "Largest range: ", highflag 3) zcat textfile.txt.zip | awk -F"," '{print $1, $2}' > textfile.txt 4) In my first iteration, I used string.split(num1, ",") but I ran into trouble when I encountered commas within column 3, such as "32787 Protexic Technologies, Inc.". I don't know how to handle this exception. I also don't know how to uncompress the file in Python and pass it to the rest of the script. Hence I used my zcat | awk oneliner to get the job done. So how do I uncompress zip and gzipped files in Python, and how do I force split to only evaluate the first two columns? Better yet, can I tell split to not evaluate commas in the double quoted 3rd column? Regards, Blake From metolone+gmane at gmail.com Fri Jan 8 09:35:41 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 8 Jan 2010 00:35:41 -0800 Subject: [Tutor] Expanding a Python script to include a zcat and awkpre-process References: <5DFF81F3-A087-41F2-984B-914A08E2B2FC@gmail.com> Message-ID: wrote in message news:5DFF81F3-A087-41F2-984B-914A08E2B2FC at gmail.com... >I wrote a simple Python script to process a text file, but I had to run a >shell one liner to get the text file primed for the script. I would much >rather have the Python script handle the whole task without any >pre-processing at all. I will show 1) a small sample of the text file, 2) >my script, 3) the one liner that I want to fold into the script, and 4) >the task at hand. > > 1) $ zcat textfile.txt.zip | head -5 > 134873600, 134873855, "32787 Protex Technologies, Inc." > 135338240, 135338495, 40597 > 135338496, 135338751, 40993 > 201720832, 201721087, "12838 HFF Infrastructure & Operations" > 202739456, 202739711, "1623 Beseau Regional de la Region Languedoc > Roussillon" > > > 2) $ cat getranges.py > #!/usr/bin/env python > > import string > > highflag = flagcount = sum = sumtotal = 0 > infile = open("textfile.txt", "r") > # Find the range by subtracting column 1 from column 2 > for line in infile: > num1, num2 = string.split(line) > sum = int(num2) - int(num1) > if sum > 10000000: > flag1 = " !!!!" > flagcount += 1 > if sum > highflag: > highflag = sum > else: > flag1 = "" > print str(num2) + " - " + str(num1) + " = " + str(sum) + flag1 > sumtotal = sumtotal + sum > print "Total ranges = ", sumtotal > print "Total # of ranges over 10 million: ", flagcount > print "Largest range: ", highflag > > 3) zcat textfile.txt.zip | awk -F"," '{print $1, $2}' > textfile.txt > > 4) In my first iteration, I used string.split(num1, ",") but I ran into > trouble when I encountered commas within column 3, such as "32787 > Protexic Technologies, Inc.". I don't know how to handle this exception. > I also don't know how to uncompress the file in Python and pass it to the > rest of the script. Hence I used my zcat | awk oneliner to get the job > done. So how do I uncompress zip and gzipped files in Python, and how do > I force split to only evaluate the first two columns? Better yet, can I > tell split to not evaluate commas in the double quoted 3rd column? Check out the csv, zipfile, and gzip modules in the Python documentation. -Mark From denis.spir at free.fr Fri Jan 8 11:46:47 2010 From: denis.spir at free.fr (spir) Date: Fri, 8 Jan 2010 11:46:47 +0100 Subject: [Tutor] Greetings Pythonistas In-Reply-To: References: Message-ID: <20100108114647.66291baf@o> galaxywatcher at gmail.com dixit: > I often > wish that I had a private tutor or a Python guru that I could just ask > how to get past a certain wall. Perhaps this list has that person or > people on it. The list as a whole certainly _can_ be this, & more ;-) (depends on how _you_ deal with it) Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Fri Jan 8 11:57:10 2010 From: denis.spir at free.fr (spir) Date: Fri, 8 Jan 2010 11:57:10 +0100 Subject: [Tutor] Help with a Dictionary In-Reply-To: References: Message-ID: <20100108115710.6e6b5b15@o> Garry Bettle dixit: [...series of data with same format...] > 2010-01-07 1437 Crayfd H3 380m > ... etc. > > The above are RaceDate + RaceTime + Fixture + RaceDetails, and are > output in RaceTime order. > > What I'd like to do, is output a transposed-like summary of just the > Fixture + RaceTime. > > i.e. > > Sund 1103 1119 1134 1148 1204 1218 1232 1247 1304 1319 1333 1351 > Sheff 1111 1128 1142 1157 1212 1227 1242 1258 1312 1327 1344 1403 > Romfd 1408 1427 ... > Crayfd 1418 1437 ... > > Do I need to use a Dictionary? The main difference in that case is order keeping. If you don't mind about it, which seems highly probable in your case, then a dict with key=Fixture, value=[lits of RaceTime] does the job. Else, Fixture order makes sense, you can use a list of tuples of the form (Fixture, [lits of RaceTime]). For output, just " ".join() together RaceTime's when needed. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Fri Jan 8 12:04:45 2010 From: denis.spir at free.fr (spir) Date: Fri, 8 Jan 2010 12:04:45 +0100 Subject: [Tutor] Help with a Dictionary In-Reply-To: References: Message-ID: <20100108120445.475d462c@o> Garry Bettle dixit: > for fixture in FixtureList: > print fixture.ljust(6), FixtureList[fixture] ... > for fixture, racetimes in FixtureList: > print fixture, racetimes > > Traceback (most recent call last): > File "", line 1, in > for fixture, racetimes in FixtureList: > ValueError: too many values to unpack Because iterating on a dict actually iterates on its keys -- the way you it in previous axample. To get directly (key, value) tuples instead, use dict.items() instead: for (fixture, racetimes) in FixtureList.items(): print fixture, racetimes (parens are optional, I just use them for clarity) Note: FixtureTimes may be a better name for your dict (usually a dict name in the form of key_values does the job well, except when key is obvious/implicit). Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Fri Jan 8 13:27:49 2010 From: denis.spir at free.fr (spir) Date: Fri, 8 Jan 2010 13:27:49 +0100 Subject: [Tutor] formatting* In-Reply-To: <721535.20681.qm@web110108.mail.gq1.yahoo.com> References: <953934.25790.qm@web86708.mail.ird.yahoo.com> <721535.20681.qm@web110108.mail.gq1.yahoo.com> Message-ID: <20100108132749.4d62ed6b@o> Lowell Tackett dixit: > An odd aside, however--I went into the Tutor Archives forum and pulled up the Page Source (HTML formatting template) and lo and behold all my paragraphs were correctly formatted (i.e. page-wrapped just as they had been when they left my mail notepad) and displayed correctly--on the source page.? So,who knows...(?) Yo, that's because you're viewing the source as plain text, so your viewer (browser, probably) can consistently wrap lines, adapting to window width. But probably archives impose a kind of formatting that prevents such adaptation [imo, this is a flaw (like imposing an absolute text size), but it's an opinion]. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Fri Jan 8 13:59:43 2010 From: denis.spir at free.fr (spir) Date: Fri, 8 Jan 2010 13:59:43 +0100 Subject: [Tutor] Expanding a Python script to include a zcat and awk pre-process In-Reply-To: <5DFF81F3-A087-41F2-984B-914A08E2B2FC@gmail.com> References: <5DFF81F3-A087-41F2-984B-914A08E2B2FC@gmail.com> Message-ID: <20100108135943.0cef3f37@o> galaxywatcher at gmail.com dixit: > I wrote a simple Python script to process a text file, but I had to > run a shell one liner to get the text file primed for the script. I > would much rather have the Python script handle the whole task without > any pre-processing at all. I will show 1) a small sample of the text > file, 2) my script, 3) the one liner that I want to fold into the > script, and 4) the task at hand. > > 1) $ zcat textfile.txt.zip | head -5 > 134873600, 134873855, "32787 Protex Technologies, Inc." > 135338240, 135338495, 40597 > 135338496, 135338751, 40993 > 201720832, 201721087, "12838 HFF Infrastructure & Operations" > 202739456, 202739711, "1623 Beseau Regional de la Region Languedoc > Roussillon" > > > 2) $ cat getranges.py > #!/usr/bin/env python > > import string > > highflag = flagcount = sum = sumtotal = 0 > infile = open("textfile.txt", "r") > # Find the range by subtracting column 1 from column 2 > for line in infile: > num1, num2 = string.split(line) > sum = int(num2) - int(num1) > if sum > 10000000: > flag1 = " !!!!" > flagcount += 1 > if sum > highflag: > highflag = sum > else: > flag1 = "" > print str(num2) + " - " + str(num1) + " = " + str(sum) + flag1 > sumtotal = sumtotal + sum > print "Total ranges = ", sumtotal > print "Total # of ranges over 10 million: ", flagcount > print "Largest range: ", highflag > > 3) zcat textfile.txt.zip | awk -F"," '{print $1, $2}' > textfile.txt > > 4) In my first iteration, I used string.split(num1, ",") but I ran > into trouble when I encountered commas within column 3, such as "32787 > Protexic Technologies, Inc.". I don't know how to handle this > exception. I also don't know how to uncompress the file in Python and > pass it to the rest of the script. Hence I used my zcat | awk oneliner > to get the job done. So how do I uncompress zip and gzipped files in > Python, and how do I force split to only evaluate the first two > columns? Better yet, can I tell split to not evaluate commas in the > double quoted 3rd column? > > Regards, > Blake There are several possibilities: 1) The choice of ',' as separator for data that can contain commas is , hem, not very clever ;-) Can you change that, so as to solve the issue at its source? (eg: any text processor allows converting a table to plain text using whatever separator). CSV is not a panacea... 2) Preprocess data to replace commas _outside quotes_ by a better chosen sep, such as TAB (eg read data while keeping an "in_quotes" flag). 3) Use a more powerful text processing tool, such as regexes: data = '''\ 134873600, 134873855, "32787 Protex Technologies, Inc." 135338240, 135338495, 40597 135338496, 135338751, 40993 201720832, 201721087, "12838 HFF Infrastructure & Operations" 202739456, 202739711, "1623 Beseau Regional de la Region Languedoc Roussillon"''' import re pat = re.compile(r"""(\d+), (\d+), (\".+\"|\d+)""") for line in data.splitlines(): result = pat.match(line) print result.groups() ==> ('134873600', '134873855', '"32787 Protex Technologies, Inc."') ('135338240', '135338495', '40597') ('135338496', '135338751', '40993') ('201720832', '201721087', '"12838 HFF Infrastructure & Operations"') ('202739456', '202739711', '"1623 Beseau Regional de la Region Languedoc Roussillon"') Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From kent37 at tds.net Fri Jan 8 14:11:45 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Jan 2010 08:11:45 -0500 Subject: [Tutor] manipulting CSV files In-Reply-To: <536293.90502.qm@web110102.mail.gq1.yahoo.com> References: <536293.90502.qm@web110102.mail.gq1.yahoo.com> Message-ID: <1c2a2c591001080511y2febb2bcy24e6949719d3377f@mail.gmail.com> On Thu, Jan 7, 2010 at 1:26 PM, Lowell Tackett wrote: > I found the Python documentation (on line} and came across--'csv.Dialect.skipinitialspace' which I believe is the answer to my dilemma.? However, my effort to implement that detail, based on interpreting the skimpy examples in the documentation: > > >>> coord = csv.reader(open('true_coord'),csv.Dialect.skipinitialspace = True) > > got me roundly shot down with: > > ? File "", line 1 > SyntaxError: keyword can't be an expression Try coord = csv.reader(open('true_coord', 'b'), skipinitialspace = True) Or you could create a Dialect and pass it as a second argument to open(). Try dialect = csv.excel() # start with the default dialect dialect.skipinitialspace = True coord = csv.reader(open('true_coord', 'b'), dialect) Note you should open the file in binary mode. Kent From kent37 at tds.net Fri Jan 8 14:40:07 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Jan 2010 08:40:07 -0500 Subject: [Tutor] (no subject) In-Reply-To: <290423.62804.qm@web112519.mail.gq1.yahoo.com> References: <290423.62804.qm@web112519.mail.gq1.yahoo.com> Message-ID: <1c2a2c591001080540x63505a0cqf61d95cd786a95bc@mail.gmail.com> On Thu, Jan 7, 2010 at 5:08 PM, kumar s wrote: > I want to take coordiates x and y from each row in file a, and check if they are in range of zx and zy. If they are in range then I want to be able to write both matched rows in a tab delim single row. > > > my code: > > f1 = open('fileA','r') > f2 = open('fileB','r') > da = f1.read().split('\n') > dat = da[:-1] > ba = f2.read().split('\n') > bat = ba[:-1] > > > for m in dat: > ? ? ? ?col = m.split('\t') > ? ? ? ?for j in bat: > ? ? ? ? ? ? ? ?cols = j.split('\t') > ? ? ? ? ? ? ? ?if col[1] == cols[1]: > ? ? ? ? ? ? ? ? ? ? ? ?xc = int(cols[2]) > ? ? ? ? ? ? ? ? ? ? ? ?yc = int(cols[3]) > ? ? ? ? ? ? ? ? ? ? ? ?if int(col[2]) in xrange(xc,yc): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?if int(col[3]) in xrange(xc,yc): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?print m+'\t'+j > > output: > a ? ? ? 4 ? ? ? 40811596 ? ? ? ?40811620 ? ?z1 4 + ?40810323 ? ? 40812000 > > > > This code is too slow. Could you experts help me speed the script a lot faster. > In each file I have over 50K rows and the script runs very slow. As others have pointed out you are doing way too much work in your inner loob. You should at least preprocess bat so you aren't doing the split and conversion on each line each time through the loop. But the bigger problem is the nested loops themselves, the inner loop will run 2,500,000,000 times which is likely to take a while. To fix this you need to find a faster way to search bat. Interval trees are one way: http://en.wikipedia.org/wiki/Interval_tree http://hackmap.blogspot.com/2008/11/python-interval-tree.html Kent From kent37 at tds.net Fri Jan 8 15:20:47 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Jan 2010 09:20:47 -0500 Subject: [Tutor] Expanding a Python script to include a zcat and awk pre-process In-Reply-To: <5DFF81F3-A087-41F2-984B-914A08E2B2FC@gmail.com> References: <5DFF81F3-A087-41F2-984B-914A08E2B2FC@gmail.com> Message-ID: <1c2a2c591001080620wf6de5cdqf877c33072e26834@mail.gmail.com> On Fri, Jan 8, 2010 at 2:24 AM, wrote: > So how do I > uncompress zip and gzipped files in Python, zipfile and gzip > and how do I force split to only > evaluate the first two columns? Use the optional second argument to split(): line.split(',', 2) > Better yet, can I tell split to not evaluate > commas in the double quoted 3rd column? Use the csv module. Kent From lowelltackett at yahoo.com Fri Jan 8 15:54:59 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Fri, 8 Jan 2010 06:54:59 -0800 (PST) Subject: [Tutor] manipulting CSV files In-Reply-To: <1c2a2c591001080511y2febb2bcy24e6949719d3377f@mail.gmail.com> Message-ID: <360031.27920.qm@web110108.mail.gq1.yahoo.com> >From the virtual desk of Lowell Tackett --- On Fri, 1/8/10, Kent Johnson wrote: > From: Kent Johnson > Subject: Re: [Tutor] manipulting CSV files > To: "Lowell Tackett" > Cc: "tutor" > Date: Friday, January 8, 2010, 8:11 AM > On Thu, Jan 7, 2010 at 1:26 PM, > Lowell Tackett > wrote: > > I found the Python documentation (on line} and came > across--'csv.Dialect.skipinitialspace' > Try > coord = csv.reader(open('true_coord', 'b'), > skipinitialspace = True) > > Note you should open the file in binary mode. > > Kent > I'm guessing the 'b' in the above code line refers to your recommendation to enlist binary mode. Here's what Python thought of it: >>> coord = csv.reader(open('true_coord', 'b'), skipinitialspace = True) Traceback (most recent call last): File "", line 1, in ValueError: mode string must begin with one of 'r', 'w', 'a' or 'U', not 'b' So, I put an 'r' in front of 'b', and it worked fine. Now, perhaps you can you shed some light on this problem--I'm trying to do some simple arithmetic with two of the retrieved values, and get this error: >>> coord = csv.reader(open('true_coord', 'rb'), skipinitialspace = True) >>> for line in coord: .... if line[0] == '1001': .... print line .... ['1001', '342821.71900', '679492.08300', '0.00000', ''] .... print (int(line[1]) + int(line[2])) .... Traceback (most recent call last): File "", line 3, in ValueError: invalid literal for int() with base 10: '342821.71900' I tried: .... print (line[1]) + (line[2]) But of course it did nothing but cat the two sequences. From kent37 at tds.net Fri Jan 8 16:07:43 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Jan 2010 10:07:43 -0500 Subject: [Tutor] manipulting CSV files In-Reply-To: <360031.27920.qm@web110108.mail.gq1.yahoo.com> References: <1c2a2c591001080511y2febb2bcy24e6949719d3377f@mail.gmail.com> <360031.27920.qm@web110108.mail.gq1.yahoo.com> Message-ID: <1c2a2c591001080707m758790c9r73672e717c067421@mail.gmail.com> On Fri, Jan 8, 2010 at 9:54 AM, Lowell Tackett wrote: > Now, perhaps you can you shed some light on this problem--I'm trying to do some simple arithmetic with two of the retrieved values, and get this error: > >>>> coord = csv.reader(open('true_coord', 'rb'), skipinitialspace = True) >>>> for line in coord: > .... ?if line[0] == '1001': > .... ? print line > .... > ['1001', '342821.71900', '679492.08300', '0.00000', ''] > .... ? print (int(line[1]) + int(line[2])) > .... > Traceback (most recent call last): > ?File "", line 3, in > ValueError: invalid literal for int() with base 10: '342821.71900' Well, it's right - that is not a valid integer. What do you want to do with it? You could convert it to a number with float(line[2]) or get just the integer part with int(line[2].split('.')[0]). Kent From lowelltackett at yahoo.com Fri Jan 8 16:56:01 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Fri, 8 Jan 2010 07:56:01 -0800 (PST) Subject: [Tutor] manipulting CSV files In-Reply-To: <1c2a2c591001080707m758790c9r73672e717c067421@mail.gmail.com> Message-ID: <139149.41706.qm@web110115.mail.gq1.yahoo.com> >From the virtual desk of Lowell Tackett --- On Fri, 1/8/10, Kent Johnson wrote: > From: Kent Johnson > Subject: Re: [Tutor] manipulting CSV files > To: "Lowell Tackett" > Cc: "tutor" > Date: Friday, January 8, 2010, 10:07 AM > > Well, it's right - that is not a valid integer. What do you > want to do > with it? You could convert it to a number with > float(line[2]) or get > just the integer part with int(line[2].split('.')[0]). > > Kent Oh... I hadn't grasped the subtle meaning of "int()"; thanks, that helps. So, here's the (happy) result: >>> coord = csv.reader(open('true_coord', 'rb'), skipinitialspace = True) >>> for line in coord: .... if line[0] == '1001': .... print [float(line[1]) + float(line[2])] .... [1022313.8019999999] Please keep in mind, as I'd mentioned earlier, all of this is fairly new concepts to me; from running an interpretive Python screen, to delving into the zen of computing, [even] to pasting stuff from there to here--there's about 4 different "Learn Python and Make New Friends" books strewn around me and my computer desk right now, opened to different subjects (and the Joy of Google waiting on the internet) and with all that I want to develop to where I can create some pretty expansive scripts dealing with land surveying stuff--manipulating coordinates, inversing, traversing, bearings, etc., etc. Ya'll are meeting me here pretty much on the proverbial "First Step" of the 1000-mile journey, so all the help is very welcome and appreciated. Thanks. > From waynejwerner at gmail.com Fri Jan 8 17:27:56 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 8 Jan 2010 10:27:56 -0600 Subject: [Tutor] manipulting CSV files In-Reply-To: <139149.41706.qm@web110115.mail.gq1.yahoo.com> References: <1c2a2c591001080707m758790c9r73672e717c067421@mail.gmail.com> <139149.41706.qm@web110115.mail.gq1.yahoo.com> Message-ID: <333efb451001080827w6d03814dw6c9cf357f737bded@mail.gmail.com> On Fri, Jan 8, 2010 at 9:56 AM, Lowell Tackett wrote: > and with all that I want to develop to where I can create some > pretty expansive scripts dealing with land surveying stuff--manipulating > coordinates, inversing, traversing, bearings, etc., etc. > Maybe you could even get into drawing the surveys graphically... and maybe even in 3d! ;) but that's probably down 'round mile 3-500 or so. But certainly possible (and there are certainly libraries available to help when you get to that point)... Ya'll are meeting me here pretty much on the proverbial "First Step" of the > 1000-mile journey, so all the help is very welcome and appreciated. Thanks. And that's pretty much they key - you'll find plenty of help when you show that you're taking the steps (i.e. searching documentation, getting your own errors, asking how to overcome said errors... all of which you've done, obviously!). -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 8 17:31:16 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Jan 2010 11:31:16 -0500 Subject: [Tutor] manipulting CSV files In-Reply-To: <139149.41706.qm@web110115.mail.gq1.yahoo.com> References: <1c2a2c591001080707m758790c9r73672e717c067421@mail.gmail.com> <139149.41706.qm@web110115.mail.gq1.yahoo.com> Message-ID: <1c2a2c591001080831u5c2846eet20cc171462de4132@mail.gmail.com> On Fri, Jan 8, 2010 at 10:56 AM, Lowell Tackett wrote: > Please keep in mind, as I'd mentioned earlier, all of this is fairly new concepts to me; from running an interpretive Python screen, to delving into the zen of computing, [even] to pasting stuff from there to here--there's about 4 different "Learn Python and Make New Friends" books strewn around me and my computer desk right now, opened to different subjects (and the Joy of Google waiting on the internet) and with all that I want to develop to where I can create some pretty expansive scripts dealing with land surveying stuff--manipulating coordinates, inversing, traversing, bearings, etc., etc. > > Ya'll are meeting me here pretty much on the proverbial "First Step" of the 1000-mile journey, so all the help is very welcome and appreciated. ?Thanks. Congratulations on making it this far, you seem to be doing fine! Kent From lowelltackett at yahoo.com Fri Jan 8 19:45:28 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Fri, 8 Jan 2010 10:45:28 -0800 (PST) Subject: [Tutor] formatting* In-Reply-To: <20100108132749.4d62ed6b@o> Message-ID: <264186.92260.qm@web110110.mail.gq1.yahoo.com> >From the virtual desk of Lowell Tackett --- On Fri, 1/8/10, spir wrote: > From: spir > Subject: Re: [Tutor] formatting* > To: tutor at python.org > Date: Friday, January 8, 2010, 7:27 AM > Lowell Tackett dixit: > > Yo, that's because you're viewing the source as plain text,... > > Denis > ________________________________ > > la vita e estrany > In the meantime, posing this query took me somewhere I hadn't imagined...I got turned on to the 'Gmane' mailsite, which pretty much solved all my issues, plus presented a much nicer 'reading room'. After rummaging around awhile I've got the site figured out enough to make good use of it (a tip of the hat to Alan Gauld for the reference to that great site). From pythontutor at lxrb.com Fri Jan 8 20:21:50 2010 From: pythontutor at lxrb.com (Rob Cherry) Date: Fri, 8 Jan 2010 14:21:50 -0500 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> Message-ID: <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> Still trying to get the hang of some python intricacies, but this one has come up a few times. Beyond the obvious syntactic niceties what is the difference between importing with and without the "from" syntax? Its nice for example to do this - from socket import * googleip = gethostbyname("www.google.com") vs import socket googleip = socket.gethostbyname("www.google.com") Is there any difference between these concepts? Is there an easy google search term for me to research the difference to death? Thanks in advance! Rob From rabidpoobear at gmail.com Fri Jan 8 20:36:11 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 8 Jan 2010 13:36:11 -0600 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> Message-ID: The difference is a term called "namespace pollution". the "from socket import *" will place a whole lot of methods into your global namespace, possibly colliding with other methods / variables you've defined yourself. For example, if your file contained x = 5 from foobar import * and foobar contained x = 6 then x would be 6. This is a potential side-effect that's pretty undesirable. If you did the other import style, then x would not get overwritten. The reason the 'from' syntax was designed was so you could only import certain methods into your global namespace, but you'd be aware of which you were importing. So in your example you'd want to do from socket import gethostbyname so you're sure you know what you're importing into your namespace and you can avoid polluting it. HTH, -Luke On Fri, Jan 8, 2010 at 1:21 PM, Rob Cherry wrote: > Still trying to get the hang of some python intricacies, but this one > has come up a few times. Beyond the obvious syntactic niceties what > is the difference between importing with and without the "from" > syntax? > > Its nice for example to do this - > > from socket import * > googleip = gethostbyname("www.google.com") > > vs > > import socket > googleip = socket.gethostbyname("www.google.com") > > Is there any difference between these concepts? Is there an easy > google search term for me to research the difference to death? > > Thanks in advance! > > Rob > _______________________________________________ > 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 pythontutor at lxrb.com Fri Jan 8 20:39:23 2010 From: pythontutor at lxrb.com (Rob Cherry) Date: Fri, 8 Jan 2010 14:39:23 -0500 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> Message-ID: <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> Extending on this advice somewhat - is it *ever* correct to "import foobar". There are countless examples of import os,sys etc,etc. Strictly speaking should we always be using "from" to only get what we know we need? Thanks, Rob From rabidpoobear at gmail.com Fri Jan 8 20:45:11 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 8 Jan 2010 13:45:11 -0600 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> Message-ID: Yes, it depends how the library was designed. Some are designed so that you can import some of the library into your global namespace. For example, in Pygame library, it's accepted to do import pygame from pygame.locals import * This keeps the methods like pygame.init() pygame.display.set_mode() etc. but it lets you avoid having to do for event in pygame.event.get(): if event.type == pygame.KEYDOWN and event.key == pygame.K_UP: instead you can do for event in pygame.event.get(): if event.type == KEYDOWN and event.key == K_UP: But I don't know of any case where it's preferable to use the "from" syntax, it's mostly just a laziness thing. -Luke On Fri, Jan 8, 2010 at 1:39 PM, Rob Cherry wrote: > Extending on this advice somewhat - is it *ever* correct to "import > foobar". > > There are countless examples of > > import os,sys > > etc,etc. Strictly speaking should we always be using "from" to only > get what we know we need? > > Thanks, > > Rob > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Fri Jan 8 20:51:49 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 8 Jan 2010 13:51:49 -0600 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> Message-ID: <333efb451001081151m69639afeu407f62fd3bb98d16@mail.gmail.com> On Fri, Jan 8, 2010 at 1:21 PM, Rob Cherry wrote: > Still trying to get the hang of some python intricacies, but this one > has come up a few times. Beyond the obvious syntactic niceties what > is the difference between importing with and without the "from" > syntax? > > Its nice for example to do this - > > from socket import * > googleip = gethostbyname("www.google.com") > > vs > > import socket > googleip = socket.gethostbyname("www.google.com") > > Is there any difference between these concepts? Is there an easy > google search term for me to research the difference to death? > Namespace is a term you might want to look for. (Google "Python Namespace" or something to that effect) What the first one does is import all of the variables, classes, functions, and anything inside the socket library into the local namespace. This can lead to some pretty unpredictable behavior and is usually discouraged. It's better to import socket (or whatever module you want to import). But if you know you just want one function or class, you can use the "from" syntax to import it. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 8 21:16:38 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Jan 2010 15:16:38 -0500 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> Message-ID: <1c2a2c591001081216o109d2754jd175c220cf5188e@mail.gmail.com> On Fri, Jan 8, 2010 at 2:39 PM, Rob Cherry wrote: > Extending on this advice somewhat - is it *ever* correct to "import foobar". > > There are countless examples of > > import os,sys > > etc,etc. ?Strictly speaking should we always be using "from" to only > get what we know we need? No, the plain import is fine. import sys adds just the single name 'sys' to your global namespace, you then have to access the items in it via sys.version, etc. from sys import version imports just the name 'version' into your global namespace. Kent From lowelltackett at yahoo.com Sat Jan 9 00:54:00 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Fri, 8 Jan 2010 15:54:00 -0800 (PST) Subject: [Tutor] $PYTHONSTARTUP Message-ID: <278119.37617.qm@web110111.mail.gq1.yahoo.com> I'm not certain if this is more correctly a bash issue, but it seems logical to at least start here.? What I hope to do is set some standard commands (whenever I open an interactive python shell) as are outlined in the Python.org tutorial: 2.2.4. The Interactive Startup File? When you use Python interactively, it is frequently handy to have some standard commands executed every time the interpreter is started. You can do this by setting an environment variable named PYTHONSTARTUP to the name of a file containing your start-up commands. This is similar to the .profile feature of the Unix shells. Toward this end, I created a file that I called 'mypythonrc' and expanded the $PYTHONSTARTUP [bash] environmental file (in my '.bashrc' file) to include it--then I [re]sourced my '~/.bashrc' file to include the new entry.? The validity of that step shows up here: > Fri Jan 08:lowell:Coord]:$echo $PYTHONSTARTUP /etc/pythonrc.py:/home/lowell/bash_function/mypythonrc The details of the file 'mypythonrc' are here: ??????????? 1 #!/usr/bin/python ??????????? 2 ??????????? 3 import csv ??????????? 4 import os ??????????? 5 filename = os.environ.get('PYTHONSTARTUP') ??????????? 6 if filename and os.path.isfile(filename): ??????????? 7???????? execfile(filename) The results are...well, there are none.? The expectation [is] that whenever I open up an interactive Python shell the two modules 'csv' and 'os' will be "pre"-imported, and waiting for my use.? Ain't happenin'. So, again...is this the right venue for my question, or does it hafta be settled over at one of the (I guess if I hafta, I hafta) Linux forums? >From the virtual desk of Lowell Tackett -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sat Jan 9 01:46:48 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sat, 9 Jan 2010 01:46:48 +0100 Subject: [Tutor] $PYTHONSTARTUP In-Reply-To: <278119.37617.qm@web110111.mail.gq1.yahoo.com> References: <278119.37617.qm@web110111.mail.gq1.yahoo.com> Message-ID: <29179d161001081646v73dcb140u6e2f410eee5e32f4@mail.gmail.com> On Sat, Jan 9, 2010 at 12:54 AM, Lowell Tackett wrote: > I'm not certain if this is more correctly a bash issue, but it seems > logical to at least start here. What I hope to do is set some standard > commands (whenever I open an interactive python shell) as are outlined in > the Python.org tutorial: > > 2.2.4. The Interactive Startup File? > > When you use Python interactively, it is frequently handy to have some > standard commands executed every time the interpreter is started. You can do > this by setting an environment variable named *PYTHONSTARTUP*to the name of a file containing your start-up commands. This is similar to > the .profile feature of the Unix shells. > > Toward this end, I created a file that I called 'mypythonrc' and expanded > the $PYTHONSTARTUP [bash] environmental file (in my '.bashrc' file) to > include it--then I [re]sourced my '~/.bashrc' file to include the new > entry. The validity of that step shows up here: > > > Fri Jan 08:lowell:Coord]:$echo $PYTHONSTARTUP > /etc/pythonrc.py:/home/lowell/bash_function/mypythonrc > > The details of the file 'mypythonrc' are here: > > 1 #!/usr/bin/python > 2 > 3 import csv > 4 import os > 5 filename = os.environ.get('PYTHONSTARTUP') > 6 if filename and os.path.isfile(filename): > 7 execfile(filename) > > The results are...well, there are none. The expectation [is] that whenever > I open up an interactive Python shell the two modules 'csv' and 'os' will be > "pre"-imported, and waiting for my use. Ain't happenin'. > > So, again...is this the right venue for my question, or does it hafta be > settled over at one of the (I guess if I hafta, I hafta) Linux forums? > > From the virtual desk of Lowell Tackett > > Well, first thing I see wrong with this file, is the execfile call. It makes no sense. PYTHONSTARTUP equals "/etc/pythonrc.pyc:/home/lowell/bash_function/mypythonrc". That is not a valid filename, so the call won't be executed. isfile does not understand colon-separated paths, it expects a simple filename. Second, even if the PYTHONSTARTUP did contain a valid filename, and the contents of that file are as described, this script will execute itself, resulting in an infinite recursion. The statement makes no sense either way. The third thing is that PYTHONSTARTUP must be a filename, and only a filename. It does not understand a colon-separated list either (the documentation is fairly explicit on this: "if this is the name of a readable file.."). Trying this on my machine, at least, results in an IOError: no such file or directory. remove the execfile call and change PYTHONSTARTUP to just the path of the one file, and things should work fine. Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sat Jan 9 08:03:50 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 09 Jan 2010 18:03:50 +1100 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> Message-ID: On 1/9/2010 6:39 AM, Rob Cherry wrote: > Extending on this advice somewhat - is it *ever* correct to "import foobar". > > There are countless examples of > > import os,sys The rule of thumb is: Use the "from module import something" if you're only going to use one or two functions from the module; only use "from module import *" if the module was designed for such use (e.g. Tkconstants, pygame.constants) or if you're in the interactive interpreter. When in doubt, use the "import module" form. > > etc,etc. Strictly speaking should we always be using "from" to only > get what we know we need? Not necessarily, the "from module..." actually does a full "import module" in the back; you don't actually save anything by micro-controlling. In fact, it is quite a work to update the from-list every time you want to access another class/function in the module. However, the "from module import *" form is considered a bad form because it introduces namespace pollution. From denis.spir at free.fr Sat Jan 9 09:50:08 2010 From: denis.spir at free.fr (spir) Date: Sat, 9 Jan 2010 09:50:08 +0100 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> Message-ID: <20100109095008.37a4c7c0@o> Lie Ryan dixit: > only use "from module import *" if the > module was designed for such use In most cases, this translates to: the imported module defines __names__, which holds the list of names (of the objects) to be exported. Check it. Below, a,b,c,f,g,X,Y are defined, but only c,g,Y are exported. This means "from mod import *" will only import these names. Without __names__ defined, it would import all. ### module mod.py ### __names__ = ['c','g','Y'] a = ... b = ... c = ... def f(): ... def g(): ... class X(object): ... class Y(object): ... Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From alan.gauld at btinternet.com Sat Jan 9 10:44:43 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Jan 2010 09:44:43 -0000 Subject: [Tutor] formatting* References: <20100108132749.4d62ed6b@o> <264186.92260.qm@web110110.mail.gq1.yahoo.com> Message-ID: "Lowell Tackett" wrote > In the meantime, posing this query took me somewhere I hadn't imagined... > I got turned on to the 'Gmane' mailsite, which pretty much solved all my > issues, > plus presented a much nicer 'reading room'. I actually use it as a news feed into Outlook Express. I only occasionally use the gmane web site. Alan G. From rdmoores at gmail.com Sat Jan 9 10:53:48 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 9 Jan 2010 01:53:48 -0800 Subject: [Tutor] question about function inside of function Message-ID: I'm working on a function that seems to cry out for some of its code to be put in a function. For convenience sake, I've put this new function inside the one that calls it. Question 1: Is this bad practice? It works fine that way, but.. Question 2: If the answer to Q1 is no, is there a standard place to put a function inside of another function? Is it standard to have it the first line of the function? I've put mine at the point where it would be called, mainly as a reminder to myself. An outline of the big function is: if: else: for loop for loop if elif the function call the function else Thanks, Dick Moores From sudheer.kay at gmail.com Sat Jan 9 10:53:56 2010 From: sudheer.kay at gmail.com (sudhir prasad) Date: Sat, 9 Jan 2010 15:23:56 +0530 Subject: [Tutor] (no subject) Message-ID: hi, iam a beginner. sample_file = file("/home/ee08m082/Desktop/python/123.txt","w") sample_file.write("About Pythons\n") in the above two line code,123.txt is being created but "About Pythons" is not being written in the file. my OS is redhat linux and python version is 2.3.4 thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sat Jan 9 12:32:44 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 09 Jan 2010 06:32:44 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4B48695C.8060201@ieee.org> sudhir prasad wrote: > hi, > iam a beginner. > > sample_file = file("/home/ee08m082/Desktop/python/123.txt","w") > sample_file.write("About Pythons\n") > > in the above two line code,123.txt is being created but "About Pythons" is > not being written in the file. > my OS is redhat linux and python version is 2.3.4 > > thanks > > You forgot to close the file. sample_file.close() DaveA From galaxywatcher at gmail.com Sat Jan 9 13:44:54 2010 From: galaxywatcher at gmail.com (galaxywatcher at gmail.com) Date: Sat, 9 Jan 2010 19:44:54 +0700 Subject: [Tutor] Expanding a Python script to include a zcat and awk pre-process In-Reply-To: <1c2a2c591001080620wf6de5cdqf877c33072e26834@mail.gmail.com> References: <5DFF81F3-A087-41F2-984B-914A08E2B2FC@gmail.com> <1c2a2c591001080620wf6de5cdqf877c33072e26834@mail.gmail.com> Message-ID: <39C02634-E169-48CA-A1F6-83F5AA7A7299@gmail.com> After many more hours of reading and testing, I am still struggling to finish this simple script, which bear in mind, I already got my desired results by preprocessing with an awk one-liner. I am opening a zipped file properly, so I did make some progress, but simply assigning num1 and num2 to the first 2 columns of the file remains elusive. Num3 here gets assigned, not to the 3rd column, but the rest of the entire file. I feel like I am missing a simple strip() or some other incantation that prevents the entire file from getting blobbed into num3. Any help is appreciated in advance. #!/usr/bin/env python import string import re import zipfile highflag = flagcount = sum = sumtotal = 0 f = file("test.zip") z = zipfile.ZipFile(f) for f in z.namelist(): ranges = z.read(f) ranges = ranges.strip() num1, num2, num3 = re.split('\W+', ranges, 2) ## This line is the root of the problem. sum = int(num2) - int(num1) if sum > 10000000: flag1 = " !!!!" flagcount += 1 else: flag1 = "" if sum > highflag: highflag = sum print str(num2) + " - " + str(num1) + " = " + str(sum) + flag1 sumtotal = sumtotal + sum print "Total ranges = ", sumtotal print "Total ranges over 10 million: ", flagcount print "Largest range: ", highflag ====== $ zcat test.zip 134873600, 134873855, "32787 Protex Technologies, Inc." 135338240, 135338495, 40597 135338496, 135338751, 40993 201720832, 201721087, "12838 HFF Infrastructure & Operations" 202739456, 202739711, "1623 Beseau Regional de la Region Languedoc Roussillon" From denis.spir at free.fr Sat Jan 9 14:03:09 2010 From: denis.spir at free.fr (spir) Date: Sat, 9 Jan 2010 14:03:09 +0100 Subject: [Tutor] question about function inside of function In-Reply-To: References: Message-ID: <20100109140309.4ca58a00@o> Richard D. Moores dixit: > I'm working on a function that seems to cry out for some of its code > to be put in a function. For convenience sake, I've put this new > function inside the one that calls it. > > Question 1: Is this bad practice? It works fine that way, but.. > > Question 2: If the answer to Q1 is no, is there a standard place to > put a function inside of another function? Is it standard to have it > the first line of the function? I've put mine at the point where it > would be called, mainly as a reminder to myself. > > An outline of the big function is: > > if: > else: > for loop > for loop > if > elif > the function > call the function > else > > Thanks, Do you realize the inner func will be redefined before each call? Meaning in your case n calls x n outer loops x n inner loops. def f() ... is actually a kind of masked assignment f = function()... To avoid polluting the global namespace (if it's what you mean), you can assiattach the inner func as an attribute of the outer: "g.f = f". Unfortunately, it's not possible (I guess), to define it directly using "def g.f()". Also, if a func logically is an attribute of another, then probably you're close to defined an object, possibly with other attributes. Think at the design of the application. I may be wrong, but I guess the only common case where you should (and must) define a func inside another is the one of a func factory, ie a func that defines (and returns) a new func: def makeAdder(val): def adder(x): return x + adder.val adder.val = val return adder add3 = makeAdder(3) print add3(2) # --> 5 Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From rdmoores at gmail.com Sat Jan 9 15:21:58 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 9 Jan 2010 06:21:58 -0800 Subject: [Tutor] question about function inside of function In-Reply-To: <20100109140309.4ca58a00@o> References: <20100109140309.4ca58a00@o> Message-ID: On Sat, Jan 9, 2010 at 05:03, spir wrote: > Do you realize the inner func will be redefined before each call? Oh, I forgot about that. Thanks! Dick From alan.gauld at btinternet.com Sat Jan 9 16:21:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Jan 2010 15:21:59 -0000 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com><43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> Message-ID: "Rob Cherry" wrote > Extending on this advice somewhat - is it *ever* correct to "import > foobar". Yes, it is *usually* correct to "import foobar" and rarely correct to "from foobar". The exception being if you only need one or two names from foobar, but usually you need a lot more, in which case use import foobar. To save typing you can give foobar a shorter name: import foobar as fb For some reason that convenience feature doesn't get mentioned all that often but I use it a lot. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 9 16:28:55 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Jan 2010 15:28:55 -0000 Subject: [Tutor] question about function inside of function References: Message-ID: "Richard D. Moores" wrote > to be put in a function. For convenience sake, I've put this new > function inside the one that calls it. > > Question 1: Is this bad practice? It works fine that way, but.. No, but there are some issues to consider. Denis has addressed some but one other is... Reuse: by hiding the function inside the outer one it means it can only ever be used inside that function. It may be better to have it as a module level function - even if you use the _prefix to limit its use outside the module. > Question 2: If the answer to Q1 is no, is there a standard place to > put a function inside of another function? Is it standard to have it > the first line of the function? I've put mine at the point where it > would be called, mainly as a reminder to myself. Top of the function is best because as Denis says it only gets defined once per function call. If you are really paranoid and the function only gets used in exceptional cases then you could define it at the point of use but in that case you probably don't need a function at all! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mab43 at duke.edu Sat Jan 9 16:31:56 2010 From: mab43 at duke.edu (Matt Ball) Date: Sat, 9 Jan 2010 10:31:56 -0500 Subject: [Tutor] cookielib and form authentication woes Message-ID: <61e6b5ce1001090731n4028f2bevb5a7516785156635@mail.gmail.com> dear tutors, I'm trying to use a GPS tracking service called InstaMapper. The service changes how frequently it updates the tracking device's position based on whether the UI is being accessed on the InstaMapper webpage. I'd like to have the increased update frequency happen all the time so I thought I'd write a python script to login to my account and access the page periodically: import urllib2, urllib, cookielib cj = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) params = urllib.urlencode(dict(username_hb='user', password_hb='resu')) opener.open('http://www.instamapper.com/fe?action=login', params) if not 'id' in [cookie.name for cookie in cj]: raise ValueError, "Login failed" # now try secured page resp = opener.open('http://www.instamapper.com/fe?page=track&device_key=abc ') print resp.read() resp.close() The ValueError is raised each time. If I remove this and read the response, the page thinks I have disabled cookies and blocks access. Why isn't cj grabbing the InstaMapper cookie? Are there better ways to make the tracking service think I'm viewing my account constantly? -Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From lowelltackett at yahoo.com Sat Jan 9 17:35:45 2010 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Sat, 9 Jan 2010 08:35:45 -0800 (PST) Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: Message-ID: <958097.31091.qm@web110103.mail.gq1.yahoo.com> If I might offer one small comment... It seems to me that this argument also goes to a code readability issue; ergo, if you choose "from foobar..." as opposed to "import foobar", then from that point on you only need employ foobar's methods in your code, and they are not alway easily recognizable.? i.e, by importing foobar, you will always prefix a method with its' parent module name, which [I think] makes the code more understandable. >From the virtual desk of Lowell Tackett? --- On Sat, 1/9/10, Alan Gauld wrote: From: Alan Gauld Subject: Re: [Tutor] Question on "import foobar" vs "from foobar import *" To: tutor at python.org Date: Saturday, January 9, 2010, 10:21 AM "Rob Cherry" wrote > Extending on this advice somewhat - is it *ever* correct to "import foobar". Yes, it is *usually* correct to "import foobar" and rarely correct to "from foobar". The exception being if you only need one or two names from foobar, but usually you need a lot more, in which case use import foobar. To save typing you can give foobar a shorter name: import foobar as fb For some reason that convenience feature doesn't get mentioned all that often but I use it a lot. 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Sat Jan 9 18:11:03 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 9 Jan 2010 09:11:03 -0800 Subject: [Tutor] question about function inside of function In-Reply-To: References: Message-ID: On Sat, Jan 9, 2010 at 07:28, Alan Gauld wrote: > > "Richard D. Moores" wrote >> >> to be put in a function. For convenience sake, I've put this new >> function inside the one that calls it. >> >> Question 1: Is this bad practice? It works fine that way, but.. > > No, but there are some issues to consider. > Denis has addressed some but one other is... > > Reuse: by hiding the function inside the outer one it means it can only ever > be used inside that function. That's OK. It's very specific to the enclosing function. > It may be better to have it as a module level > function - even if you use the _prefix to limit its use outside the module. > >> Question 2: If the answer to Q1 is no, is there a standard place to >> put a function inside of another function? Is it standard to have it >> the first line of the function? I've put mine at the point where it >> would be called, mainly as a reminder to myself. > > Top of the function is best because as Denis says it only gets defined once > per function call. If you are really paranoid and the function only gets > used in exceptional cases then you could define it at the point of use but > in that case you probably don't need a function at all! I moved it to the top. But since writing it I debugged and edited the script so that the small function is used in only one case. So you're right, I don't need it as a function at all. Thanks, Alan. Right on as usual. Dick From davea at ieee.org Sat Jan 9 18:25:48 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 09 Jan 2010 12:25:48 -0500 Subject: [Tutor] Expanding a Python script to include a zcat and awk pre-process In-Reply-To: <39C02634-E169-48CA-A1F6-83F5AA7A7299@gmail.com> References: <5DFF81F3-A087-41F2-984B-914A08E2B2FC@gmail.com> <1c2a2c591001080620wf6de5cdqf877c33072e26834@mail.gmail.com> <39C02634-E169-48CA-A1F6-83F5AA7A7299@gmail.com> Message-ID: <4B48BC1C.7090600@ieee.org> galaxywatcher at gmail.com wrote: >
After > many more hours of reading and testing, I am still struggling to > finish this simple script, which bear in mind, I already got my > desired results by preprocessing with an awk one-liner. > > I am opening a zipped file properly, so I did make some progress, but > simply assigning num1 and num2 to the first 2 columns of the file > remains elusive. Num3 here gets assigned, not to the 3rd column, but > the rest of the entire file. I feel like I am missing a simple strip() > or some other incantation that prevents the entire file from getting > blobbed into num3. Any help is appreciated in advance. > > #!/usr/bin/env python > > import string > import re > import zipfile > highflag = flagcount = sum = sumtotal = 0 > f = file("test.zip") > z = zipfile.ZipFile(f) > for f in z.namelist(): > ranges = z.read(f) This reads the whole file into ranges. In your earlier incantation, you looped over the file, one line at a time. So to do the equivalent, you want to do a split here, and one more nesting of loops. lines = z.read(f).split("\n") #build a list of text lines for ranges in lines: #here, ranges is a single line and of course, indent the remainder. > ranges = ranges.strip() > num1, num2, num3 = re.split('\W+', ranges, 2) ## This line is the > root of the problem. > sum = int(num2) - int(num1) > if sum > 10000000: > flag1 = " !!!!" > flagcount += 1 > else: > flag1 = "" > if sum > highflag: > highflag = sum > print str(num2) + " - " + str(num1) + " = " + str(sum) + flag1 > sumtotal = sumtotal + sum > > print "Total ranges = ", sumtotal > print "Total ranges over 10 million: ", flagcount > print "Largest range: ", highflag > > ====== > $ zcat test.zip > 134873600, 134873855, "32787 Protex Technologies, Inc." > 135338240, 135338495, 40597 > 135338496, 135338751, 40993 > 201720832, 201721087, "12838 HFF Infrastructure & Operations" > 202739456, 202739711, "1623 Beseau Regional de la Region Languedoc > Roussillon" > > >
> From galaxywatcher at gmail.com Sat Jan 9 18:34:54 2010 From: galaxywatcher at gmail.com (galaxywatcher at gmail.com) Date: Sun, 10 Jan 2010 00:34:54 +0700 Subject: [Tutor] Expanding a Python script to include a zcat and awk pre-process In-Reply-To: References: Message-ID: <93D0DED8-02A6-4D6E-81A0-FB4AE42CEA0F@gmail.com> I finally got it working! I would do a victory lap around my apartment building if I wasn't recovering from a broken ankle. Excuse my excitement, but this simple script marks a new level of Python proficiency for me. Thanks to Kent, Bob, Denis, and others who pointed me in the right direction. It does quite a few things: decompresses a zipped file or files if there is an archive of them, processes a rather ugly csv file (ugly because it uses a comma as a delimiter, yet there are commas in double quote separated fields), and it does a simple subtraction of the two columns with a little summary to give me the data I need. #!/usr/bin/env python import string import re import zipfile highflag = flagcount = sum = sumtotal = 0 z = zipfile.ZipFile('textfile.zip') for subfile in z.namelist(): print "Working on filename: " + subfile + "\n" data = z.read(subfile) pat = re.compile(r"""(\d+), (\d+), (\".+\"|\w+)""") for line in data.splitlines(): result = pat.match(line) ranges = result.groups() num1 = ranges[0] num2 = ranges[1] sum = int(num2) - int(num1) if sum > 10000000: flag1 = " !!!!" flagcount += 1 else: flag1 = "" if sum > highflag: highflag = sum print str(num2) + " - " + str(num1) + " = " + str(sum) + flag1 sumtotal = sumtotal + sum print "Total ranges = ", sumtotal print "Total ranges over 10 million: ", flagcount print "Largest range: ", highflag A few observations from a Python newbie: The zipfile and gzip modules should really be merged together. gzcat on unix reads both compression formats. It took me way too long to figure out the namelist() method. But I did learn a lot more about how zip actually works as a result. Is there really no way to extract the contents of a single zipped file without using a 'for in namelist' construct? Trying to get split() to extract just two columns from my data was a dead end. The re module is the way to go. I feel like I am in relatively new territory with Python's regex engine. Denis did save me some valuable time with his regex, but my file had values in the 3rd column that started with alphas as opposed to numerics only, and flipping that (\".+\"|\d+)""") to a (\".+\"|\w +)""") had me gnashing teeth and pulling hair the whole way through the regex tutorial. When I finally figured it out, I smack my forehead and say "of course!". The compile() method of Python's regex engine is new for me. Makes sense. Just something I have to get used to. I do have the feeling that Perl's regex is better. But that is another story. From timgoddardsemail at gmail.com Sat Jan 9 21:22:40 2010 From: timgoddardsemail at gmail.com (Tim Goddard) Date: Sat, 9 Jan 2010 14:22:40 -0600 Subject: [Tutor] Hooray! I finished the 'Learning Python for absolute beginners' Message-ID: Ok, it's not a big deal, but once I learned enough I went off on a few tangents to create programs of my own design. Since I had to return the book to the public library, I finally got back to finishing the last chapter. Since the book is not current, I took the time to decipher the differences and eventually figured out the final project creating an asteroids game using the latest livewires. I would eventually like to use pygame, but for now I'm content that it works. I know there have been some questions in the past about errors, so this is simply being submitted as a placemarker for those working through the same book. I'm really glad I decided to learn Python! I also figured out how to configure Eclipse IDE to recognize modules. Apparently in the preferences for each 'project' is a separate PYTHONPATH.. which is not to be confused with sys.path. Adding the appropriate folders to the preferences allows the user to browse through a module i.e. after writing: 'from livewires import games' typing: 'games.' yields a drop down menu of all methods etc.... very convenient when trying to follow older tutorials of older packages. From eddie9139 at gmail.com Sat Jan 9 23:54:06 2010 From: eddie9139 at gmail.com (Eddie) Date: Sun, 10 Jan 2010 09:54:06 +1100 Subject: [Tutor] Hooray! I finished the 'Learning Python for absolute beginners' In-Reply-To: References: Message-ID: Nice one... I should still get to starting lol... 2010/1/10 Tim Goddard > Ok, it's not a big deal, but once I learned enough I went off on a few > tangents to create programs of my own design. Since I had to return > the book to the public library, I finally got back to finishing the > last chapter. Since the book is not current, I took the time to > decipher the differences and eventually figured out the final project > creating an asteroids game using the latest livewires. I would > eventually like to use pygame, but for now I'm content that it works. > > I know there have been some questions in the past about errors, so > this is simply being submitted as a placemarker for those working > through the same book. > > I'm really glad I decided to learn Python! > > I also figured out how to configure Eclipse IDE to recognize modules. > Apparently in the preferences for each 'project' is a separate > PYTHONPATH.. which is not to be confused with sys.path. Adding the > appropriate folders to the preferences allows the user to browse > through a module i.e. > > after writing: > 'from livewires import games' > > typing: > 'games.' yields a drop down menu of all methods etc.... very > convenient when trying to follow older tutorials of older packages. > _______________________________________________ > 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 Sun Jan 10 00:40:07 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Jan 2010 23:40:07 -0000 Subject: [Tutor] Hooray! I finished the 'Learning Python for absolutebeginners' References: Message-ID: "Tim Goddard" wrote > I also figured out how to configure Eclipse IDE to recognize modules. > Apparently in the preferences for each 'project' is a separate > PYTHONPATH.. which is not to be confused with sys.path. Adding the > appropriate folders to the preferences allows the user to browse > through a module i.e. I assume you have already installed the PyDev plugin? I'm currently reading a book on Eclipse (Eclipse Distilled) which has turned up many settings and tricks that I was unaware of. It is a powerful tool but like all such it takes a lot of learing to get the most from it. Alan G. From warpcat at gmail.com Sun Jan 10 01:23:26 2010 From: warpcat at gmail.com (Eric Pavey) Date: Sat, 9 Jan 2010 16:23:26 -0800 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <958097.31091.qm@web110103.mail.gq1.yahoo.com> References: <958097.31091.qm@web110103.mail.gq1.yahoo.com> Message-ID: <23cba4bf1001091623h20aa96e9y3a552f2c33b7d518@mail.gmail.com> I should add (that as I understand it), when you do a 'from foo import blah', or 'from foo import *', this is doing a *copy* (effectively) of that module's attributes into the current namespace. Doing "import foo" or "import foo as goo" is keeping a *reference *to the imported module rather than a copy. If you use the 'from import' system, changes made to attrs of the imported module *won't* be seen by any other module that imported it. If you do just an 'import' on a module (or 'import ... as ...'), then changes made to attrs on the imported module *will *be seen by othe modules that import it as well. I hope that is somewhat clear. ;) On Sat, Jan 9, 2010 at 8:35 AM, Lowell Tackett wrote: > If I might offer one small comment... > > It seems to me that this argument also goes to a code readability issue; > ergo, if you choose "from foobar..." as opposed to "import foobar", then > from that point on you only need employ foobar's methods in your code, and > they are not alway easily recognizable. i.e, by importing foobar, you will > always prefix a method with its' parent module name, which [I think] makes > the code more understandable. > > From the virtual desk of Lowell Tackett > > > --- On *Sat, 1/9/10, Alan Gauld * wrote: > > > From: Alan Gauld > Subject: Re: [Tutor] Question on "import foobar" vs "from foobar import *" > To: tutor at python.org > Date: Saturday, January 9, 2010, 10:21 AM > > > > "Rob Cherry" > > wrote > > > Extending on this advice somewhat - is it *ever* correct to "import > foobar". > > Yes, it is *usually* correct to "import foobar" and rarely correct to "from > foobar". > The exception being if you only need one or two names from foobar, but > usually you need a lot more, in which case use import foobar. > > To save typing you can give foobar a shorter name: > > import foobar as fb > > For some reason that convenience feature doesn't get mentioned > all that often but I use it a lot. > > HTH, > > > -- Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jan 10 02:52:37 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 09 Jan 2010 20:52:37 -0500 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <23cba4bf1001091623h20aa96e9y3a552f2c33b7d518@mail.gmail.com> References: <958097.31091.qm@web110103.mail.gq1.yahoo.com> <23cba4bf1001091623h20aa96e9y3a552f2c33b7d518@mail.gmail.com> Message-ID: <4B4932E5.9080506@gmail.com> Eric Pavey wrote: > I should add (that as I understand it), when you do a 'from foo import > blah', or 'from foo import *', this is doing a /copy/ (effectively) of > that module's attributes into the current namespace. Not a copy (which means duplicating the attribute) but a new reference to the original attribute. Example >>> import sys >>> from sys import modules >>> sys.modules is modules True >>> m = dict(sys.modules) # create a copy >>> m is modules False -- Bob Gailer Chapel Hill NC 919-636-4239 From lie.1296 at gmail.com Sun Jan 10 06:08:40 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 10 Jan 2010 16:08:40 +1100 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <23cba4bf1001091623h20aa96e9y3a552f2c33b7d518@mail.gmail.com> References: <958097.31091.qm@web110103.mail.gq1.yahoo.com> <23cba4bf1001091623h20aa96e9y3a552f2c33b7d518@mail.gmail.com> Message-ID: On 1/10/2010 11:23 AM, Eric Pavey wrote: > I should add (that as I understand it), when you do a 'from foo import > blah', or 'from foo import *', this is doing a /copy/ (effectively) of > that module's attributes into the current namespace. Doing "import foo" > or "import foo as goo" is keeping a /reference /to the imported module > rather than a copy. No, that's a roundabout way to look at it. Python's variable holds references to objects[1] and never the object themselves; name assignment statement in python never makes a copy of the object, but always makes a new reference to the same object. "Assignment statements" in python includes the '=', 'from import', and regular 'import' [2]. [1] this is call-by-object http://effbot.org/zone/python-objects.htm http://effbot.org/zone/call-by-object.htm [2] there are other more obscure statements that is an 'assignment statement' as well, such as "with ... as ...", "agumented assignment operators", dictionary/list assignment, etc. The list is non-exhaustive. > If you use the 'from import' system, changes made to attrs of the > imported module /won't/ be seen by any other module that imported it. > If you do just an 'import' on a module (or 'import ... as ...'), then > changes made to attrs on the imported module /will /be seen by othe > modules that import it as well. I hope that is somewhat clear. ;) Read both links to effbot's article, they should make it clear why the current behavior is the way it is. From timgoddardsemail at gmail.com Sun Jan 10 16:09:07 2010 From: timgoddardsemail at gmail.com (Tim Goddard) Date: Sun, 10 Jan 2010 09:09:07 -0600 Subject: [Tutor] Hooray! I finished the 'Learning Python for > absolutebeginners' Message-ID: "Alan Gauld" wrote: > I assume you have already installed the PyDev plugin? > > I'm currently reading a book on Eclipse (Eclipse Distilled) which has > turned up many settings and tricks that I was unaware of. It is a > powerful tool but like all such it takes a lot of learing to get the most > from it. > > Alan G. > Sorry Alan, I am being too vague in my writing. My instance of Eclipse was installed as part of Python(x,y) and included the Pydev plugin. I was fortunate as a beginner programmer, that someone else figured out how to configure Eclipse with the PyDev plugin. Using other IDE installed as part of Python(x,y) i.e. Spyder, gave me insight into what I was missing with Eclipse. I'm missing a lot, I mean simply missing out on one aspect of Eclipse. Tim G From warpcat at gmail.com Sun Jan 10 22:11:59 2010 From: warpcat at gmail.com (Eric Pavey) Date: Sun, 10 Jan 2010 13:11:59 -0800 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: References: <958097.31091.qm@web110103.mail.gq1.yahoo.com> <23cba4bf1001091623h20aa96e9y3a552f2c33b7d518@mail.gmail.com> Message-ID: <23cba4bf1001101311u1c65064atdeff8da9632c319e@mail.gmail.com> On Sat, Jan 9, 2010 at 9:08 PM, Lie Ryan wrote: > On 1/10/2010 11:23 AM, Eric Pavey wrote: > >> I should add (that as I understand it), when you do a 'from foo import >> blah', or 'from foo import *', this is doing a /copy/ (effectively) of >> that module's attributes into the current namespace. Doing "import foo" >> or "import foo as goo" is keeping a /reference /to the imported module >> rather than a copy. >> > > No, that's a roundabout way to look at it. Python's variable holds > references to objects[1] and never the object themselves; name assignment > statement in python never makes a copy of the object, but always makes a new > reference to the same object. "Assignment statements" in python includes the > '=', 'from import', and regular 'import' [2]. > > [1] this is call-by-object http://effbot.org/zone/python-objects.htm > http://effbot.org/zone/call-by-object.htm > [2] there are other more obscure statements that is an 'assignment > statement' as well, such as "with ... as ...", "agumented assignment > operators", dictionary/list assignment, etc. The list is non-exhaustive. > > > If you use the 'from import' system, changes made to attrs of the >> imported module /won't/ be seen by any other module that imported it. >> If you do just an 'import' on a module (or 'import ... as ...'), then >> changes made to attrs on the imported module /will /be seen by othe >> modules that import it as well. I hope that is somewhat clear. ;) >> > > Read both links to effbot's article, they should make it clear why the > current behavior is the way it is. > See, I figured I'd get straightened out myself by posting that. Those concepts help me out as well ;) Always learning... -------------- next part -------------- An HTML attachment was scrubbed... URL: From kvander11 at gmail.com Mon Jan 11 01:45:59 2010 From: kvander11 at gmail.com (Kirk Vander Meulen) Date: Sun, 10 Jan 2010 18:45:59 -0600 Subject: [Tutor] tk help Message-ID: <2d0c08ca1001101645v501cb5f1n9f327e052a7f38d1@mail.gmail.com> I'm working on a program partly to get the hang of gui programming. I'm a bit puzzled by the behavior of simple dialogs- I wonder why, in the following code, the second call to tkMessageBox.askyesno always returns 'False' (either 'yes' or 'no' return False!). If I take out the call to tkFileDialog.askdirectory(), the second call works as expected (yes->True,no->False). I would really appreciate if someone could take a look at this and tell me what I'm missing. Thanks, Kirk import tkFileDialog,tkMessageBox addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?') print(addDirectory) theDirectory=tkFileDialog.askdirectory() print(addDirectory) print(theDirectory) addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?') print(addDirectory) print(theDirectory) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 11 03:29:10 2010 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Jan 2010 21:29:10 -0500 Subject: [Tutor] question about function inside of function In-Reply-To: <20100109140309.4ca58a00@o> References: <20100109140309.4ca58a00@o> Message-ID: <1c2a2c591001101829m7a607dd6ocf8d8d981c693bab@mail.gmail.com> On Sat, Jan 9, 2010 at 8:03 AM, spir wrote: > Do you realize the inner func will be redefined before each call? Meaning in your case n calls x n outer loops x n inner loops. > ? def f() ... > is actually a kind of masked assignment > ? f = function()... That's true, but it is pretty inexpensive. The heavy lifting is at compile time when a code object is created. Wrapping this as a function is fast. Kent From kent37 at tds.net Mon Jan 11 03:34:36 2010 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Jan 2010 21:34:36 -0500 Subject: [Tutor] Question on "import foobar" vs "from foobar import *" In-Reply-To: <20100109095008.37a4c7c0@o> References: <43ebcc41001081117i25835c0tbba66acb65ef6b29@mail.gmail.com> <43ebcc41001081121i3dd7d335rcd1b9ea1806e975e@mail.gmail.com> <43ebcc41001081139u67965675g61c3ca75b1537f6c@mail.gmail.com> <20100109095008.37a4c7c0@o> Message-ID: <1c2a2c591001101834u75c21a71iae7e18094540eae8@mail.gmail.com> On Sat, Jan 9, 2010 at 3:50 AM, spir wrote: > Lie Ryan dixit: > >> only use "from module import *" if the >> module was designed for such use > > In most cases, this translates to: the imported module defines __names__, which holds the list of names (of the objects) to be exported. Check it. > Below, a,b,c,f,g,X,Y are defined, but only c,g,Y are exported. This means "from mod import *" will only import these names. Without __names__ defined, it would import all.\ That should be __all__, not __names__ Kent From Tom_Roche at pobox.com Mon Jan 11 04:44:31 2010 From: Tom_Roche at pobox.com (Tom Roche) Date: Sun, 10 Jan 2010 22:44:31 -0500 (EST) Subject: [Tutor] composing one test suite from two test cases Message-ID: <20100111034431.40DEB141D1C19@cedar.isis.unc.edu> How to create a single unittest test suite class that runs all methods from multiple TestCase classes? Why I ask: I'm trying to relearn TDD and learn Python by coding a simple app. Currently the app has 2 simple functional classes, Pid and TallyPid, and 2 very simple testcases, PidTests and TallyPidTests: http://www.unc.edu/~tr/courses/ENVR400/Pid.py http://www.unc.edu/~tr/courses/ENVR400/PidTests.py http://www.unc.edu/~tr/courses/ENVR400/Tally.py http://www.unc.edu/~tr/courses/ENVR400/TallyPidTests.py I can run both testcases > >python PidTests.py > .................... > ---------------------------------------------------------------------- > Ran 20 tests in 0.000s > OK > >python TallyPidTests.py > . > ---------------------------------------------------------------------- > Ran 1 test in 0.563s > OK Before I continue, I'd like to create a single suite, in a separate cfile file/module (e.g. AllTests.py), that will run both testcases (PidTests.py and TallyPidTests.py). Unfortunately I have not been able to do this! which surprises me, since creating such a suite in JUnit is trivial. Can someone show me how to create this suite in python? (FWIW the python version=2.5.2: downlevel, I know, but the box also needs to run ArcGIS.) TIA, Tom Roche From sudheer.kay at gmail.com Mon Jan 11 08:33:29 2010 From: sudheer.kay at gmail.com (sudhir prasad) Date: Mon, 11 Jan 2010 13:03:29 +0530 Subject: [Tutor] what is the equivalent function to strtok() in c++ Message-ID: hi, what is the equivalent function to strtok() in c++, what i need to do is to divide a line into different strings and store them in different lists,and write them in to another file -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Jan 11 08:49:06 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 11 Jan 2010 02:49:06 -0500 Subject: [Tutor] what is the equivalent function to strtok() in c++ In-Reply-To: References: Message-ID: <4B4AD7F2.5030007@ieee.org> sudhir prasad wrote: > hi, > what is the equivalent function to strtok() in c++, > what i need to do is to divide a line into different strings and store them > in different lists,and write them in to another file > > If your tokens are separated by whitespace, you can simply use a single call to split(). It will turn a single string into a list of tokens. line = "Now is the time" print line.split() will display the list: ['Now', 'is', 'the', 'time'] HTH DaveA From alan.gauld at btinternet.com Mon Jan 11 10:02:30 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Jan 2010 09:02:30 -0000 Subject: [Tutor] tk help References: <2d0c08ca1001101645v501cb5f1n9f327e052a7f38d1@mail.gmail.com> Message-ID: "Kirk Vander Meulen" wrote > I'm working on a program partly to get the hang of gui programming. I'm > a > bit puzzled by the behavior of simple dialogs- I wonder why, in the > following code, the second call to tkMessageBox.askyesno always returns > 'False' (either 'yes' or 'no' return False!). If I take out the call to > tkFileDialog.askdirectory(), the second call works as expected > (yes->True,no->False). I would really appreciate if someone could take a > look at this and tell me what I'm missing. Thanks, After converting the imports for Python 3 it worked perfectly for me >>> ================================ RESTART >>> ================================ >>> True True H:/PROJECTS/Python/Tutor3 True H:/PROJECTS/Python/Tutor3 >>> ================================ RESTART >>> ================================ >>> > import tkFileDialog,tkMessageBox > addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?') > print(addDirectory) > theDirectory=tkFileDialog.askdirectory() > print(addDirectory) Any reason why you print it a second time even though there has been no change? > print(theDirectory) > addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?') > print(addDirectory) > print(theDirectory) And the same here? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jan 11 10:07:23 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Jan 2010 09:07:23 -0000 Subject: [Tutor] what is the equivalent function to strtok() in c++ References: <4B4AD7F2.5030007@ieee.org> Message-ID: "Dave Angel" wrote > If your tokens are separated by whitespace, you can simply use a single > call to split(). It will turn a single string into a list of tokens. > > line = "Now is the time" > print line.split() > > will display the list: > ['Now', 'is', 'the', 'time'] And if it's not separated by whitespace you can supply the separator, eg a colon: line.split(':') For more sophisticated functionality use the re module or a specialised parser. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From stefan_ml at behnel.de Mon Jan 11 10:32:47 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 11 Jan 2010 10:32:47 +0100 Subject: [Tutor] what is the equivalent function to strtok() in c++ In-Reply-To: References: <4B4AD7F2.5030007@ieee.org> Message-ID: Alan Gauld, 11.01.2010 10:07: > For more sophisticated functionality use the re module or a specialised > parser. Just a quick note here, "specialised parser" might sound like something that's hard to write. It's not. There are quite some parser packages available for Python that are easy to use. Pyparsing comes to mind, for example. Stefan From ph4nut at gmail.com Mon Jan 11 11:41:46 2010 From: ph4nut at gmail.com (Make Twilight) Date: Mon, 11 Jan 2010 18:41:46 +0800 Subject: [Tutor] Tutor Digest, Vol 71, Issue 28 In-Reply-To: References: Message-ID: <43563d821001110241w4e47dccat103b1518ef19cb3c@mail.gmail.com> On Sat, Jan 9, 2010 at 9:08 PM, Lie Ryan wrote: > On 1/10/2010 11:23 AM, Eric Pavey wrote: > >> I should add (that as I understand it), when you do a 'from foo import >> blah', or 'from foo import *', this is doing a /copy/ (effectively) of >> that module's attributes into the current namespace. Doing "import foo" >> or "import foo as goo" is keeping a /reference /to the imported module >> rather than a copy. >> > > No, that's a roundabout way to look at it. Python's variable holds > references to objects[1] and never the object themselves; name assignment > statement in python never makes a copy of the object, but always makes a new > reference to the same object. "Assignment statements" in python includes the > '=', 'from import', and regular 'import' [2]. > > [1] this is call-by-object http://effbot.org/zone/python-objects.htm > http://effbot.org/zone/call-by-object.htm > [2] there are other more obscure statements that is an 'assignment > statement' as well, such as "with ... as ...", "agumented assignment > operators", dictionary/list assignment, etc. The list is non-exhaustive. > > > If you use the 'from import' system, changes made to attrs of the >> imported module /won't/ be seen by any other module that imported it. >> If you do just an 'import' on a module (or 'import ... as ...'), then >> changes made to attrs on the imported module /will /be seen by othe >> modules that import it as well. I hope that is somewhat clear. ;) >> > > Read both links to effbot's article, they should make it clear why the > current behavior is the way it is. > I am confuse on the text above: "If you use the 'from import' system, changes made to attrs of the imported module /won't/ be seen by any other module that imported it. If you do just an 'import' on a module (or 'import ... as ...'), then changes made to attrs on the imported module /will /be seen by othe modules that import it as well. I hope that is somewhat clear. ;)" I had tried to simulate this situation: ------------ Module a----------- #!usr/bin/env ptyhon #Module a.py name = "a::name" ------------Module b------------ #usr/bin/env python #Module b.py form a import * while Ture: blah = rawinput("input something:") print a.name ------------Module c------------ #usr/bin/env python #Module c.py import a while Ture: blah = rawinput("input something:") print a.name ------------end------------------- when i excuted b.py,c.py and modified the attr name = "a::newname",but b.py and c.py were still output "a::name". what's the problem? does it the right way python takes? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jan 11 11:51:50 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Jan 2010 10:51:50 -0000 Subject: [Tutor] what is the equivalent function to strtok() in c++ References: <4B4AD7F2.5030007@ieee.org> Message-ID: "Stefan Behnel" wrote >> For more sophisticated functionality use the re module or a specialised >> parser. > > Just a quick note here, "specialised parser" might sound like something > that's hard to write. It's not. Good point. I meant one of the many existing parsing packages for specific purposes such as XML/HTML, csv, configfile etc - or pyparsing for more general purpose work. I did not mean to write a specialised parser from scratch, although occasionally that may be needed but usually not. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jan 11 11:57:51 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Jan 2010 10:57:51 -0000 Subject: [Tutor] Tutor Digest, Vol 71, Issue 28 References: <43563d821001110241w4e47dccat103b1518ef19cb3c@mail.gmail.com> Message-ID: "Make Twilight" wrote > I am confuse on the text above: > "If you use the 'from import' system, changes made to attrs of the > imported module /won't/ be seen by any other module that imported it. > If you do just an 'import' on a module (or 'import ... as ...'), then > changes made to attrs on the imported module /will /be seen by othe > modules that import it as well. I hope that is somewhat clear. ;)" > > I had tried to simulate this situation: > ------------ Module a----------- > #!usr/bin/env ptyhon > #Module a.py > name = "a::name" > > ------------Module b------------ > #usr/bin/env python > #Module b.py > form a import * > > while Ture: # True? > blah = rawinput("input something:") > print a.name This should not work because you have not imported "a" only "name" from a. This should therefore say print name > ------------Module c------------ > #usr/bin/env python > #Module c.py > import a > > while Ture: > blah = rawinput("input something:") > print a.name But this is OK. > when i excuted b.py,c.py and modified the attr name = "a::newname",but > b.py > and c.py were still output "a::name". How did you execute them? There is nothing to change the attributes here so how did you change them? If you altered the source code of a after the imports were run then the changes will not be seen. > what's the problem? > does it the right way python takes? I'm not sure there is a problem. It depends on how you are conducting the test and what you expect the answer to be. Alan G. From Vacs at petradiamonds.com Mon Jan 11 06:33:11 2010 From: Vacs at petradiamonds.com (VacStudent) Date: Mon, 11 Jan 2010 07:33:11 +0200 Subject: [Tutor] Tips Message-ID: I would like to get a python book, how and where to get one? Jappie Monele Mechanical Engineer Student Koffiefontein Blue Diamond Mine JV Petra Diamonds Group Management Office: Elizabeth House, 9 Castle Street, St. Helier, Jersey, JE4 2QP South African Office: Block 3, Silver Point Office Park, 22 Ealing Crescent, Bryanston, Johannesburg, 2052. Postal Address: PO Box 71007, Bryanston, 2021, South Africa. Koffiefontein Office: 1 Du Preezstreet, Koffiefontein, Free State Province, S.A, 9986. Postal Address: PostOfficeBox 80, Koffiefontein, 9986, South Africa. Office: +27 (53)205 5 Cell: +27 (0) 844428008 e mail: VacS at petradiamonds.com Web Address: www.petradiamonds.com This email is intended for the sole use of the addressee and may contain information that is confidential and privileged. Access to this email by anyone else is unauthorised. If you are not the intended recipient any disclosure, copying, distribution or any action taken or omitted to be taken in reliance on it is strictly prohibited and may be unlawful. If you have received this email in error, please notify us immediately by return of the email or telephone +27 11 467 6710 and destroy the original message. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 11 12:42:39 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jan 2010 06:42:39 -0500 Subject: [Tutor] composing one test suite from two test cases In-Reply-To: <20100111034431.40DEB141D1C19@cedar.isis.unc.edu> References: <20100111034431.40DEB141D1C19@cedar.isis.unc.edu> Message-ID: <1c2a2c591001110342w4c3c517ftaf9fab096a59f19e@mail.gmail.com> On Sun, Jan 10, 2010 at 10:44 PM, Tom Roche wrote: > > How to create a single unittest test suite class that runs all methods > from multiple TestCase classes? Why I ask: > > I'm trying to relearn TDD and learn Python by coding a simple app. > Currently the app has 2 simple functional classes, Pid and TallyPid, > and 2 very simple testcases, PidTests and TallyPidTests: > > http://www.unc.edu/~tr/courses/ENVR400/Pid.py > http://www.unc.edu/~tr/courses/ENVR400/PidTests.py > http://www.unc.edu/~tr/courses/ENVR400/Tally.py > http://www.unc.edu/~tr/courses/ENVR400/TallyPidTests.py > Before I continue, I'd like to create a single suite, in a separate > cfile file/module (e.g. AllTests.py), that will run both testcases > (PidTests.py and TallyPidTests.py). Unfortunately I have not been able > to do this! which surprises me, since creating such a suite in JUnit > is trivial. ?Can someone show me how to create this suite in python? > (FWIW the python version=2.5.2: downlevel, I know, but the box also > needs to run ArcGIS.) The supported way to do this is to create a test suite. There is an example here: http://docs.python.org/library/unittest.html#organizing-test-code In your case I think AllTests.py would look something like import unittest from PidTests import PidTests from TallyPidTests import TallyPidTests class AllTests(unittest.TestCase): def suite(): suite1 = unittest.TestLoader().loadTestsFromTestCase(PidTests) suite2 = unittest.TestLoader().loadTestsFromTestCase(TallyPidTests) return unittest.TestSuite([suite1, suite2]) However I don't recommend this style of organizing tests. I prefer using nose for test discovery, it saves the work of creating all the aggregating suites. I think py.test also has a test discovery component. In Python 2.7 the unittest module will finally have it's own test discovery. http://somethingaboutorange.com/mrl/projects/nose/0.11.1/finding_tests.html http://docs.python.org/dev/library/unittest.html#test-discovery Kent From kent37 at tds.net Mon Jan 11 12:46:15 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jan 2010 06:46:15 -0500 Subject: [Tutor] what is the equivalent function to strtok() in c++ In-Reply-To: References: Message-ID: <1c2a2c591001110346u658adc77xf4bc2ce60a6f1608@mail.gmail.com> On Mon, Jan 11, 2010 at 2:33 AM, sudhir prasad wrote: > hi, > what is the equivalent function to strtok() in c++, > what i need to do is to divide a line into different strings and store them > in different lists,and write them in to another file To split on a single character or a fixed sequence of characters use str.split(). To split on any one of a collection of characters use re.split(). Note that if you pass multiple characters to str.split(), the string is split on occurrences of the multiple character string, not on occurrences of any character in the string. So for multiple character arguments, str.split() is not equivalent to strtok(). Kent From kent37 at tds.net Mon Jan 11 12:48:12 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jan 2010 06:48:12 -0500 Subject: [Tutor] Tips In-Reply-To: References: Message-ID: <1c2a2c591001110348j31a44ec1w26e3d73cf9cc7635@mail.gmail.com> On Mon, Jan 11, 2010 at 12:33 AM, VacStudent wrote: > I would like to get a python book, how and where to get one? Amazon.com? Or lots of free resources online. Kent From garry.bettle at gmail.com Mon Jan 11 13:10:21 2010 From: garry.bettle at gmail.com (Garry Bettle) Date: Mon, 11 Jan 2010 13:10:21 +0100 Subject: [Tutor] Help with a Dictionary In-Reply-To: References: Message-ID: Many thanks to Alan Gauld, Gerard Flanagan, Lie Ryan and spir for your replies. All systems are go! Cheers, Garry From Tom_Roche at pobox.com Mon Jan 11 14:53:36 2010 From: Tom_Roche at pobox.com (Tom Roche) Date: Mon, 11 Jan 2010 08:53:36 -0500 (EST) Subject: [Tutor] composing one test suite from two test cases In-Reply-To: <1c2a2c591001110342w4c3c517ftaf9fab096a59f19e@mail.gmail.com> References: <1c2a2c591001110342w4c3c517ftaf9fab096a59f19e@mail.gmail.com> Message-ID: <20100111135336.BF4EF141D1C0F@cedar.isis.unc.edu> Tom Roche Sun, Jan 10, 2010 at 10:44 PM >> How to create a single unittest test suite class that runs all >> methods from multiple TestCase classes? Kent Johnson Mon, 11 Jan 2010 06:42:39 -0500 > The supported way to do this is to create a test suite. There is an > example here: > http://docs.python.org/library/unittest.html#organizing-test-code Yes, I saw that, in particular http://docs.python.org/library/unittest.html#organizing-test-code >>> unittest provides a TestLoader class that can be used to automate >>> the process of creating a test suite and populating it with >>> individual tests. For example, >>> suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase) >>> will create a test suite that will run >>> WidgetTestCase.testDefaultSize() and WidgetTestCase.testResize. ... >>> TestSuite instances can be added to a TestSuite just as TestCase >>> instances can be added to a TestSuite: >>> suite1 = module1.TheTestSuite() >>> suite2 = module2.TheTestSuite() >>> alltests = unittest.TestSuite([suite1, suite2]) but I couldn't get AllTests.py to run: I kept getting errors about "unbound method", "no such test method", class/instance problems, etc. Thanks to your assistance, I suspect my key faults were: * namespace: I was doing - import PidTests - import TallyPidTests instead of + from PidTests import PidTests + from TallyPidTests import TallyPidTests * not encapsulating the TestSuite-adding code in another suite() The only thing your code was missing was the main(), but that was easy to add. (The complete AllTests.py that runs for me follows my .sig) > However I don't recommend this style of organizing tests. I prefer > using nose for test discovery, it saves the work of creating all the > aggregating suites. I've heard of Nose and am planning to try it, but for now I thought I'd "do the simplest thing that could possibly work." > I think py.test also has a test discovery component. In Python 2.7 > the unittest module will finally have it's own test discovery. > http://somethingaboutorange.com/mrl/projects/nose/0.11.1/finding_tests.html > http://docs.python.org/dev/library/unittest.html#test-discovery Thanks again, Tom Roche ---AllTests.py follows--- import unittest from PidTests import PidTests from TallyPidTests import TallyPidTests class AllTests(unittest.TestCase): def suite(): suite1 = unittest.TestLoader().loadTestsFromTestCase(PidTests) suite2 = unittest.TestLoader().loadTestsFromTestCase(TallyPidTests) return unittest.TestSuite([suite1, suite2]) def main(): unittest.main() if __name__ == '__main__': main() From kent37 at tds.net Mon Jan 11 15:50:20 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jan 2010 09:50:20 -0500 Subject: [Tutor] composing one test suite from two test cases In-Reply-To: <20100111135336.BF4EF141D1C0F@cedar.isis.unc.edu> References: <1c2a2c591001110342w4c3c517ftaf9fab096a59f19e@mail.gmail.com> <20100111135336.BF4EF141D1C0F@cedar.isis.unc.edu> Message-ID: <1c2a2c591001110650v6bd0a366g99e5e8386da2b39b@mail.gmail.com> On Mon, Jan 11, 2010 at 8:53 AM, Tom Roche wrote: > Kent Johnson Mon, 11 Jan 2010 06:42:39 -0500 >> However I don't recommend this style of organizing tests. I prefer >> using nose for test discovery, it saves the work of creating all the >> aggregating suites. > > I've heard of Nose and am planning to try it, but for now I thought > I'd "do the simplest thing that could possibly work." That would be nose, IMO, because you don't have to write any code at all beyond your individual tests. Kent From grigor.kolev at gmail.com Mon Jan 11 16:55:49 2010 From: grigor.kolev at gmail.com (=?windows-1251?B?w/Do4+7w?=) Date: Mon, 11 Jan 2010 17:55:49 +0200 Subject: [Tutor] cxfreeze Message-ID: Hi. Can I make exe file from python script. With cxfreeze on Windows no have problem. But how make exe on ubuntu. -- ????? ???? ???? ???, ???? ???? ??????? ?? ???? ?? ???? ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From kvander11 at gmail.com Mon Jan 11 17:15:02 2010 From: kvander11 at gmail.com (Kirk Vander Meulen) Date: Mon, 11 Jan 2010 10:15:02 -0600 Subject: [Tutor] Tk help Message-ID: <2d0c08ca1001110815h7a9cef68sb6fcff3ad1dc6577@mail.gmail.com> Hi Alan, thanks for the reply and my apologies for not realizing there was a Tkinter-discuss group. After even more searching, this seems to be something weird with my version of Tkinter and/or my installation. I can eliminate this effect on my machine (linux, python 2.6) by explicitly creating and destroying a toplevel window after the askdirectory() dialog, as such: import tkFileDialog,tkMessageBox import Tkinter toplevel=Tkinter.Tk() addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?') print addDirectory theDirectory=tkFileDialog.askdirectory() toplevel.destroy() addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?') print addDirectory If I remove the "toplevel.destroy()" call, I get incorrect behavior. However, if I run the same program on my windows installation (python 2.5), I get correct behavior regardless of the presence of this destroy() command, which I'm pretty sure must be the expected behavior. I will look into my tkinter version and file a bug report if I convince myself my install's not goofy- I get the same behavior with my 3.1 installation on my linux box. Regarding teh print statements, I was using python 3 syntax but running python 2.6...I just like the 3 syntax better, sorry for the confusion. The extra prints were just me getting carried away with debugging, I love printing stuff. Kirk > "Kirk Vander Meulen" wrote > > > I'm working on a program partly to get the hang of gui programming. I'm > > a > > bit puzzled by the behavior of simple dialogs- I wonder why, in the > > following code, the second call to tkMessageBox.askyesno always returns > > 'False' (either 'yes' or 'no' return False!). If I take out the call to > > tkFileDialog.askdirectory(), the second call works as expected > > (yes->True,no->False). I would really appreciate if someone could take a > > look at this and tell me what I'm missing. Thanks, > > After converting the imports for Python 3 it worked perfectly for me > > >>> ================================ RESTART > >>> ================================ > >>> > True > True > H:/PROJECTS/Python/Tutor3 > True > H:/PROJECTS/Python/Tutor3 > >>> ================================ RESTART > >>> ================================ > >>> > > > import tkFileDialog,tkMessageBox > > addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?') > > print(addDirectory) > > theDirectory=tkFileDialog.askdirectory() > > print(addDirectory) > > Any reason why you print it a second time even though there has been no > change? > > > print(theDirectory) > > addDirectory=tkMessageBox.askyesno('a dialog','Add a directory?') > > print(addDirectory) > > print(theDirectory) > > And the same here? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Mon Jan 11 17:20:10 2010 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 11 Jan 2010 21:50:10 +0530 Subject: [Tutor] Array slices in python with negative step Message-ID: <5487b3061001110820g2ca86b29v586d2abcd678bb39@mail.gmail.com> Hello All, I am bit confuse how the slice works in case a negative step is supplied a = 'abcde' a[::-1] gives me edcba but [4:0:-1] gives me edcb while searching net I came accross something which said the following: If a negative stride is specified and the starting or stopping indices are omitted, they default to ``end of axis'' and ``beginning of axis'' respectively. In my case 4 is end of axis and 0 is begining of the axis so a[::-1] should be equivalent to [4:0:-1] but result which I get in both the cases does not validate. -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://singhvishwajeet.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From kamronb at gmail.com Mon Jan 11 17:10:33 2010 From: kamronb at gmail.com (Kamron Bennett) Date: Mon, 11 Jan 2010 11:10:33 -0500 Subject: [Tutor] Newbie Just Joining Message-ID: <785cdef91001110810j4a189670k3f2d5febdb721428@mail.gmail.com> I'd like to say hi and I'm a new member of this mailing list. -- "You'll never know if you don't go, you'll never shine if you don't glow" -Smash Mouth "All Star" -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Mon Jan 11 18:02:50 2010 From: denis.spir at free.fr (spir) Date: Mon, 11 Jan 2010 18:02:50 +0100 Subject: [Tutor] Array slices in python with negative step In-Reply-To: <5487b3061001110820g2ca86b29v586d2abcd678bb39@mail.gmail.com> References: <5487b3061001110820g2ca86b29v586d2abcd678bb39@mail.gmail.com> Message-ID: <20100111180250.1660bd38@o> On Mon, 11 Jan 2010 21:50:10 +0530 vishwajeet singh wrote: > Hello All, > > I am bit confuse how the slice works in case a negative step is supplied > a = 'abcde' > a[::-1] gives me edcba > > but [4:0:-1] gives me edcb > > while searching net I came accross something which said the following: > > If a negative stride is specified and the starting or stopping indices are > omitted, they default to ``end of axis'' and ``beginning of axis'' > respectively. > In my case 4 is end of axis and 0 is begining of the axis so a[::-1] should > be equivalent to [4:0:-1] but result which I get in both the cases does not > validate. Your interpretation is wrong. In your case, 4 is start index, 0 is end index (as obviously shown by the result you get). Step -1 lets you step backwards, but this does not change the fact that the end-index is the second argument of the slice, right? Now, python work with (right-side) half-open intervals, meaning that the second border is excluded (s[0:4] would return "abcd"). Which means in your case you won't get a[0] in the result. Hope I'm clear... It can be a bit misleading at start but, as it's consistent, once you get used to it all works fine ;-) Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From dextrous85 at gmail.com Mon Jan 11 18:17:59 2010 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 11 Jan 2010 22:47:59 +0530 Subject: [Tutor] Array slices in python with negative step In-Reply-To: <20100111180250.1660bd38@o> References: <5487b3061001110820g2ca86b29v586d2abcd678bb39@mail.gmail.com> <20100111180250.1660bd38@o> Message-ID: <5487b3061001110917t4fbe7bf7k11e00ded99f9b19c@mail.gmail.com> On Mon, Jan 11, 2010 at 10:32 PM, spir wrote: > On Mon, 11 Jan 2010 21:50:10 +0530 > vishwajeet singh wrote: > > > Hello All, > > > > I am bit confuse how the slice works in case a negative step is supplied > > a = 'abcde' > > a[::-1] gives me edcba > > > > but [4:0:-1] gives me edcb > > > > while searching net I came accross something which said the following: > > > > If a negative stride is specified and the starting or stopping indices > are > > omitted, they default to ``end of axis'' and ``beginning of axis'' > > respectively. > > In my case 4 is end of axis and 0 is begining of the axis so a[::-1] > should > > be equivalent to [4:0:-1] but result which I get in both the cases does > not > > validate. > > Your interpretation is wrong. In your case, 4 is start index, 0 is end > index (as obviously shown by the result you get). Step -1 lets you step > backwards, but this does not change the fact that the end-index is the > second argument of the slice, right? Now, python work with (right-side) > half-open intervals, meaning that the second border is excluded (s[0:4] > would return "abcd"). Which means in your case you won't get a[0] in the > result. Hope I'm clear... It can be a bit misleading at start but, as it's > consistent, once you get used to it all works fine ;-) > Thanks for your response but I am still not clear; can you show me the equivalent of [::-1] in terms actually specifying start-index, end-index which gives me reverse of the given arrary. > > 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 > -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://singhvishwajeet.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From jecarnell at saintfrancis.com Mon Jan 11 19:20:50 2010 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Mon, 11 Jan 2010 12:20:50 -0600 Subject: [Tutor] Numpy unexpected result: subtraction of cell values Message-ID: I'm sure this is easy, but I am having a difficult time finding the right search terms to find it on the Internet. Any help much appreciated. 3 dimensional array(x,y,rgb) which is a PIL image into a numpy array using 'asarray' function. I want to subtract the Red Value in an array cell from a neighboring Red Value cell. >>> pictArray[39][4] #pixel at 39 4 array([150, 140, 120], dtype=unint8) >>> pictArray[39][5] #pixel at 39 5 array([160, 150, 120], dtype=unint8) >>> pictArray[39][4][0] #red pixel 150 >>> pictArray[39][5[0] #neighboring red pixel 160 >>> pictArray[39][4] - pictArray[39][5] ) 246 # <--------------- ??? vs -10 How do I get the number -10? Does this have to do with the dtype? Thanks in advance, James Carnell -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Mon Jan 11 19:42:11 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 11 Jan 2010 12:42:11 -0600 Subject: [Tutor] Newbie Just Joining In-Reply-To: <785cdef91001110810j4a189670k3f2d5febdb721428@mail.gmail.com> References: <785cdef91001110810j4a189670k3f2d5febdb721428@mail.gmail.com> Message-ID: Hey, welcome to the list! No probemas so far? On 1/11/10, Kamron Bennett wrote: > I'd like to say hi and I'm a new member of this mailing list. > > -- > "You'll never know if you don't go, you'll never shine if you don't glow" > -Smash Mouth "All Star" > -- Sent from my mobile device From marc.tompkins at gmail.com Mon Jan 11 19:47:38 2010 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 11 Jan 2010 10:47:38 -0800 Subject: [Tutor] Numpy unexpected result: subtraction of cell values In-Reply-To: References: Message-ID: <40af687b1001111047k7a9b21c1w1e579a20dd3dccd6@mail.gmail.com> On Mon, Jan 11, 2010 at 10:20 AM, Carnell, James E < jecarnell at saintfrancis.com> wrote: > > I'm sure this is easy, but I am having a difficult time finding the right > search terms to find it on the Internet. Any help much appreciated. > > 3 dimensional array(x,y,rgb) which is a PIL image into a numpy array using > 'asarray' function. > > I want to subtract the Red Value in an array cell from a neighboring Red > Value cell. > > >>> pictArray[39][4] #pixel at 39 4 > array([150, 140, 120], dtype=unint8) > > >>> pictArray[39][5] #pixel at 39 5 > array([160, 150, 120], dtype=unint8) > > >>> pictArray[39][4][0] #red pixel > 150 > > >>> pictArray[39][5[0] #neighboring red pixel > 160 > > >>> pictArray[39][4] - pictArray[39][5] ) > 246 # <--------------- ??? vs -10 > > How do I get the number -10? Does this have to do with the dtype? > It looks like you're re-typing from your terminal window into your Compose window... your life (and ours!) will be simpler if you just cut and paste. There are a couple of weirdnesses in what you posted - unmatched parentheses and such - that are probably just typos. Anyway, assuming that what you've posted IS the same as what you're trying to do, in your last line you're trying to subtract one entire cell from another (instead of just the red value of one from the red value of the other.) I don't know where the number 246 came from, but I'm not really sure what number I would have expected anyway (matrix algebra was a LONG time ago, I'm afraid!) I think what you want to do is >>> pictArray[39][4][0] - pictArray[39][5][0] I'm not in a place where I can test, but I think that should do it. --- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jecarnell at saintfrancis.com Mon Jan 11 20:02:03 2010 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Mon, 11 Jan 2010 13:02:03 -0600 Subject: [Tutor] Numpy unexpected result: subtraction of cell values Message-ID: > > I'm sure this is easy, but I am having a difficult time finding the > right search terms to find it on the Internet. Any help much > appreciated. > > 3 dimensional array(x,y,rgb) which is a PIL image into a numpy array > using 'asarray' function. > > I want to subtract the Red Value in an array cell from a neighboring > Red Value cell. > > >>> pictArray[39][4] #pixel at 39 4 > array([150, 140, 120], dtype=unint8) > > >>> pictArray[39][5] #pixel at 39 5 > array([160, 150, 120], dtype=unint8) > > >>> pictArray[39][4][0] #red pixel > 150 > > >>> pictArray[39][5[0] #neighboring red pixel > 160 > > >>> pictArray[39][4][0] - pictArray[39][5][0] > 246 # <--------------- ??? vs -10 > > How do I get the number -10? Does this have to do with the dtype? > It looks like you're re-typing from your terminal window into your Compose window... your life (and ours!) will be simpler if you just cut and paste. - sorry I am at work and due to security reasons can't plug a thumb drive in for copying copde from my laptop. I have corrected the values above. - pictArray[39][4][0] - pictArray[39][5][0] = 246 is where I am getting stuck -------------- next part -------------- An HTML attachment was scrubbed... URL: From michaelsprayberry at gmail.com Mon Jan 11 20:26:12 2010 From: michaelsprayberry at gmail.com (Michael Sprayberry) Date: Mon, 11 Jan 2010 14:26:12 -0500 Subject: [Tutor] Array slices in python with negative step Message-ID: <1263237972.3010.10.camel@msprayberry-laptop> > > Hello All, > > > > I am bit confuse how the slice works in case a negative step is supplied > > a = 'abcde' > > a[::-1] gives me edcba > > > > but [4:0:-1] gives me edcb > > > > while searching net I came accross something which said the following: > > > > If a negative stride is specified and the starting or stopping indices > are > > omitted, they default to ``end of axis'' and ``beginning of axis'' > > respectively. > > In my case 4 is end of axis and 0 is begining of the axis so a[::-1] > should > > be equivalent to [4:0:-1] but result which I get in both the cases does > not > > validate. > > Your interpretation is wrong. In your case, 4 is start index, 0 is end > index (as obviously shown by the result you get). Step -1 lets you step > backwards, but this does not change the fact that the end-index is the > second argument of the slice, right? Now, python work with (right-side) > half-open intervals, meaning that the second border is excluded (s[0:4] > would return "abcd"). Which means in your case you won't get a[0] in the > result. Hope I'm clear... It can be a bit misleading at start but, as it's > consistent, once you get used to it all works fine ;-) > Thanks for your response but I am still not clear; can you show me the equivalent of [::-1] in terms actually specifying start-index, end-index which gives me reverse of the given arrary. Dennis, I hope this clears up your question. a[begin index: end index: step] a = ['a','b','c','d','e'] there are 5 indexes 0 through 4 if you a[4:0:-1] a = ['e','d','c','b'] because you stopped at index 0 but did not include it a[::-1] uses the last index going back to and including index 0 as the following example shows >>> a =[1,2,3,4,5,6] >>> b = a[5:0:-1] >>> b [6, 5, 4, 3, 2] >>> b = a[5:-1:-1] >>> b [] >>> a [1, 2, 3, 4, 5, 6] >>> b = a[5::-1] >>> b [6, 5, 4, 3, 2, 1] >>> Like I said I hope that clears it up a little Michael From alan.gauld at btinternet.com Mon Jan 11 20:46:09 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Jan 2010 19:46:09 -0000 Subject: [Tutor] Array slices in python with negative step References: <5487b3061001110820g2ca86b29v586d2abcd678bb39@mail.gmail.com><20100111180250.1660bd38@o> <5487b3061001110917t4fbe7bf7k11e00ded99f9b19c@mail.gmail.com> Message-ID: "vishwajeet singh" wrote > Thanks for your response but I am still not clear; can you show me the > equivalent of [::-1] in terms actually specifying start-index, end-index > which gives me reverse of the given arrary. I don't think you can, you must use the empty value. In theory you could use -1 except of course -1 refers to the 'e'... Its a slight anomoly due to the use of negative indexing. You can do: 'abcde'[0:5] and get the same as [0:] But you cannot put any valid value for x in 'abcde[4 : x :-1] that gets you the full string. You need to use [4::-1] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Mon Jan 11 21:01:38 2010 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 11 Jan 2010 12:01:38 -0800 Subject: [Tutor] Numpy unexpected result: subtraction of cell values In-Reply-To: References: Message-ID: <40af687b1001111201v50167fas34117f1c32c29a5@mail.gmail.com> On Mon, Jan 11, 2010 at 11:02 AM, Carnell, James E < jecarnell at saintfrancis.com> wrote: > > > > > I'm sure this is easy, but I am having a difficult time finding the > > right search terms to find it on the Internet. Any help much > > appreciated. > > > > 3 dimensional array(x,y,rgb) which is a PIL image into a numpy array > > using 'asarray' function. > > > > I want to subtract the Red Value in an array cell from a neighboring > > Red Value cell. > > > > >>> pictArray[39][4] #pixel at 39 4 > > array([150, 140, 120], dtype=unint8) > > > > >>> pictArray[39][5] #pixel at 39 5 > > array([160, 150, 120], dtype=unint8) > > > > >>> pictArray[39][4][0] #red pixel > > 150 > > > > >>> pictArray[39][5[0] #neighboring red pixel > > 160 > > > > >>> pictArray[39][4][0] - pictArray[39][5][0] > > 246 # <--------------- ??? vs -10 > > > > How do I get the number -10? Does this have to do with the dtype? > > > > It looks like you're re-typing from your terminal window into your Compose > window... your life (and ours!) will be simpler if you just cut and paste. > > - sorry I am at work and due to security reasons can't plug a > thumb drive in for copying copde from my laptop. I have corrected the values > above. > > - pictArray[39][4][0] - pictArray[39][5][0] = 246 is where I am > getting stuck > > > Silly of me not to have noticed, but those are UNsigned 8-bit integers, which means values 0-255. -10 wraps around to 246. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Mon Jan 11 21:07:31 2010 From: dextrous85 at gmail.com (vishwajeet singh) Date: Tue, 12 Jan 2010 01:37:31 +0530 Subject: [Tutor] Array slices in python with negative step In-Reply-To: References: <5487b3061001110820g2ca86b29v586d2abcd678bb39@mail.gmail.com> <20100111180250.1660bd38@o> <5487b3061001110917t4fbe7bf7k11e00ded99f9b19c@mail.gmail.com> Message-ID: <5487b3061001111207l5505b45rc04d1bcc00fe421d@mail.gmail.com> On Tue, Jan 12, 2010 at 1:16 AM, Alan Gauld wrote: > > "vishwajeet singh" wrote > > Thanks for your response but I am still not clear; can you show me the >> equivalent of [::-1] in terms actually specifying start-index, end-index >> which gives me reverse of the given arrary. >> > > I don't think you can, you must use the empty value. > > In theory you could use -1 except of course -1 refers to the 'e'... > > Its a slight anomoly due to the use of negative indexing. You > can do: > > 'abcde'[0:5] > > and get the same as [0:] > > But you cannot put any valid value for x in > > 'abcde[4 : x :-1] > > that gets you the full string. You need to use [4::-1] > > HTH, > > Thanks Alan and Micheal that surely cleard my doubts. -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://singhvishwajeet.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 11 21:17:17 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jan 2010 15:17:17 -0500 Subject: [Tutor] Numpy unexpected result: subtraction of cell values In-Reply-To: References: Message-ID: <1c2a2c591001111217j7dd30b89r8c279708a22efb5@mail.gmail.com> On Mon, Jan 11, 2010 at 2:02 PM, Carnell, James E wrote: >> I want to subtract the Red Value in an array cell from a neighboring >> Red Value cell. >> >> >>> pictArray[39][4]??????????????????? #pixel at 39 4 >> array([150, 140, 120], dtype=unint8) >> >> >>> pictArray[39][5]??????????????????? #pixel at 39 5 >> array([160, 150, 120], dtype=unint8) >> >> >>> pictArray[39][4][0]???????????????? #red pixel >> 150 >> >> >>> pictArray[39][5[0]????????????????? #neighboring red pixel >> 160 >> >> >>> pictArray[39][4][0] - pictArray[39][5][0] >> 246? # <---------------? ???? vs -10 >> >> How do I get the number -10? Does this have to do with the dtype? > ??????? - pictArray[39][4][0] - pictArray[39][5][0] = 246? is where I am > getting stuck I guess the subtraction is happening on unsigned values, which can't represent -10. Try int(pictArray[39][4][0]) - int(pictArray[39][5][0]) Kent From eike.welk at gmx.net Tue Jan 12 01:24:24 2010 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 12 Jan 2010 01:24:24 +0100 Subject: [Tutor] cxfreeze In-Reply-To: References: Message-ID: <201001120124.24515.eike.welk@gmx.net> Hello ??????! On Monday January 11 2010 16:55:49 ?????? wrote: > Hi. Can I make exe file from python script. With cxfreeze on Windows no > have problem. But how make exe on ubuntu. > On Linux programs are distributed as so called packages. A program called the package manager opens these packages and installs the programs. Ubuntu uses the Debian package format. These packages have the extension ".deb". 1. Creating DEBs. This website seems to give a good overview (I have Suse which uses RPM packages, so I have no real knowledge about it.): https://help.ubuntu.com/community/PythonRecipes/DebianPackage An especially interesting tool seems to be this one. It creates DEBs from Python sources with a "setup.py" script, the next alternative which I'll describe: http://pypi.python.org/pypi/stdeb/ 2. Distributing sources An other alternative is distributing the sources with a "setup.py" script. Pythons distutils library then installs the program in the right place. Distutils can also create RPMs (which are the packages for Redhat, Suse and Mandriva). Creating a "setup.py" script is described here (unfortunately quite confusing): http://docs.python.org/distutils/index.html#distutils-index The user would then extract the files from the archive, cd into the extracted directory and run "python setup.py install". Small overview of frequently used commands of the "setup.py" script. The command line generally is: python setup.py [--dry-run] Some commands are: sdist : create source distribution. (*.tar.gz or *.zip) bdist_wininst : create Windows executable installer (binary distribution). (*.exe) bdist_rpm : create binary RPM distribution (*.rpm) install : install the software --dry-run : test the operation without doing anything also useful: python setup.py --help python setup.py --help-commands 3. Run the Windows EXE on Linux. Wine is a set of compatibility libraries, that allow the execution of Windows programs on Linux. However Wine is very big and it often doesn't work very well, but it might be worth a try. Steps are: - Start the package manager. - Find Wine in the gigantic list of available packages. - Select Wine and click on the "Install" button. - Click the EXE file to run it. Eike. From grigor.kolev at gmail.com Tue Jan 12 08:41:00 2010 From: grigor.kolev at gmail.com (=?windows-1251?B?w/Do4+7w?=) Date: Tue, 12 Jan 2010 09:41:00 +0200 Subject: [Tutor] cxfreeze In-Reply-To: <201001120124.24515.eike.welk@gmx.net> References: <201001120124.24515.eike.welk@gmx.net> Message-ID: 2010/1/12 Eike Welk > > Hello ??????! > > On Monday January 11 2010 16:55:49 ?????? wrote: > > Hi. Can I make exe file from python script. With cxfreeze on Windows no > > ?have problem. But how make exe on ubuntu. > > > > On Linux programs are distributed as so called packages. A program called the > package manager opens these packages and installs the programs. Ubuntu uses > the Debian package format. These packages have the extension ".deb". > > 1. Creating DEBs. > This website seems to give a good overview (I have Suse which uses RPM > packages, so I have no real knowledge about it.): > https://help.ubuntu.com/community/PythonRecipes/DebianPackage > > An especially interesting tool seems to be this one. It creates DEBs from > Python sources with a "setup.py" script, the next alternative which I'll > describe: > http://pypi.python.org/pypi/stdeb/ > > > 2. Distributing sources > An other alternative is distributing the sources with a "setup.py" script. > Pythons distutils library then installs the program in the right place. > Distutils can also create RPMs (which are the packages for Redhat, Suse and > Mandriva). Creating a "setup.py" script is described here (unfortunately quite > confusing): > http://docs.python.org/distutils/index.html#distutils-index > > The user would then extract the files from the archive, cd into the extracted > directory and run "python setup.py install". > > Small overview of frequently used commands of the "setup.py" script. The > command line generally is: > ? ?python setup.py ?[--dry-run] > > Some commands are: > ? ?sdist ? ? ? ? : create source distribution. (*.tar.gz or *.zip) > ? ?bdist_wininst : create Windows executable installer (binary > ? ? ? ? ? ? ? ? ? ?distribution). (*.exe) > ? ?bdist_rpm ? ? : create binary RPM distribution (*.rpm) > ? ?install ? ? ? : install the software > ? ?--dry-run ? ? : test the operation without doing anything > > also useful: > ? ?python setup.py --help > ? ?python setup.py --help-commands > > > 3. Run the Windows EXE on Linux. > Wine is a set of compatibility libraries, that allow the execution of Windows > programs on Linux. However Wine is very big and it often doesn't work very > well, but it might be worth a try. Steps are: > - Start the package manager. > - Find Wine in the gigantic list of available packages. > - Select Wine and click on the "Install" button. > - Click the EXE file to run it. > > > > Eike. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor At home I use Ubuntu. I know how install programs. If I make program for Linux. Linux users look in README file and I can write there what you need. But if useing GTK+ you can not start this program in the Windows. You must be install additional modules and Python. However. Thanks for answers -- ????? ???? ???? ???, ???? ???? ??????? ?? ???? ?? ???? ! From ph4nut at gmail.com Tue Jan 12 15:39:11 2010 From: ph4nut at gmail.com (Make Twilight) Date: Tue, 12 Jan 2010 22:39:11 +0800 Subject: [Tutor] samples on sort method of sequence object. Message-ID: <43563d821001120639m856bf5fy59e156dca9bf510c@mail.gmail.com> Hi,there: The document of Python.org[http://docs.python.org/library/stdtypes.html] says that: ------------------------------------------------------------------------------------------------------------------ s.sort([cmp[, key[, reverse]]]) 8. The sort() method takes optional arguments for controlling the comparisons. cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None. key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None. reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed. -------------------------------------------------------------------------------------------------------------------- I can understand how to use parameters of cmp and reverse,except the key parameter... Would anyone give me an example of using sort method with key parameter? Thanks! -- ph4nut at gmail.com Mak Twilight From hugo.yoshi at gmail.com Tue Jan 12 18:00:06 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 12 Jan 2010 18:00:06 +0100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: <43563d821001120639m856bf5fy59e156dca9bf510c@mail.gmail.com> References: <43563d821001120639m856bf5fy59e156dca9bf510c@mail.gmail.com> Message-ID: <29179d161001120900p17553825q72387a5d8d390204@mail.gmail.com> On Tue, Jan 12, 2010 at 3:39 PM, Make Twilight wrote: > Hi,there: > ?The document of > Python.org[http://docs.python.org/library/stdtypes.html] says that: > > > > ?I can understand how to use parameters of cmp and reverse,except the > key parameter... > ?Would anyone give me an example of using sort method with key parameter? > ?Thanks! > key has essentially the same purpose as cmp, but it works more efficiently because it only calls the key function once for each value in the sequence. A simple though maybe not very useful example could be sorting lists of integers in such a way that the list with the lowest sum comes first: >>> seqs = [(2, 0, 0), (3, 5, 5), (1, 100, 100)] >>> seqs.sort() >>> seqs [(1, 100, 100), (2, 0, 0), (3, 5, 5)] >>> seqs.sort(key=sum) >>> seqs [(2, 0, 0), (3, 5, 5), (1, 100, 100)] the sort function calls the key function sum(s) for every s in sequence, then sorts the list using the result of that call. An equivalent example using the cmp function could be this one: >>> seqs.sort(cmp=lambda x, y: cmp(sum(x), sum(y)) Another example given by the docs is using the str.lower function. Here it is in action: >>> s = list("A string WitH Some Capitals") >>> s.sort(key=str.lower) >>> s [' ', ' ', ' ', ' ', 'A', 'a', 'a', 'C', 'e', 'g', 'H', 'i', 'i', 'i', 'l', 'm', 'n', 'o', 'p', 'r', 's', 'S', 's', 't', 't', 't', 'W'] >>> s.sort() >>> s [' ', ' ', ' ', ' ', 'A', 'C', 'H', 'S', 'W', 'a', 'a', 'e', 'g', 'i', 'i', 'i', 'l', 'm', 'n', 'o', 'p', 'r', 's', 's', 't', 't', 't'] Normally, when sorting a string, capital letters come before regular ones. With the key() argument, the sorting is done between the lowered versions of each letter, so the sort becomes case insensitive. Note that this doesn't actually change our string, it only changes what exactly is used for our comparisons. Again, same sort using the cmp argument: s.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()) Hugo From kent37 at tds.net Tue Jan 12 19:53:56 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Jan 2010 13:53:56 -0500 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: <43563d821001120639m856bf5fy59e156dca9bf510c@mail.gmail.com> References: <43563d821001120639m856bf5fy59e156dca9bf510c@mail.gmail.com> Message-ID: <1c2a2c591001121053s35f4d9bfubeb72559403d613d@mail.gmail.com> On Tue, Jan 12, 2010 at 9:39 AM, Make Twilight wrote: > ?I can understand how to use parameters of cmp and reverse,except the > key parameter... > ?Would anyone give me an example of using sort method with key parameter? http://personalpages.tds.net/~kent37/kk/00007.html Kent From michael at arpsorensen.dk Wed Jan 13 10:13:30 2010 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Wed, 13 Jan 2010 10:13:30 +0100 Subject: [Tutor] Kill a socket doing a recvfrom Message-ID: <1618521001130113t1f5c199fkdc0a26257d82fe76@mail.gmail.com> Greetings my masters. How do I kill a socket which is locked in a recvfrom? My effort to kill it failed. The socket is running in its own thread. Any bright ideas? Med venlig hilsen/Kind regards Michael B. Arp S?rensen Programmer / BOFH "If you want to enter my network while I'm out, you can find my SSH-key under my mouse mat" - Michael Bernhard Arp S?rensen -------------- next part -------------- An HTML attachment was scrubbed... URL: From ljmamoreira at gmail.com Wed Jan 13 11:42:26 2010 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Wed, 13 Jan 2010 10:42:26 +0000 Subject: [Tutor] help using f2py Message-ID: <201001131042.26586.ljmamoreira@gmail.com> Hello! I posted this question on the f2py list but since I haven't got any answers (yet), I thought I'd try my luck here. I'm having a hard time wrapping a fortran subroutine into a python module. The problem seems to be related to having a subroutine argument to the fortran subroutine. A simple version of my problem is the following. Consider a subroutine (sub), which takes as argument a real array (x), the dimension (n) of that array and another subroutine (other_sub) that is to be called by sub : file sub.f95 ---------------------------------------------- subroutine sub(x,other_sub,n) integer::n real, dimension(n)::x external other_sub call other_sub(x) end subroutine sub ---------------------------------------------- The gnu fortran compiler compiles this snippet without any warnings or errors. However, when I run it through f2py, all I get is a bunch of errors (see below the error output). I'm not sure if this has any relevance but if I change argument x to a real scalar (instead of an array), then f2py executes fine and the python module is generated. I just don't get it! Can anybody explain me what I am doing wrong, please? Thanks in advance. Jose Amoreira Part of the output of f2py -m sub -c sub.f95: ---------------------------------------------- creating /tmp/tmpyHp76U/tmp creating /tmp/tmpyHp76U/tmp/tmpyHp76U creating /tmp/tmpyHp76U/tmp/tmpyHp76U/src.linux-x86_64-2.6 compile options: '-I/tmp/tmpyHp76U/src.linux-x86_64-2.6 - I/usr/lib64/python2.6/site-packages/numpy/core/include - I/usr/include/python2.6 -c' gcc: /tmp/tmpyHp76U/src.linux-x86_64-2.6/fortranobject.c gcc: /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c: In function ?cb_other_sub_in_sub__user__routines?: /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: ?n? undeclared (first use in this function) /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: (Each undeclared identifier is reported only once /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: for each function it appears in.) /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c: In function ?cb_other_sub_in_sub__user__routines?: /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: ?n? undeclared (first use in this function) /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: (Each undeclared identifier is reported only once /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c:306: error: for each function it appears in.) error: Command "gcc -pthread -fno-strict-aliasing -DNDEBUG -fmessage-length=0 -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector -funwind-tables - fasynchronous-unwind-tables -g -fwrapv -fPIC -I/tmp/tmpyHp76U/src.linux- x86_64-2.6 -I/usr/lib64/python2.6/site-packages/numpy/core/include - I/usr/include/python2.6 -c /tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.c -o /tmp/tmpyHp76U/tmp/tmpyHp76U/src.linux-x86_64-2.6/submodule.o" failed with exit status 1 ------------------------------------- From fomcl at yahoo.com Wed Jan 13 13:51:30 2010 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 13 Jan 2010 04:51:30 -0800 (PST) Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: <1c2a2c591001121053s35f4d9bfubeb72559403d613d@mail.gmail.com> Message-ID: <139466.16040.qm@web110708.mail.gq1.yahoo.com> Interesting. Can this also be used to make sorting of alphanumerical list items in a 'numerical' way easier? E.g.: >>> x ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', 'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', 'var_12'] >>> x.sort() >>> x ['var_0', 'var_1', 'var_10', 'var_11', 'var_12', 'var_13', 'var_14', 'var_2', 'var_3', 'var_4', 'var_5', 'var_6', 'var_7', 'var_8', 'var_9'] >>> ? This clearly does not give the desired result. I once solved this by making a dictionary of which the keys are zfilled versions of the list items (e.g. var_01, etc), then sort the keys, get the dictionary values in the right order, etc. It seemed a cumbersome way. Isn't there an easier way to sort x? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the face of ambiguity, refuse the temptation to guess. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- On Tue, 1/12/10, Kent Johnson wrote: From: Kent Johnson Subject: Re: [Tutor] samples on sort method of sequence object. To: "Make Twilight" Cc: tutor at python.org Date: Tuesday, January 12, 2010, 7:53 PM On Tue, Jan 12, 2010 at 9:39 AM, Make Twilight wrote: > ?I can understand how to use parameters of cmp and reverse,except the > key parameter... > ?Would anyone give me an example of using sort method with key parameter? http://personalpages.tds.net/~kent37/kk/00007.html Kent _______________________________________________ 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 Wed Jan 13 14:13:24 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 13 Jan 2010 14:13:24 +0100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: <139466.16040.qm@web110708.mail.gq1.yahoo.com> References: <1c2a2c591001121053s35f4d9bfubeb72559403d613d@mail.gmail.com> <139466.16040.qm@web110708.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam, 13.01.2010 13:51: > Interesting. Can this also be used to make sorting of alphanumerical list items in a 'numerical' way easier? E.g.: >>>> x > ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', 'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', 'var_12'] >>>> x.sort() >>>> x > ['var_0', 'var_1', 'var_10', 'var_11', 'var_12', 'var_13', 'var_14', 'var_2', 'var_3', 'var_4', 'var_5', 'var_6', 'var_7', 'var_8', 'var_9'] > > This clearly does not give the desired result. I once solved this by making a dictionary of which the keys are zfilled versions of the list items (e.g. var_01, etc), then sort the keys, get the dictionary values in the right order, etc. It seemed a cumbersome way. Isn't there an easier way to sort x? x.sort(key = lambda name: int(name.split('_')[-1])) Stefan From sander.sweers at gmail.com Wed Jan 13 14:14:30 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 13 Jan 2010 14:14:30 +0100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: <139466.16040.qm@web110708.mail.gq1.yahoo.com> References: <1c2a2c591001121053s35f4d9bfubeb72559403d613d@mail.gmail.com> <139466.16040.qm@web110708.mail.gq1.yahoo.com> Message-ID: 2010/1/13 Albert-Jan Roskam > > Interesting. Can this also be used to make sorting of alphanumerical list items in a 'numerical' way easier? > >>> x > ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', 'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', 'var_12'] Yes. >>> x ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', 'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', 'var_12'] >>> sorted(x, key=lamda x: int(x.strip('var_'))) SyntaxError: invalid syntax >>> sorted(x, key=lambda x: int(x.strip('var_'))) ['var_0', 'var_1', 'var_2', 'var_3', 'var_4', 'var_5', 'var_6', 'var_7', 'var_8', 'var_9', 'var_10', 'var_11', 'var_12', 'var_13', 'var_14'] Greets Sander From fomcl at yahoo.com Wed Jan 13 14:32:58 2010 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 13 Jan 2010 05:32:58 -0800 (PST) Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: Message-ID: <458754.55990.qm@web110712.mail.gq1.yahoo.com> Very concise == neat solutions. Yummy.?;-) Thanks for your replies! Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the face of ambiguity, refuse the temptation to guess. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- On Wed, 1/13/10, Sander Sweers wrote: From: Sander Sweers Subject: Re: [Tutor] samples on sort method of sequence object. To: "Albert-Jan Roskam" Cc: "*tutor python" Date: Wednesday, January 13, 2010, 2:14 PM 2010/1/13 Albert-Jan Roskam > > Interesting. Can this also be used to make sorting of alphanumerical list items in a 'numerical' way easier? > >>> x > ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', 'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', 'var_12'] Yes. >>> x ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', 'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', 'var_12'] >>> sorted(x, key=lamda x: int(x.strip('var_'))) SyntaxError: invalid syntax >>> sorted(x, key=lambda x: int(x.strip('var_'))) ['var_0', 'var_1', 'var_2', 'var_3', 'var_4', 'var_5', 'var_6', 'var_7', 'var_8', 'var_9', 'var_10', 'var_11', 'var_12', 'var_13', 'var_14'] Greets Sander -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Wed Jan 13 15:25:06 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 13 Jan 2010 15:25:06 +0100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: <458754.55990.qm@web110712.mail.gq1.yahoo.com> References: <458754.55990.qm@web110712.mail.gq1.yahoo.com> Message-ID: <29179d161001130625x15163afh2d692df90883b980@mail.gmail.com> I should note that this doesn't solve the general case of mixed numeric/alphabetic sorting: >>> a = ['a_1', 'a_2', 'a_3', 'a_4', 'a_10', 'b_1', 'b_2', 'b_3', 'b_4', 'b_10'] >>> a.sort(key=lambda x: int(x.split('_')[-1])) >>> a ['a_1', 'b_1', 'a_2', 'b_2', 'a_3', 'b_3', 'a_4', 'b_4', 'a_10', 'b_10'] It only works if the alphabetic part of the string is the same everywhere, and it doesn't work with a collection where some numbers appear before, some after, etc. Here is my solution for the general case: from itertools import groupby def alphanum_key(string): t = [] for isdigit, group in groupby(string, str.isdigit): group = ''.join(group) t.append(int(group) if isdigit else group) return t or, in a oneliner: >>> alphanum_key = lambda x: tuple((int(''.join(g)) if k else ''.join(g)) for k, g in groupby(x, str.isdigit)) that's equivalent, but not very readable. It works by grouping sequences of numbers and not numbers together, and treating the number sequences as integers rather than strings. >>> a = ['0a', '1a', '10a', 'a1', 'a2', 'a10', 'a11', 'b2', 'b3', 'b20'] >>> a.sort() >>> a ['0a', '10a', '1a', 'a1', 'a10', 'a11', 'a2', 'b2', 'b20', 'b3'] >>> # regular sort messes up because 'a10' is alphabetically before 'a2'. now with alphanumeric sort: >>> a.sort(key=alphanum_key) >>> a ['0a', '1a', '10a', 'a1', 'a2', 'a10', 'a11', 'b2', 'b3', 'b20'] Hugo On Wed, Jan 13, 2010 at 2:32 PM, Albert-Jan Roskam wrote: > Very concise == neat solutions. Yummy. ;-) Thanks for your replies! > > > Cheers!! > Albert-Jan > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > In the face of ambiguity, refuse the temptation to guess. > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > --- On *Wed, 1/13/10, Sander Sweers * wrote: > > > From: Sander Sweers > > Subject: Re: [Tutor] samples on sort method of sequence object. > To: "Albert-Jan Roskam" > Cc: "*tutor python" > Date: Wednesday, January 13, 2010, 2:14 PM > > > 2010/1/13 Albert-Jan Roskam > > > > > > Interesting. Can this also be used to make sorting of alphanumerical list > items in a 'numerical' way easier? > > >>> x > > ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', > 'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', 'var_12'] > > Yes. > >>> x > ['var_0', 'var_13', 'var_11', 'var_9', 'var_4', 'var_1', 'var_5', > 'var_6', 'var_7', 'var_14', 'var_2', 'var_3', 'var_8', 'var_10', > 'var_12'] > >>> sorted(x, key=lamda x: int(x.strip('var_'))) > SyntaxError: invalid syntax > >>> sorted(x, key=lambda x: int(x.strip('var_'))) > ['var_0', 'var_1', 'var_2', 'var_3', 'var_4', 'var_5', 'var_6', > 'var_7', 'var_8', 'var_9', 'var_10', 'var_11', 'var_12', 'var_13', > 'var_14'] > > Greets > Sander > > > > _______________________________________________ > 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 ilhs_hs at yahoo.com Wed Jan 13 16:21:44 2010 From: ilhs_hs at yahoo.com (Hs Hs) Date: Wed, 13 Jan 2010 07:21:44 -0800 (PST) Subject: [Tutor] how to sort a tab delim file Message-ID: <50972.60420.qm@web111207.mail.gq1.yahoo.com> Hi: I have a tab-delim file: col1 col2 col3 andrew 1987 1990 jake 1974 1980 jim 1964 1970 lance 1984 1992 how can I sort column 2 and get : jim 1964 1970 jake 1974 1980 lance 1984 1992 andrew 1987 1990 I know how to sort a items in one list. but I cannot get how this can be done on a file. any suggestions. thanks! Hs -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Jan 13 16:25:18 2010 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 13 Jan 2010 09:25:18 -0600 Subject: [Tutor] how to sort a tab delim file In-Reply-To: <50972.60420.qm@web111207.mail.gq1.yahoo.com> References: <50972.60420.qm@web111207.mail.gq1.yahoo.com> Message-ID: <1e53c511001130725m46860101p86986b3ccf1eb5ee@mail.gmail.com> On Wed, Jan 13, 2010 at 9:21 AM, Hs Hs wrote: > Hi: > > I have a tab-delim file: > > col1 col2 col3 > andrew 1987 1990 > jake 1974 1980 > jim 1964 1970 > lance 1984 1992 > > > how can I sort column 2 and get : > jim 1964 1970 > jake 1974 1980 > lance 1984 1992 > andrew 1987 1990 > > > I know how to sort a items in one list. but I cannot get how this can be > done on a file. > > any suggestions. thanks! > Hs > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Sounds like a school project to me -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Jan 13 16:25:55 2010 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 13 Jan 2010 09:25:55 -0600 Subject: [Tutor] how to sort a tab delim file In-Reply-To: <50972.60420.qm@web111207.mail.gq1.yahoo.com> References: <50972.60420.qm@web111207.mail.gq1.yahoo.com> Message-ID: <1e53c511001130725l370cdcc6v1baaebbdcf43d584@mail.gmail.com> On Wed, Jan 13, 2010 at 9:21 AM, Hs Hs wrote: > Hi: > > I have a tab-delim file: > > col1 col2 col3 > andrew 1987 1990 > jake 1974 1980 > jim 1964 1970 > lance 1984 1992 > > > how can I sort column 2 and get : > jim 1964 1970 > jake 1974 1980 > lance 1984 1992 > andrew 1987 1990 > > > I know how to sort a items in one list. but I cannot get how this can be > done on a file. > > any suggestions. thanks! > Hs > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > http://diveintopython.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at assured-networks.co.uk Wed Jan 13 18:49:23 2010 From: paul at assured-networks.co.uk (Paul Melvin) Date: Wed, 13 Jan 2010 17:49:23 -0000 Subject: [Tutor] Searching in a file Message-ID: <005f01ca9478$bde97320$39bc5960$@co.uk> Hi, I have a file generated from a webpage. I want to search that file for a specific keyword, in my case 'NEW'. Once I have found that keyword I want to retrieve information below it, e.g. web link, size of file etc. When I have this information I move off until I find another 'NEW' and the process starts all over. Please can someone give me some pointers on how to do this. I can find the line containing 'NEW' which I get using a simple for loop on every line in the file, but how do I then traverse the next x amount of lines, taking what I want until either the next 'NEW' or eof. e.g. for line in file: if re.findall('NEW', line) # or search list.append(line) # to do something to later I cannot 'get' to the following lines because I would need to get out of the loop. I did use enumerate and was wondering if I could use the line number, or maybe I could use an re iterator. Any advice would be much appreciated. Thanks paul __________ Information from ESET Smart Security, version of virus signature database 4767 (20100113) __________ The message was checked by ESET Smart Security. http://www.eset.com From stefan_ml at behnel.de Wed Jan 13 20:21:58 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 13 Jan 2010 20:21:58 +0100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: <29179d161001130625x15163afh2d692df90883b980@mail.gmail.com> References: <458754.55990.qm@web110712.mail.gq1.yahoo.com> <29179d161001130625x15163afh2d692df90883b980@mail.gmail.com> Message-ID: Hugo Arts, 13.01.2010 15:25: > Here is my solution for the general case: > > from itertools import groupby > def alphanum_key(string): > t = [] > for isdigit, group in groupby(string, str.isdigit): > group = ''.join(group) > t.append(int(group) if isdigit else group) > return t Note that this won't work in Py3, where integers and strings are not ordered, i.e. not comparable w.r.t the < and > operators. Stefan From hugo.yoshi at gmail.com Wed Jan 13 20:56:28 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 13 Jan 2010 20:56:28 +0100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: References: <458754.55990.qm@web110712.mail.gq1.yahoo.com> <29179d161001130625x15163afh2d692df90883b980@mail.gmail.com> Message-ID: <29179d161001131156l37dd16dv32b921220e152713@mail.gmail.com> On Wed, Jan 13, 2010 at 8:21 PM, Stefan Behnel wrote: > Hugo Arts, 13.01.2010 15:25: >> >> Here is my solution for the general case: >> >> from itertools import groupby >> def alphanum_key(string): >> ? ?t = [] >> ? ?for isdigit, group in groupby(string, str.isdigit): >> ? ? ? ?group = ''.join(group) >> ? ? ? ?t.append(int(group) if isdigit else group) >> ? ?return t > > Note that this won't work in Py3, where integers and strings are not > ordered, i.e. not comparable w.r.t the < and > operators. > True. You can accommodate by writing a ComparableInt class extending int, and implement __lt__ and __gt__. It's not exactly succinct, but it works. From wescpy at gmail.com Wed Jan 13 21:12:16 2010 From: wescpy at gmail.com (wesley chun) Date: Wed, 13 Jan 2010 12:12:16 -0800 Subject: [Tutor] how to sort a tab delim file In-Reply-To: <50972.60420.qm@web111207.mail.gq1.yahoo.com> References: <50972.60420.qm@web111207.mail.gq1.yahoo.com> Message-ID: <78b3a9581001131212g722c8fcu1ea1cbfbfdeea584@mail.gmail.com> > I have a tab-delim file: > > col1???????? col2???? col3 > andrew??? 1987?? 1990 > jake???????? 1974?? 1980 > jim?????????? 1964?? 1970 > lance??????? 1984?? 1992 > > how can I sort column 2 and get : > jim?????????? 1964?? 1970 > jake???????? 1974?? 1980 > lance??????? 1984?? 1992 > andrew??? 1987?? 1990 > > I know how to sort a items in one list. but I cannot get how this can be > done on a file. hi, it seems like you almost have all the tools you need to solve this problem! here are your tasks: 1. read the data out of a file and into a list -- experiment with open() and listcomps 2. sort the list -- you already know how to do this 3. create a new file with the sorted data - use open() again, listcomps, str.join(), and file.write() good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Wed Jan 13 21:16:53 2010 From: wescpy at gmail.com (wesley chun) Date: Wed, 13 Jan 2010 12:16:53 -0800 Subject: [Tutor] Searching in a file In-Reply-To: <005f01ca9478$bde97320$39bc5960$@co.uk> References: <005f01ca9478$bde97320$39bc5960$@co.uk> Message-ID: <78b3a9581001131216y24f81ab6re67e2e29988b4a6c@mail.gmail.com> > I have a file generated from a webpage. > I want to search that file for a specific keyword, in my case 'NEW'. > Once I have found that keyword I want to retrieve information below it, e.g. > web link, size of file etc. > When I have this information I move off until I find another 'NEW' and the > process starts all over. > Please can someone give me some pointers on how to do this. > > I can find the line containing 'NEW' which I get using a simple for loop on > every line in the file, but how do I then traverse the next x amount of > lines, taking what I want until either the next 'NEW' or eof. > : > Any advice would be much appreciated. based on your requirements, i think you should abandon the use of 're' and regular expressions in general since you aren't matching a pattern. just use the 'in' operator or any string methods, e.g., {,r}{find,index}(). it sounds like "NEW" only appears once on any given line, so those should suffice. if not, you'll have to do further checks. given those clues, you should be able to accomplish your task be iterating over each line and processing it as desired. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From emile at fenx.com Wed Jan 13 21:39:02 2010 From: emile at fenx.com (Emile van Sebille) Date: Wed, 13 Jan 2010 12:39:02 -0800 Subject: [Tutor] Searching in a file In-Reply-To: <005f01ca9478$bde97320$39bc5960$@co.uk> References: <005f01ca9478$bde97320$39bc5960$@co.uk> Message-ID: On 1/13/2010 9:49 AM Paul Melvin said... > Hi, > > I have a file generated from a webpage. > > I want to search that file for a specific keyword, in my case 'NEW'. > > Once I have found that keyword I want to retrieve information below it, e.g. > web link, size of file etc. > > When I have this information I move off until I find another 'NEW' and the > process starts all over. > > Please can someone give me some pointers on how to do this. > > I can find the line containing 'NEW' which I get using a simple for loop on > every line in the file, but how do I then traverse the next x amount of > lines, taking what I want until either the next 'NEW' or eof. > > e.g. > > for line in file: > if re.findall('NEW', line) # or search > list.append(line) # to do something to later > > I cannot 'get' to the following lines because I would need to get out of the > loop. How about (untested): additionalLines = 3 remainingLines = 0 for line in file: if 'NEW' in line or remainingLines: mylist.append(line) if not remainingLines: remainingLines = additionalLines else: remainingLines -= 1 Emile > > I did use enumerate and was wondering if I could use the line number, or > maybe I could use an re iterator. > > Any advice would be much appreciated. > > Thanks > > paul > > > __________ Information from ESET Smart Security, version of virus signature > database 4767 (20100113) __________ > > The message was checked by ESET Smart Security. > > http://www.eset.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 Wed Jan 13 22:03:34 2010 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Jan 2010 16:03:34 -0500 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: References: <458754.55990.qm@web110712.mail.gq1.yahoo.com> <29179d161001130625x15163afh2d692df90883b980@mail.gmail.com> Message-ID: <1c2a2c591001131303v2694a266qf4f3e906698e1209@mail.gmail.com> On Wed, Jan 13, 2010 at 2:21 PM, Stefan Behnel wrote: > Hugo Arts, 13.01.2010 15:25: >> >> Here is my solution for the general case: >> >> from itertools import groupby >> def alphanum_key(string): >> ? ?t = [] >> ? ?for isdigit, group in groupby(string, str.isdigit): >> ? ? ? ?group = ''.join(group) >> ? ? ? ?t.append(int(group) if isdigit else group) >> ? ?return t > > Note that this won't work in Py3, where integers and strings are not > ordered, i.e. not comparable w.r.t the < and > operators. It will work fine if all the list items have the same format which I would think is the most common case. Kent From hugo.yoshi at gmail.com Wed Jan 13 22:20:01 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 13 Jan 2010 22:20:01 +0100 Subject: [Tutor] Searching in a file In-Reply-To: <005f01ca9478$bde97320$39bc5960$@co.uk> References: <005f01ca9478$bde97320$39bc5960$@co.uk> Message-ID: <29179d161001131320i7104d98bh636049ac10e28b9f@mail.gmail.com> On Wed, Jan 13, 2010 at 6:49 PM, Paul Melvin wrote: > Hi, > > I have a file generated from a webpage. > > I want to search that file for a specific keyword, in my case 'NEW'. > > Once I have found that keyword I want to retrieve information below it, e.g. > web link, size of file etc. > > When I have this information I move off until I find another 'NEW' and the > process starts all over. > > Please can someone give me some pointers on how to do this. > > I can find the line containing 'NEW' which I get using a simple for loop on > every line in the file, but how do I then traverse the next x amount of > lines, taking what I want until either the next 'NEW' or eof. > > e.g. > > for line in file: > ? ? ? ?if re.findall('NEW', line) ? ? ?# or search > ? ? ? ? ? ? ? ?list.append(line) ? ? ? ? ? ? ? # to do something to later > > I cannot 'get' to the following lines because I would need to get out of the > loop. > the most obvious answer would be to take a look at the 'next()' function, that should solve this immediate problem. Another approach is to set a variable, foundnew = True, after you have found the word 'NEW', and continue. Then, in your loop, if foundnew is True, you could process the line for your additional data. Then, after processing, foundnew could be set back to false. Yet another approach is to abandon the for loop entirely, and use a while loop combined with the readline method, which allows you to read lines wherever you like. This is a similar solution to the one using next() above. I would personally prefer solutions one or three. number two seems like it could get complicated when you need to process multiple lines of information after every NEW. Hugo From alan.gauld at btinternet.com Thu Jan 14 00:05:11 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Jan 2010 23:05:11 -0000 Subject: [Tutor] Searching in a file References: <005f01ca9478$bde97320$39bc5960$@co.uk> <29179d161001131320i7104d98bh636049ac10e28b9f@mail.gmail.com> Message-ID: "Hugo Arts" wrote > the most obvious answer would be to take a look at the 'next()' > function, that should solve this immediate problem. This would be nmy advice too, but you need to get an explicit iterator to use it. it = open(.....) for line in it: if 'NEW' in line: ln = it.next() etc... > Yet another approach is to abandon the for loop entirely, and use a > while loop combined with the readline method, I prefer the next() approach. But a third option is to use a split and apply it to the whole file as a string thereby breaking the file into as many chunks as start with a line containing 'NEW'... data = open(....).read() for chunk in data.split('NEW'): for line in chunk.split('\n'): # create lines out of the chunks - you may not need this # process lines till done Just a thought. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From hugo.yoshi at gmail.com Thu Jan 14 00:29:04 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 14 Jan 2010 00:29:04 +0100 Subject: [Tutor] Searching in a file In-Reply-To: References: <005f01ca9478$bde97320$39bc5960$@co.uk> <29179d161001131320i7104d98bh636049ac10e28b9f@mail.gmail.com> Message-ID: <29179d161001131529wff871bcxadad2e7e8beb64e7@mail.gmail.com> On Thu, Jan 14, 2010 at 12:05 AM, Alan Gauld wrote: > > I prefer the next() approach. Rightfully so. IMO, The while loop with readline is basically the C version of that, for the poor people who don't have iterators. > But a third option is to use a split and apply it to the whole file as > a string thereby breaking the file into as many chunks as start with > a line containing 'NEW'... > > data = open(....).read() > for chunk in data.split('NEW'): > ? ?for line in chunk.split('\n'): ?# create lines out of the chunks - you > may not need this > ? ? ? ? # process lines till done > > Just a thought. > Probably the simplest option by far. Disadvantage is you'll have to load the entire file into memory. Whether that is important depends entirely on the file. But unless the file is extremely large, it shouldn't be a big problem. Hugo From lie.1296 at gmail.com Thu Jan 14 01:47:46 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 14 Jan 2010 11:47:46 +1100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: <29179d161001131156l37dd16dv32b921220e152713@mail.gmail.com> References: <458754.55990.qm@web110712.mail.gq1.yahoo.com> <29179d161001130625x15163afh2d692df90883b980@mail.gmail.com> <29179d161001131156l37dd16dv32b921220e152713@mail.gmail.com> Message-ID: On 01/14/10 06:56, Hugo Arts wrote: > On Wed, Jan 13, 2010 at 8:21 PM, Stefan Behnel wrote: >> Hugo Arts, 13.01.2010 15:25: >>> >>> Here is my solution for the general case: >>> >>> from itertools import groupby >>> def alphanum_key(string): >>> t = [] >>> for isdigit, group in groupby(string, str.isdigit): >>> group = ''.join(group) >>> t.append(int(group) if isdigit else group) >>> return t >> >> Note that this won't work in Py3, where integers and strings are not >> ordered, i.e. not comparable w.r.t the < and > operators. >> > > True. You can accommodate by writing a ComparableInt class extending > int, and implement __lt__ and __gt__. > It's not exactly succinct, but it works. Not necessary, you can just pass the cmp= parameter to sort that checks the chunk's type. From hugo.yoshi at gmail.com Thu Jan 14 02:01:16 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 14 Jan 2010 02:01:16 +0100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: References: <458754.55990.qm@web110712.mail.gq1.yahoo.com> <29179d161001130625x15163afh2d692df90883b980@mail.gmail.com> <29179d161001131156l37dd16dv32b921220e152713@mail.gmail.com> Message-ID: <29179d161001131701sd7abdd9v2e3e3bd5f50a269e@mail.gmail.com> On Thu, Jan 14, 2010 at 1:47 AM, Lie Ryan wrote: > On 01/14/10 06:56, Hugo Arts wrote: >> On Wed, Jan 13, 2010 at 8:21 PM, Stefan Behnel wrote: >>> Hugo Arts, 13.01.2010 15:25: >>>> >>>> Here is my solution for the general case: >>>> >>>> from itertools import groupby >>>> def alphanum_key(string): >>>> ? ?t = [] >>>> ? ?for isdigit, group in groupby(string, str.isdigit): >>>> ? ? ? ?group = ''.join(group) >>>> ? ? ? ?t.append(int(group) if isdigit else group) >>>> ? ?return t >>> >>> Note that this won't work in Py3, where integers and strings are not >>> ordered, i.e. not comparable w.r.t the < and > operators. >>> >> >> True. You can accommodate by writing a ComparableInt class extending >> int, and implement __lt__ and __gt__. >> It's not exactly succinct, but it works. > > Not necessary, you can just pass the cmp= parameter to sort that checks > the chunk's type. > might be interesting to see which performs better. cmp is called more often, but replacing C versions of __lt__ and __gt__ with python versions slows things down also, I would presume. Hugo From guilherme at gpfreitas.com Thu Jan 14 03:24:10 2010 From: guilherme at gpfreitas.com (Guilherme P. de Freitas) Date: Wed, 13 Jan 2010 18:24:10 -0800 Subject: [Tutor] Keeping a list of attributes of a certain type Message-ID: Hi everybody, Here is my problem. I have two classes, 'Body' and 'Member', and some attributes of 'Body' can be of type 'Member', but some may not. The precise attributes that 'Body' has depend from instance to instance, and they can be added or deleted. I need any instance of 'Body' to keep an up-to-date list of all its attributes that belong to the class 'Member'. How do I do this? Best, Guilherme -- Guilherme P. de Freitas http://www.gpfreitas.com From afith13 at gmail.com Thu Jan 14 02:45:40 2010 From: afith13 at gmail.com (Andrew Fithian) Date: Wed, 13 Jan 2010 17:45:40 -0800 Subject: [Tutor] confidence interval Message-ID: <64fb0beb1001131745n14b7bfbif6ea932107c602fe@mail.gmail.com> Hi tutor, I have this code for generating a confidence interval from an array of values: import numpy as np import scipy as sp def mean_confidence_interval(data, confidence=0.95): a = 1.0*np.array(data) n = len(a) m, se = np.mean(a), sp.stats.stderr(a) h = se * sp.stats.t._ppf((1+confidence)/2., n-1) return m, m-h, m+h This works but I feel there's a better and more succinct way to do this. Does anyone know of an existing python package that can do this for me? Thanks, -Drew -------------- next part -------------- An HTML attachment was scrubbed... URL: From guilherme at gpfreitas.com Thu Jan 14 05:15:21 2010 From: guilherme at gpfreitas.com (Guilherme P. de Freitas) Date: Wed, 13 Jan 2010 20:15:21 -0800 Subject: [Tutor] Keeping a list of attributes of a certain type In-Reply-To: References: Message-ID: Ok, I got something that seems to work for me. Any comments are welcome. class Member(object): def __init__(self): pass class Body(object): def __init__(self): self.members = [] def __setattr__(self, obj, value): if isinstance(value, Member): self.members.append(obj) object.__setattr__(self, obj, value) else: object.__setattr__(self, obj, value) def __delattr__(self, obj): if isinstance(getattr(self, obj), Member): self.members.remove(obj) object.__delattr__(self, obj) else: object.__delattr__(self, obj) john = Body() john.arm = Member() print(john.members) del john.arm print(john.members) On Wed, Jan 13, 2010 at 6:24 PM, Guilherme P. de Freitas wrote: > Hi everybody, > > Here is my problem. I have two classes, 'Body' and 'Member', and some > attributes of 'Body' can be of type 'Member', but some may not. The > precise attributes that 'Body' has depend from instance to instance, > and they can be added or deleted. I need any instance of 'Body' to > keep an up-to-date list of all its attributes that belong to the class > 'Member'. How do I do this? > > Best, > > Guilherme > > -- > Guilherme P. de Freitas > http://www.gpfreitas.com > -- Guilherme P. de Freitas http://www.gpfreitas.com From stefan_ml at behnel.de Thu Jan 14 10:13:04 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 14 Jan 2010 10:13:04 +0100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: References: <458754.55990.qm@web110712.mail.gq1.yahoo.com> <29179d161001130625x15163afh2d692df90883b980@mail.gmail.com> <29179d161001131156l37dd16dv32b921220e152713@mail.gmail.com> Message-ID: Lie Ryan, 14.01.2010 01:47: > On 01/14/10 06:56, Hugo Arts wrote: >> On Wed, Jan 13, 2010 at 8:21 PM, Stefan Behnel wrote: >>> Hugo Arts, 13.01.2010 15:25: >>>> Here is my solution for the general case: >>>> >>>> from itertools import groupby >>>> def alphanum_key(string): >>>> t = [] >>>> for isdigit, group in groupby(string, str.isdigit): >>>> group = ''.join(group) >>>> t.append(int(group) if isdigit else group) >>>> return t >>> Note that this won't work in Py3, where integers and strings are not >>> ordered, i.e. not comparable w.r.t the < and > operators. >>> >> True. You can accommodate by writing a ComparableInt class extending >> int, and implement __lt__ and __gt__. >> It's not exactly succinct, but it works. > > Not necessary, you can just pass the cmp= parameter to sort that checks > the chunk's type. Note that this won't work in Py3, where the "cmp" parameter is gone. Stefan From hugo.yoshi at gmail.com Thu Jan 14 10:22:05 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 14 Jan 2010 10:22:05 +0100 Subject: [Tutor] samples on sort method of sequence object. In-Reply-To: References: <458754.55990.qm@web110712.mail.gq1.yahoo.com> <29179d161001130625x15163afh2d692df90883b980@mail.gmail.com> <29179d161001131156l37dd16dv32b921220e152713@mail.gmail.com> Message-ID: <29179d161001140122s49fb6c19i1c3cb148defb1971@mail.gmail.com> On Thu, Jan 14, 2010 at 10:13 AM, Stefan Behnel wrote: > > Note that this won't work in Py3, where the "cmp" parameter is gone. > > Stefan And he's right again. I should've checked for that. Well, that makes a CmpInt class the only other solution: class CmpInt(int): def __lt__(self, other): if isinstance(other, str): return True return int.__lt__(self, other) def __gt__(self, other): if isinstance(other, str): return False return int.__gt__(self, other) Hugo From davea at ieee.org Thu Jan 14 11:34:28 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 14 Jan 2010 05:34:28 -0500 Subject: [Tutor] Keeping a list of attributes of a certain type In-Reply-To: References: Message-ID: <4B4EF334.4010307@ieee.org> (You top-posted, which puts your two comments out of order. Now the solution comes before the problem statement) Guilherme P. de Freitas wrote: > Ok, I got something that seems to work for me. Any comments are welcome. > > > class Member(object): > def __init__(self): > pass > > > class Body(object): > def __init__(self): > self.members = [] > > def __setattr__(self, obj, value): > if isinstance(value, Member): > self.members.append(obj) > object.__setattr__(self, obj, value) > else: > object.__setattr__(self, obj, value) > > def __delattr__(self, obj): > if isinstance(getattr(self, obj), Member): > self.members.remove(obj) > object.__delattr__(self, obj) > else: > object.__delattr__(self, obj) > > > > john = Body() > john.arm = Member() > print(john.members) > del john.arm > print(john.members) > > > On Wed, Jan 13, 2010 at 6:24 PM, Guilherme P. de Freitas > wrote: > >> Hi everybody, >> >> Here is my problem. I have two classes, 'Body' and 'Member', and some >> attributes of 'Body' can be of type 'Member', but some may not. The >> precise attributes that 'Body' has depend from instance to instance, >> and they can be added or deleted. I need any instance of 'Body' to >> keep an up-to-date list of all its attributes that belong to the class >> 'Member'. How do I do this? >> >> Best, >> >> Guilherme >> >> -- >> Guilherme P. de Freitas >> http://www.gpfreitas.com >> >> If this is a class assignment, you've probably got the desired answer. But if it's a real-world problem, there are tradeoffs, and until those are known, the simplest solution is usually the best. Usually, what's desired is that the object behaves "as if" it has an up-to-date list of... If order of the list doesn't matter, I'd consider simply writing a single method, called 'members' which does a list comprehension of the object's attributes, calculating the list when needed. Then use a decorator to make this method look like a read-only data attribute (untested): class Body (object): @property def members(self): return [obj for ..... if .... ] DaveA From kent37 at tds.net Thu Jan 14 12:40:12 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Jan 2010 06:40:12 -0500 Subject: [Tutor] Keeping a list of attributes of a certain type In-Reply-To: References: Message-ID: <1c2a2c591001140340u7befff64vd2c8a2663732e01b@mail.gmail.com> On Wed, Jan 13, 2010 at 9:24 PM, Guilherme P. de Freitas wrote: > Hi everybody, > > Here is my problem. I have two classes, 'Body' and 'Member', and some > attributes of 'Body' can be of type 'Member', but some may not. The > precise attributes that 'Body' has depend from instance to instance, > and they can be added or deleted. I need any instance of 'Body' to > keep an up-to-date list of all its attributes that belong to the class > 'Member'. How do I do this? If you want to keep track of attributes as they are added and deleted, you should override __setattr__() and __delattr__() in your Body class. http://docs.python.org/reference/datamodel.html#customizing-attribute-access Here is a simple example: In [4]: class LogAttributes(object): ...: def __setattr__(self, name, value): ...: print 'setting', name, 'to', value, type(value) ...: object.__setattr__(self, name, value) ...: def __delattr__(self, name): ...: print 'removing', name ...: object.__delattr__(self, name) In [5]: l = LogAttributes() In [6]: l.foo = 'bar' setting foo to bar In [7]: l.foo Out[7]: 'bar' In [8]: del l.foo removing foo Kent From kent37 at tds.net Thu Jan 14 12:43:09 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Jan 2010 06:43:09 -0500 Subject: [Tutor] Keeping a list of attributes of a certain type In-Reply-To: References: Message-ID: <1c2a2c591001140343m43f27562n90c1727f5f5c51f8@mail.gmail.com> On Wed, Jan 13, 2010 at 11:15 PM, Guilherme P. de Freitas wrote: > Ok, I got something that seems to work for me. Any comments are welcome. > > > class Member(object): > ? ?def __init__(self): > ? ? ? ?pass > > > class Body(object): > ? ?def __init__(self): > ? ? ? ?self.members = [] > > ? ?def __setattr__(self, obj, value): > ? ? ? ?if isinstance(value, Member): > ? ? ? ? ? ?self.members.append(obj) > ? ? ? ? ? ?object.__setattr__(self, obj, value) > ? ? ? ?else: > ? ? ? ? ? ?object.__setattr__(self, obj, value) That's fine but there is no need to duplicate the object.__setattr__() call: def __setattr__(self, obj, value): if isinstance(value, Member): self.members.append(obj) object.__setattr__(self, obj, value) > ? ?def __delattr__(self, obj): > ? ? ? ?if isinstance(getattr(self, obj), Member): > ? ? ? ? ? ?self.members.remove(obj) > ? ? ? ? ? ?object.__delattr__(self, obj) > ? ? ? ?else: > ? ? ? ? ? ?object.__delattr__(self, obj) Same here. Kent From maxwellhansen at hotmail.com Thu Jan 14 06:58:32 2010 From: maxwellhansen at hotmail.com (maxwell hansen) Date: Wed, 13 Jan 2010 21:58:32 -0800 Subject: [Tutor] looking for tutor Message-ID: I have a decent amount of knowledge with QBASIC and am looking for a tutor who can help me learn the pythonic equivalent of QBASIC features and commands such as COLOR, LOCATE, IF...THEN, GOTO, loops, etc. as well as visual things and objects, which arent available in QBASIC (due to it being mostly text oriented). I would really appreciate this, as I am greatly enjoying learning python so far, but I really really need someone to help me along. thanks! -maxwell _________________________________________________________________ Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. http://clk.atdmt.com/GBL/go/196390709/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Thu Jan 14 13:25:03 2010 From: denis.spir at free.fr (spir) Date: Thu, 14 Jan 2010 13:25:03 +0100 Subject: [Tutor] Searching in a file In-Reply-To: References: <005f01ca9478$bde97320$39bc5960$@co.uk> <29179d161001131320i7104d98bh636049ac10e28b9f@mail.gmail.com> Message-ID: <20100114132503.4d01f9a3@o> On Wed, 13 Jan 2010 23:05:11 -0000 "Alan Gauld" wrote: > But a third option is to use a split and apply it to the whole file as > a string thereby breaking the file into as many chunks as start with > a line containing 'NEW'... Why not simply a regex pattern starting with "NEW" and ending with '\n'? import re pat = re.compile("""NEW(.+)\n""") source = "abc\defNEWghi\njkl\nmno\nNEWpqr\nstu\n" print pat.findall(source) # ==> ['ghi', 'pqr'] Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From denis.spir at free.fr Thu Jan 14 13:39:00 2010 From: denis.spir at free.fr (spir) Date: Thu, 14 Jan 2010 13:39:00 +0100 Subject: [Tutor] Keeping a list of attributes of a certain type In-Reply-To: References: Message-ID: <20100114133900.4f088367@o> On Wed, 13 Jan 2010 20:15:21 -0800 "Guilherme P. de Freitas" wrote: > Ok, I got something that seems to work for me. Any comments are welcome. > > > class Member(object): > def __init__(self): > pass > > > class Body(object): > def __init__(self): > self.members = [] > > def __setattr__(self, obj, value): > if isinstance(value, Member): > self.members.append(obj) > object.__setattr__(self, obj, value) > else: > object.__setattr__(self, obj, value) > > def __delattr__(self, obj): > if isinstance(getattr(self, obj), Member): > self.members.remove(obj) > object.__delattr__(self, obj) > else: > object.__delattr__(self, obj) Seems perfectly ok to me, except for if...else constructs in place of simple if's: an optional statement is added in case obj is of type Member; this is not an alternative. if isinstance(value, Member): self.members.append(obj) object.__setattr__(self, obj, value) # in both cases Same for __delattr__, indeed. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From waynejwerner at gmail.com Thu Jan 14 13:44:46 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 14 Jan 2010 06:44:46 -0600 Subject: [Tutor] looking for tutor In-Reply-To: References: Message-ID: <333efb451001140444h28299047ieb089b12a71d3bad@mail.gmail.com> On Wed, Jan 13, 2010 at 11:58 PM, maxwell hansen wrote: > I have a decent amount of knowledge with QBASIC and am looking for a tutor > who can help me learn the pythonic equivalent of QBASIC features and > commands such as COLOR, LOCATE, IF...THEN, GOTO, loops, etc. as well as > visual things and objects, which arent available in QBASIC (due to it being > mostly text oriented). I would really appreciate this, as I am greatly > enjoying learning python so far, but I really really need someone to help me > along. thanks! > Well, there are lots of online tutorials available - at python.org if you click documentation, and then there are several contributors to this list who have also written tutorials. And then if you get stuck or need help understanding something, if you ask on this list, someone will usually have some insight. 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 alan.gauld at btinternet.com Thu Jan 14 13:50:22 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Jan 2010 12:50:22 -0000 Subject: [Tutor] Searching in a file References: <005f01ca9478$bde97320$39bc5960$@co.uk><29179d161001131320i7104d98bh636049ac10e28b9f@mail.gmail.com> <20100114132503.4d01f9a3@o> Message-ID: "spir" wrote >> But a third option is to use a split and apply it to the whole file as >> a string thereby breaking the file into as many chunks as start with >> a line containing 'NEW'... > > Why not simply a regex pattern starting with "NEW" and ending with '\n'? Because I understood the OP had to extract the info from the lines *following* the one with NEW. You could mess around with match object stat positions etc but split seemed a much easier solution. Alan G From alan.gauld at btinternet.com Thu Jan 14 13:52:22 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Jan 2010 12:52:22 -0000 Subject: [Tutor] Keeping a list of attributes of a certain type References: Message-ID: "Guilherme P. de Freitas" wrote > Here is my problem. I have two classes, 'Body' and 'Member', and some > attributes of 'Body' can be of type 'Member', but some may not. The > precise attributes that 'Body' has depend from instance to instance, > and they can be added or deleted. I need any instance of 'Body' to > keep an up-to-date list of all its attributes that belong to the class > 'Member'. How do I do this? Check the type of the attribute? Using isinstance()? I'm not sure of the rationale - why it needs to know the type etc But isinstance is the most obvious way that I can think of. Alan G. From alan.gauld at btinternet.com Thu Jan 14 13:56:50 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Jan 2010 12:56:50 -0000 Subject: [Tutor] looking for tutor References: Message-ID: "maxwell hansen" wrote > I have a decent amount of knowledge with QBASIC and am looking > for a tutor who can help me learn the pythonic equivalent of QBASIC > features and commands The original version of my tutor was based on QBASIC and Python(v1.5!) It might still be useful for comparisons. The latest version uses VBScript which is somewhat similar to QBASIC... http://www.freenetpages.co.uk/hp/alan.gauld/oldtutor/index.htm -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From beachkid at insightbb.com Thu Jan 14 14:27:48 2010 From: beachkid at insightbb.com (Ken G.) Date: Thu, 14 Jan 2010 08:27:48 -0500 Subject: [Tutor] looking for tutor In-Reply-To: References: Message-ID: <4B4F1BD4.4060702@insightbb.com> maxwell hansen wrote: > I have a decent amount of knowledge with QBASIC and am looking for a > tutor who can help me learn the pythonic equivalent of QBASIC features > and commands such as COLOR, LOCATE, IF...THEN, GOTO, loops, etc. as > well as visual things and objects, which arent available in QBASIC > (due to it being mostly text oriented). I would really appreciate > this, as I am greatly enjoying learning python so far, but I really > really need someone to help me along. thanks! > > -maxwell May I suggest ( http://inventwithpython.com/ ) that features Graphics and Animation in Chapter 16. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Jan 14 15:50:52 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 15 Jan 2010 01:50:52 +1100 Subject: [Tutor] Searching in a file In-Reply-To: <29179d161001131529wff871bcxadad2e7e8beb64e7@mail.gmail.com> References: <005f01ca9478$bde97320$39bc5960$@co.uk> <29179d161001131320i7104d98bh636049ac10e28b9f@mail.gmail.com> <29179d161001131529wff871bcxadad2e7e8beb64e7@mail.gmail.com> Message-ID: On 01/14/10 10:29, Hugo Arts wrote: > On Thu, Jan 14, 2010 at 12:05 AM, Alan Gauld wrote: >> > >> > I prefer the next() approach. > Rightfully so. IMO, The while loop with readline is basically the C > version of that, for the poor people who don't have iterators. I would often prefer while loop with next() though. Writing a state machine with for-loop can become quite messy because of the implicit next() on each iteration. From grigor.kolev at gmail.com Fri Jan 15 08:28:24 2010 From: grigor.kolev at gmail.com (=?windows-1251?B?w/Do4+7w?=) Date: Fri, 15 Jan 2010 09:28:24 +0200 Subject: [Tutor] Book for Python and XML Message-ID: Someone to have good E-book for python and XMl -- ????? ???? ???? ???, ???? ???? ??????? ?? ???? ?? ???? ! From paul at assured-networks.co.uk Fri Jan 15 10:24:49 2010 From: paul at assured-networks.co.uk (Paul Melvin) Date: Fri, 15 Jan 2010 09:24:49 -0000 Subject: [Tutor] Searching in a file Message-ID: <001b01ca95c4$99f29120$cdd7b360$@co.uk> Hi, Thanks very much to all your suggestions, I am looking into the suggestions of Hugo and Alan. The file is not very big, only 700KB (~20000 lines), which I think should be fine to be loaded into memory? I have two further questions though please, the lines are like this: NEW Revenge (2011) 5 days 65 minutes Etc with a chunk (between each NEW) being about 60 lines, I need to extract info from these lines, e.g. /browse/post/5354361/ and Revenge (2011) to pass back to the output, is re the best option to get all these various bits, maybe a generic function that I pass the search strings too? And if I use the split suggestion of Alan's I assume the last one would be the rest of the file, would the next() option just let me search for the next /browse/post/5354361/ etc after the NEW? (maybe putting this info into a list) Thanks again paul __________ Information from ESET Smart Security, version of virus signature database 4773 (20100114) __________ The message was checked by ESET Smart Security. http://www.eset.com From kent37 at tds.net Fri Jan 15 13:56:06 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Jan 2010 07:56:06 -0500 Subject: [Tutor] Searching in a file In-Reply-To: <001b01ca95c4$99f29120$cdd7b360$@co.uk> References: <001b01ca95c4$99f29120$cdd7b360$@co.uk> Message-ID: <1c2a2c591001150456n4da1e27cgcd0717fbb7444aeb@mail.gmail.com> On Fri, Jan 15, 2010 at 4:24 AM, Paul Melvin wrote: > Hi, > > Thanks very much to all your suggestions, I am looking into the suggestions > of Hugo and Alan. > > The file is not very big, only 700KB (~20000 lines), which I think should be > fine to be loaded into memory? > > I have two further questions though please, the lines are like this: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?NEW src="/m/I/I/star.png" /> > ? ? ? ? ? ? ? ? ? ? ? ?Revenge > (2011) > > > > ? ? ? ? ? ? ? ? ? ? ? ? class="ageVeryNew">5 days > > > ? ? ? ? ? ? ? ? ? ? ? ? class="ageVeryNew">65 minutes > > Etc with a chunk (between each NEW) being about 60 lines, I need to extract > info from these lines, e.g. /browse/post/5354361/ and Revenge (2011) to pass > back to the output, is re the best option to get all these various bits, > maybe a generic function that I pass the search strings too? You might be better off using an HTML parser such as BeautifulSoup or lxml. Kent From davea at ieee.org Fri Jan 15 16:05:09 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 15 Jan 2010 10:05:09 -0500 Subject: [Tutor] Searching in a file In-Reply-To: <001b01ca95c4$99f29120$cdd7b360$@co.uk> References: <001b01ca95c4$99f29120$cdd7b360$@co.uk> Message-ID: <4B508425.6050506@ieee.org> Paul Melvin wrote: > Hi, > > Thanks very much to all your suggestions, I am looking into the suggestions > of Hugo and Alan. > > The file is not very big, only 700KB (~20000 lines), which I think should be > fine to be loaded into memory? > > I have two further questions though please, the lines are like this: > > NEW src="/m/I/I/star.png" /> > Revenge > (2011) > > > > class="ageVeryNew">5 days > > > class="ageVeryNew">65 minutes > > Etc with a chunk (between each NEW) being about 60 lines, I need to extract > info from these lines, e.g. /browse/post/5354361/ and Revenge (2011) to pass > back to the output, is re the best option to get all these various bits, > maybe a generic function that I pass the search strings too? > > And if I use the split suggestion of Alan's I assume the last one would be > the rest of the file, would the next() option just let me search for the > next /browse/post/5354361/ etc after the NEW? (maybe putting this info into > a list) > > One way to handle "the rest of the file" is to add a marker at the end of the data. So if you read the whole thing with readlines(), you can append another "NEW" so that all matches are between one NEW and the next. > Thanks again > > paul > > If this file is valid html, or xml, then perhaps you should use one of the html or xml parsing tools, rather than anything so esoteric as regex. In any case, it now appears that NEW won't necessarily be unique, so you might want to start with 'alt="NEW"' or something like that. A key question becomes whether this data was automatically generated, or whether it might have variations from one sample to the next. (for example, alt = "NEW" with different spacing. or ALT="NEW") And whether it's definitely valid html, or just close. DaveA From guilherme at gpfreitas.com Fri Jan 15 21:33:11 2010 From: guilherme at gpfreitas.com (Guilherme P. de Freitas) Date: Fri, 15 Jan 2010 12:33:11 -0800 Subject: [Tutor] Keeping a list of attributes of a certain type In-Reply-To: References: Message-ID: Thanks everybody for all the suggestions and ideas. I still did not have time to look them all over, but I will. Thanks again! Best, Guilherme On Thu, Jan 14, 2010 at 4:52 AM, Alan Gauld wrote: > > "Guilherme P. de Freitas" wrote > >> Here is my problem. I have two classes, 'Body' and 'Member', and some >> attributes of 'Body' can be of type 'Member', but some may not. The >> precise attributes that 'Body' has depend from instance to instance, >> and they can be added or deleted. I need any instance of 'Body' to >> keep an up-to-date list of all its attributes that belong to the class >> 'Member'. How do I do this? > > Check the type of the attribute? Using isinstance()? > > I'm not sure of the rationale - why it needs to know the type etc > But isinstance is the most obvious way that I can think of. > > Alan G. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Guilherme P. de Freitas http://www.gpfreitas.com From guilherme at gpfreitas.com Fri Jan 15 21:43:30 2010 From: guilherme at gpfreitas.com (Guilherme P. de Freitas) Date: Fri, 15 Jan 2010 12:43:30 -0800 Subject: [Tutor] Keeping a list of attributes of a certain type In-Reply-To: References: Message-ID: Ok, I checked the answers you all gave me, and the suggestions seem to be 2: a. Compute the list of members on the fly, with a list comprehension that looks up stuff on self.__dict___; b. Stay with my solution, but substituting the unnecessary "if-else" by a simple "if". In sum, maintain a list of members that is updated whenever a member is added or removed. Which one is better? I am new to all this, so please correct me if I am wrong. It seems that (a) is better if you do a lot of adding/removing members operations compared to the number of lookups to the "members" list. Otherwise, (b) is better. Right? In my application, I will do many more lookups on the members list than adding/removing members (this sounds weird, feels like I'm Dr. Frankenstein), so I will go with (b). Thanks again for all the suggestions, Guilherme -- Guilherme P. de Freitas http://www.gpfreitas.com From kent37 at tds.net Fri Jan 15 22:53:34 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Jan 2010 16:53:34 -0500 Subject: [Tutor] Keeping a list of attributes of a certain type In-Reply-To: References: Message-ID: <1c2a2c591001151353r7300b66m7a5718545092430d@mail.gmail.com> On Fri, Jan 15, 2010 at 3:43 PM, Guilherme P. de Freitas wrote: > Ok, I checked the answers you all gave me, and the suggestions seem to be 2: > > a. Compute the list of members on the fly, with a list comprehension > that looks up stuff on self.__dict___; > > b. Stay with my solution, but substituting the unnecessary "if-else" > by a simple "if". In sum, maintain a list of members that is updated > whenever a member is added or removed. > > Which one is better? I am new to all this, so please correct me if I > am wrong. It seems that (a) is better if you do a lot of > adding/removing members operations compared to the number of lookups > to the "members" list. Otherwise, (b) is better. Right? Personally (b) feels more direct and robust. There is no guarantee that attributes are stored in self.__dict__, they can be in __slots__ or delegated to some other container. For example, here is a class with no __dict__: In [1]: class Foo(object): ...: __slots__ = ['bar'] ...: def __setattr__(self, name, value): ...: print 'set', name, 'to', value ...: object.__setattr__(self, name, value) In [2]: f=Foo() In [3]: f.bar = 'baz' set bar to baz In [4]: f.__dict__ --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) C:\Project\(misc)\MangoDB\ in () AttributeError: 'Foo' object has no attribute '__dict__' Granted if you have control over all the classes this won't happen but still...relying on __dict__ makes me nervous. Kent From luhmann_br at yahoo.com Sat Jan 16 11:46:42 2010 From: luhmann_br at yahoo.com (Luhmann) Date: Sat, 16 Jan 2010 02:46:42 -0800 (PST) Subject: [Tutor] Images on Python 3k Message-ID: <747239.16071.qm@web30903.mail.mud.yahoo.com> Hello List, Does anyone know of a way simple way to display JPG and PNG images on python 3? My program uses tkinter, and currently my solution is to use ImageMagick's convert through std to convert the images to gif. However the conversion is too time consuming. I have only started using python after Py3 was released, so this is is the only version I know. I have tried to make my code work in Python 2 so I could use PIL, but I came across many bugs to which I could not readily find a solution, and it seems it would take me a long time to get it fixed. D?couvrez les photos les plus int?ressantes du jour. http://www.flickr.com/explore/interesting/7days/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 17 01:50:58 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Jan 2010 00:50:58 -0000 Subject: [Tutor] Images on Python 3k References: <747239.16071.qm@web30903.mail.mud.yahoo.com> Message-ID: "Luhmann" wrote > I have only started using python after Py3 was released, so this is is > the only version I know. I have tried to make my code work in > Python 2 so I could use PIL, This is one of the biggest barriers to adopting Python 3. Until PIL gets ported it's a non starter for many folks. And why Tk doesn't support formats other than GIF and PPM for its "PhotoImage" widget is a long standing mystery! Thee has been much talk of supporting JPG but nothing has ever materialised. Alan G. From webtourist at gmail.com Sun Jan 17 07:10:32 2010 From: webtourist at gmail.com (Robert) Date: Sun, 17 Jan 2010 01:10:32 -0500 Subject: [Tutor] Confirmation about __init__() Message-ID: <8af18dcf1001162210o6985a117k12b5c960e51099e0@mail.gmail.com> I have read quite a bit in the past 2 months, ( I have also looked at codes) At this point, I think I understand well what __init__() is and does - But, I have yet to see this *specifically* spelled out about the the __init__ method for a Class; It is OPTIONAL, correct ? if I have NO start values/variables to set, no Base Class __init__ to call --- the __init__ method is NOT required, correct ? thanks From steve at alchemy.com Sun Jan 17 07:16:15 2010 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 16 Jan 2010 22:16:15 -0800 Subject: [Tutor] Confirmation about __init__() In-Reply-To: <8af18dcf1001162210o6985a117k12b5c960e51099e0@mail.gmail.com> References: <8af18dcf1001162210o6985a117k12b5c960e51099e0@mail.gmail.com> Message-ID: <4B52AB2F.1060904@alchemy.com> Robert wrote: > I have read quite a bit in the past 2 months, ( I have also looked at codes) > At this point, I think I understand well what __init__() is and does - > But, I have yet to see this *specifically* spelled out about the the > __init__ method for a Class; > > It is OPTIONAL, correct ? In a manner of speaking, that's correct. You'll get a basic default initialization (and inherit the __init__() from your superclass(es) if your new class is derived from another one. You just create your own __init__() if you have something you need to set up, and/or need to call the superclass __init__() in a special way. From webtourist at gmail.com Sun Jan 17 09:43:23 2010 From: webtourist at gmail.com (Robert) Date: Sun, 17 Jan 2010 03:43:23 -0500 Subject: [Tutor] command line invocation Message-ID: <8af18dcf1001170043w2a0aeb7fnc66e0657113456f4@mail.gmail.com> Say that I have module "spam.py" in "/tmp" which is in PYTHONPATH. in shell, my current directory is "/tmp", are line#3 and #4 --- http://paste.pocoo.org/show/166268/ - "equivalent" --- i.e. yielding the same result ? Thanks From alan.gauld at btinternet.com Sun Jan 17 10:26:26 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Jan 2010 09:26:26 -0000 Subject: [Tutor] Confirmation about __init__() References: <8af18dcf1001162210o6985a117k12b5c960e51099e0@mail.gmail.com> Message-ID: "Robert" wrote >I have read quite a bit in the past 2 months, ( I have also looked at >codes) > At this point, I think I understand well what __init__() is and does - > But, I have yet to see this *specifically* spelled out about the the > __init__ method for a Class; > > It is OPTIONAL, correct ? Yes as are all metods. There is nothing very special about __init__ except that it is not called explicitly by users of the class. It could have been done as an explicit method as in Smalltalk or Objective C. In these the instance creation paradigm is a two stage process obj = [[class new] init] In Python we get the init call for "free" Alan G. From alan.gauld at btinternet.com Sun Jan 17 10:32:02 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Jan 2010 09:32:02 -0000 Subject: [Tutor] command line invocation References: <8af18dcf1001170043w2a0aeb7fnc66e0657113456f4@mail.gmail.com> Message-ID: "Robert" wrote > in shell, my current directory is "/tmp", > are line#3 and #4 --- http://paste.pocoo.org/show/166268/ - > "equivalent" --- i.e. yielding the same result ? No need to use pastebin when its only 2 lines! Since -m runs a module as a script I think the answer is yes. Where they would be different is if you were not in the same folder as the module. Then the -m option would search the PYTHONPATH whereas without -m I think it would not search for the module, you would need to specify the location. I think... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From webtourist at gmail.com Sun Jan 17 06:42:52 2010 From: webtourist at gmail.com (Robert) Date: Sun, 17 Jan 2010 00:42:52 -0500 Subject: [Tutor] Confirmation about __init__() Message-ID: <8af18dcf1001162142y3cf7b2c4ke76278d2b6549815@mail.gmail.com> I have read quite a bit in the past 2 months, ( I have also looked at codes) At this point, I think I understand well what __init__() is and does - But, I have yet to see this *specifically* spelled out about the the __init__ method for a Class; It is OPTIONAL, correct ? if I have NO start values/variables to set, no Base Class __init__ to call --- the __init__ method is NOT required, correct ? thanks From timovwb at gmail.com Sun Jan 17 16:47:15 2010 From: timovwb at gmail.com (Timo Vanwynsberghe) Date: Sun, 17 Jan 2010 16:47:15 +0100 Subject: [Tutor] Subclassing object Message-ID: <801f3cfb1001170747o69ae980ai732ff1c75e8766b7@mail.gmail.com> I read that it is advised to subclass object. Is it really necessary? I mean, everything works, why should I add it to my code? Cheers, Timo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 17 17:25:09 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Jan 2010 16:25:09 -0000 Subject: [Tutor] Subclassing object References: <801f3cfb1001170747o69ae980ai732ff1c75e8766b7@mail.gmail.com> Message-ID: "Timo Vanwynsberghe" wrote >I read that it is advised to subclass object. > > Is it really necessary? I mean, everything works, why should I add it to > my > code? In older versions of Python it made a difference whether you used object or not. Using object gave you a "new style" class which has several extra features, without you got an "old style class" without the features. In Python v3 you only get new style classes and I think you can omit the object without detriment. For comparison here are Python v2.5 definitions >>> class New(object): pass ... >>> dir(New) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash_ _', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr_ _', '__setattr__', '__str__', '__weakref__'] >>> class Old: pass ... >>> dir(Old) ['__doc__', '__module__'] As you can see there is quite a lot of extra "stuff" in the New class. In Python 3: >>> class New(object): pass >>> dir(New) ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] >>> class Old: pass >>> dir(Old) ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] There is even more "stuff" but it is the same with/without the explicit 'object'. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From shizuhaaki1 at yahoo.com Sun Jan 17 18:40:23 2010 From: shizuhaaki1 at yahoo.com (Shizuha Aki) Date: Sun, 17 Jan 2010 09:40:23 -0800 (PST) Subject: [Tutor] adding more text to a file Message-ID: <140105.87064.qm@web112901.mail.gq1.yahoo.com> Hi, I am new to python, and i am trying to make a program that makes like a txt file database. so i have my whole program in a while True loop, it asks for information about the person and then writes the information about the person to a txt file, but i need it to be able to add more entries instead of just one. my code is like this: while True: name = raw_input("what is the name ") age = raw_input("what is the age ") out_file = open("persons.txt", "w") out_file.write("name: ") out_file.write(name) out_file.write("\n") out_file.write("age: ") out_file.write(age) out_file.write("\n") out_file.write("\n") out_file.close now i want to add like say 5 persons to the txt file, but whenever i enter a new person it just overwrites the previous, im sure its because of the "w" but how exactly do i need to change my code to add more text instead of overwriting? -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Jan 17 18:52:33 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 17 Jan 2010 18:52:33 +0100 Subject: [Tutor] adding more text to a file In-Reply-To: <140105.87064.qm@web112901.mail.gq1.yahoo.com> References: <140105.87064.qm@web112901.mail.gq1.yahoo.com> Message-ID: <29179d161001170952p75827e0bx662a6049a171320c@mail.gmail.com> On Sun, Jan 17, 2010 at 6:40 PM, Shizuha Aki wrote: > Hi, > > I am new to python, and i am trying to make a program that makes like a txt > file database. so i have my whole program in a while True loop, it asks for > information about the person and then writes the information about the > person to a txt file, but i need it to be able to add more entries instead > of just one. > > my code is like this: > > while True: > ?????? name = raw_input("what is the name ") > ?????? age = raw_input("what is the age ") > > ?????? out_file = open("persons.txt", "w") > ?????? out_file.write("name: ") > ?????? out_file.write(name) > ?????? out_file.write("\n") > ?????? out_file.write("age: ") > ?????? out_file.write(age) > ?????? out_file.write("\n") > ?????? out_file.write("\n") > ?????? out_file.close > > now i want to add like say 5 persons to the txt file, but whenever i enter a > new person it just overwrites the previous, im sure its because of the "w" > but how exactly do i need to change my code to add more text instead of > overwriting? > you should check the python documentation for the 'open' function. help() is your friend, works on any interactive session. On linux, you could also check out the pydoc program. Or you could check the website docs.python.org. Hugo From magnus.kriel at gmail.com Sun Jan 17 19:01:03 2010 From: magnus.kriel at gmail.com (Magnus Kriel) Date: Sun, 17 Jan 2010 10:01:03 -0800 Subject: [Tutor] adding more text to a file In-Reply-To: <140105.87064.qm@web112901.mail.gq1.yahoo.com> References: <140105.87064.qm@web112901.mail.gq1.yahoo.com> Message-ID: Hi, It is the way you open the text file in the beginning. This is from the python manual: open() returns a file object, and is most commonly used with two arguments: "open(filename, mode)". >>> f=open('/tmp/workfile', 'w') >>> print f The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w'for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it's omitted. You should use 'a' and not 'w'. It might be that when you create a file for the first time with 'a', that it will through an exception. So you will have to try with 'w', and if there is an exception, you know the file does not exist and you will have to create the file for the first time with 'w'. Hope it helps. Buy the way, why don't you try sqlite for your database structure? sqlite is still a single file, not like MySQL. You get a pysqilte at : http://pypi.python.org/pypi/pysqlite/ Magnus Kriel The 'W' means write. An 'A' means append On Sun, Jan 17, 2010 at 9:40 AM, Shizuha Aki wrote: > Hi, > > I am new to python, and i am trying to make a program that makes like a txt > file database. so i have my whole program in a while True loop, it asks for > information about the person and then writes the information about the > person to a txt file, but i need it to be able to add more entries instead > of just one. > > my code is like this: > > while True: > name = raw_input("what is the name ") > age = raw_input("what is the age ") > > out_file = open("persons.txt", "w") > out_file.write("name: ") > out_file.write(name) > out_file.write("\n") > out_file.write("age: ") > out_file.write(age) > out_file.write("\n") > out_file.write("\n") > out_file.close > > now i want to add like say 5 persons to the txt file, but whenever i enter > a new person it just overwrites the previous, im sure its because of the "w" > but how exactly do i need to change my code to add more text instead of > overwriting? > > > _______________________________________________ > 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 webtourist at gmail.com Sun Jan 17 19:04:49 2010 From: webtourist at gmail.com (Robert) Date: Sun, 17 Jan 2010 13:04:49 -0500 Subject: [Tutor] Subclassing object In-Reply-To: <8af18dcf1001170947u7ddf2098r639037a08d2c9339@mail.gmail.com> References: <801f3cfb1001170747o69ae980ai732ff1c75e8766b7@mail.gmail.com> <8af18dcf1001170947u7ddf2098r639037a08d2c9339@mail.gmail.com> Message-ID: <8af18dcf1001171004ha231f1bh38660ac0c0474356@mail.gmail.com> On Sun, Jan 17, 2010 at 12:47 PM, Robert wrote: > On Sun, Jan 17, 2010 at 11:25 AM, Alan Gauld wrote: >> In older versions of Python it made a difference whether you used object >> or not. Using object gave you a "new style" class which has several extra >> features, without you got an "old style class" without the features. I have been wondering about this "New-style Class" subject along this line: so, *theoretically speaking*, in EXISTING, pre-P3K code, if one changes everywhere where it's coded "class someClass()" to "class someClass(object)", it should not break the programs, right ? From steve at alchemy.com Sun Jan 17 19:34:39 2010 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 17 Jan 2010 10:34:39 -0800 Subject: [Tutor] adding more text to a file In-Reply-To: References: <140105.87064.qm@web112901.mail.gq1.yahoo.com> Message-ID: <4B53583F.3030804@alchemy.com> Magnus Kriel wrote: > It might be that when you create a file for the first time with 'a', > that it will through an exception. So you will have to try with 'w', and > if there is an exception, you know the file does not exist and you will > have to create the file for the first time with 'w'. That's a little confusing, I think. I think you meant "try with 'a' and if there is an exception ... create ... with 'w'" but that shouldn't be necessary anyway. Opening a file with 'a' will append to an existing file, or create a new file if one doesn't exist already. From magnus.kriel at gmail.com Sun Jan 17 19:52:13 2010 From: magnus.kriel at gmail.com (Magnus Kriel) Date: Sun, 17 Jan 2010 10:52:13 -0800 Subject: [Tutor] adding more text to a file In-Reply-To: <4B53583F.3030804@alchemy.com> References: <140105.87064.qm@web112901.mail.gq1.yahoo.com> <4B53583F.3030804@alchemy.com> Message-ID: Thanx, you are correct. And now I know that 'a' will create a file as well. Magnus On Sun, Jan 17, 2010 at 10:34 AM, Steve Willoughby wrote: > Magnus Kriel wrote: > > It might be that when you create a file for the first time with 'a', > > that it will through an exception. So you will have to try with 'w', and > > if there is an exception, you know the file does not exist and you will > > have to create the file for the first time with 'w'. > > That's a little confusing, I think. I think you meant "try with 'a' and > if there is an exception ... create ... with 'w'" but that shouldn't be > necessary anyway. Opening a file with 'a' will append to an existing > file, or create a new file if one doesn't exist already. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From webtourist at gmail.com Sun Jan 17 21:10:34 2010 From: webtourist at gmail.com (Robert) Date: Sun, 17 Jan 2010 15:10:34 -0500 Subject: [Tutor] what is dynamic about "dynamic name resolution" ? Message-ID: <8af18dcf1001171210u17679059l11d2c540867eea41@mail.gmail.com> In the Python tutorial (highlighted here http://awurl.com/N1XvzIo2Q) What exactly is "dynamic name resolution" ? specifically what is "dynamic" about it ? thanks From kbailey at howlermonkey.net Sun Jan 17 21:45:00 2010 From: kbailey at howlermonkey.net (Kirk Z Bailey) Date: Sun, 17 Jan 2010 15:45:00 -0500 Subject: [Tutor] smtp project Message-ID: <4B5376CC.2050802@howlermonkey.net> I am writing a script that will send an email message. This will run in a windows XP box. The box does not have a smtp server, so the script must crete not merely a smtp client to talk to a MTA, it must BE one for the duration of sending the message- then shut off, we don't need no bloody op0en relays here! I am RTFM and having some heavy sledding, can I get an Elmer on this? -- end Very Truly yours, - Kirk Bailey, Largo Florida kniht +-----+ | BOX | +-----+ think From wescpy at gmail.com Mon Jan 18 00:11:40 2010 From: wescpy at gmail.com (wesley chun) Date: Sun, 17 Jan 2010 15:11:40 -0800 Subject: [Tutor] what is dynamic about "dynamic name resolution" ? In-Reply-To: <8af18dcf1001171210u17679059l11d2c540867eea41@mail.gmail.com> References: <8af18dcf1001171210u17679059l11d2c540867eea41@mail.gmail.com> Message-ID: <78b3a9581001171511w2dcfa83btd3d7671ad1223331@mail.gmail.com> On Sun, Jan 17, 2010 at 12:10 PM, Robert wrote: > In the Python tutorial (highlighted here http://awurl.com/N1XvzIo2Q) > > What exactly is "dynamic name resolution" ? specifically what is > "dynamic" about it ? what this means is that as your code is executing and the interpreter encounters an identifier/variable, it "dynamically" looks up the variable at that point -- it checks at that point to see if it's a local variable; if not, global; finally it checks if it's a built-in. to rephrase: this check is *not* done during compile time (static); instead, it is done during runtime (dynamic). if it were static, it would've already been checked *before* your code ever started running. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Mon Jan 18 00:17:32 2010 From: wescpy at gmail.com (wesley chun) Date: Sun, 17 Jan 2010 15:17:32 -0800 Subject: [Tutor] adding more text to a file In-Reply-To: <140105.87064.qm@web112901.mail.gq1.yahoo.com> References: <140105.87064.qm@web112901.mail.gq1.yahoo.com> Message-ID: <78b3a9581001171517r2e51de4ic240ba33d45d9f39@mail.gmail.com> > while True: > ?????? name = raw_input("what is the name ") > ?????? age = raw_input("what is the age ") > > ?????? out_file = open("persons.txt", "w") > ?????? out_file.write("name: ") > ?????? out_file.write(name) > ?????? out_file.write("\n") > ?????? out_file.write("age: ") > ?????? out_file.write(age) > ?????? out_file.write("\n") > ?????? out_file.write("\n") > ?????? out_file.close while everyone is helping you with your original inquiry, i'm going to inject some "Pythonic" style guidelines here. 1. i would strongly suggest calling the close() method instead of merely providing the object. in other words, change your last line to "out_file.close()" so you execute it. otherwise your file contents are not guaranteed. 2. try to minimize the total number of calls to write() to make things run faster. for example, your code only really needs one call: out_file.write("name: %s\nage: %s\n\n" % (name, age)) the reason why it's faster is because you pay a little bit of overhead with every function call you make. of course, since your example requires human input each time, it doesn't make as much of a difference in this example, but this is mostly a general suggestion. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Mon Jan 18 01:07:22 2010 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Jan 2010 19:07:22 -0500 Subject: [Tutor] smtp project In-Reply-To: <4B5376CC.2050802@howlermonkey.net> References: <4B5376CC.2050802@howlermonkey.net> Message-ID: <1c2a2c591001171607k3277aaadj4765b4a49d0f9a3d@mail.gmail.com> On Sun, Jan 17, 2010 at 3:45 PM, Kirk Z Bailey wrote: > I am writing a script that will send an email message. This will run in a > windows XP box. The box does not have a smtp server, so the script must > crete not merely a smtp client to talk to a MTA, it must BE one for the > duration of sending the message- then shut off, we don't need no bloody > op0en relays here! Is there no SMTP server available on another machine? Can you send email from a regular email client (e.g. Thunderbird)? > I am RTFM and having some heavy sledding, can I get an Elmer on this? An Elmer? Kent From steve at alchemy.com Mon Jan 18 01:17:23 2010 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 17 Jan 2010 16:17:23 -0800 Subject: [Tutor] smtp project In-Reply-To: <1c2a2c591001171607k3277aaadj4765b4a49d0f9a3d@mail.gmail.com> References: <4B5376CC.2050802@howlermonkey.net> <1c2a2c591001171607k3277aaadj4765b4a49d0f9a3d@mail.gmail.com> Message-ID: <4B53A893.40105@alchemy.com> Kent Johnson wrote: > On Sun, Jan 17, 2010 at 3:45 PM, Kirk Z Bailey wrote: >> I am writing a script that will send an email message. This will run in a >> windows XP box. The box does not have a smtp server, so the script must >> crete not merely a smtp client to talk to a MTA, it must BE one for the >> duration of sending the message- then shut off, we don't need no bloody >> op0en relays here! > > Is there no SMTP server available on another machine? Can you send > email from a regular email client (e.g. Thunderbird)? Unless I'm missing something, you're probably overly complicating your solution. You don't need to open a local relay just to *send* a message from the same script. Your script can connect to whatever upstream SMTP server your organization uses and send mail to it directly. >> I am RTFM and having some heavy sledding, can I get an Elmer on this? > > An Elmer? Old Amateur Radio term. An "Elmer" is someone who mentors new people and shows them the ropes. Which is essentially what the list is for. From alan.plum at uni-koeln.de Mon Jan 18 01:24:08 2010 From: alan.plum at uni-koeln.de (Alan Plum) Date: Mon, 18 Jan 2010 01:24:08 +0100 Subject: [Tutor] smtp project In-Reply-To: <4B5376CC.2050802@howlermonkey.net> References: <4B5376CC.2050802@howlermonkey.net> Message-ID: <1263774248.2928.9.camel@kallisti> On So, 2010-01-17 at 15:45 -0500, Kirk Z Bailey wrote: > I am writing a script that will send an email message. This will > run in a windows XP box. The box does not have a smtp server, so > the script must crete not merely a smtp client to talk to a MTA, > it must BE one for the duration of sending the message- then shut > off, we don't need no bloody op0en relays here! Twisted is the obvious choice for a server daemon, but it should be good enough for what you do, too. What you need isn't a "SMTP server", it's a "SMTP sender", which is more like a client than a server in the usual model. As you don't want it to run as a daemon, first consider how you want it to behave if the server (SMTP receiver, the destination or a server that is willing to relay the message) is not responding or responds with an error. A message queue (in terms of days not seconds) is out of the question for a fire-and-forget service like the one you want, so you probably want the transfer synchronously, i.e. somewhere between receiving the user's input (or whatever triggers the script) and the output (or the end of the lifetime of whatever script was triggered). If you're dealing with real users, though, this can mean an unexpected pause of several seconds, depending on how long the delivery takes (or how long it takes to notice it's not going anywhere). This is bad if the user isn't expecting it (zero progress can be interpreted as a freeze). Anyway. Take a look at Twisted or other libraries for SMTP senders or "clients". Actual SMTP servers are mostly concerned with accepting mail via SMTP and doing something with them (if they are capable of relaying, they can also act as SMTP senders, otherwise they probably just deliver the mail locally or forward them to a local message queue for a separate SMTP sender). Hope that helped a bit, Alan Plum From alan.gauld at btinternet.com Mon Jan 18 02:17:36 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Jan 2010 01:17:36 -0000 Subject: [Tutor] Subclassing object References: <801f3cfb1001170747o69ae980ai732ff1c75e8766b7@mail.gmail.com><8af18dcf1001170947u7ddf2098r639037a08d2c9339@mail.gmail.com> <8af18dcf1001171004ha231f1bh38660ac0c0474356@mail.gmail.com> Message-ID: "Robert" wrote > I have been wondering about this "New-style Class" subject along this > line: > > so, *theoretically speaking*, in EXISTING, pre-P3K code, > if one changes everywhere where it's coded "class someClass()" to > "class someClass(object)", > it should not break the programs, right ? More correctly replacing old style class SomeClass: with new style class SomeClass(object): should not break anything. You cannot of course reliably go the other way! Alan G From alan.gauld at btinternet.com Mon Jan 18 02:24:21 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Jan 2010 01:24:21 -0000 Subject: [Tutor] adding more text to a file References: <140105.87064.qm@web112901.mail.gq1.yahoo.com> Message-ID: "Shizuha Aki" wrote > i need it to be able to add more entries instead of just one. > > my code is like this: > > while True: > name = raw_input("what is the name ") > age = raw_input("what is the age ") > > out_file = open("persons.txt", "w") It would work if you moved the open() call outside the loop so the file is only opened once. Every time you open the file you create a new file on top of the old one. You need to move the close outside the loop too of course. That way you don't need append mode unless you want to run the program multiple times to keep adding data. > out_file.write("name: ") > out_file.write(name) > out_file.write("\n") You should join the strings together and write a full line out at once. It will be more efficient and possibly more resilient too. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jan 18 02:19:50 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Jan 2010 01:19:50 -0000 Subject: [Tutor] adding more text to a file References: <140105.87064.qm@web112901.mail.gq1.yahoo.com> Message-ID: "Magnus Kriel" wrote > It might be that when you create a file for the first time with 'a', that > it > will through an exception. So you will have to try with 'w', and if there > is > an exception, you know the file does not exist and you will have to > create > the file for the first time with 'w'. That should not happen. If there is no file 'a' will act like 'w' Alan G. From shuying at gmail.com Mon Jan 18 03:13:34 2010 From: shuying at gmail.com (Shuying Wang) Date: Mon, 18 Jan 2010 13:13:34 +1100 Subject: [Tutor] exit handler for C extension module Message-ID: <75fa0c3a1001171813n4018f561j90e66064d2ae96a@mail.gmail.com> Hi, What would be an atexit equivalent for a C extension module? When my extension module is unloaded, I would like some clean up functions to be called from an external c library. I've had a look at the C extension guide but I can't find anything like that, Thanks in advance, .S From lie.1296 at gmail.com Mon Jan 18 07:47:36 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 18 Jan 2010 17:47:36 +1100 Subject: [Tutor] Confirmation about __init__() In-Reply-To: <8af18dcf1001162142y3cf7b2c4ke76278d2b6549815@mail.gmail.com> References: <8af18dcf1001162142y3cf7b2c4ke76278d2b6549815@mail.gmail.com> Message-ID: On 01/17/10 16:42, Robert wrote: > I have read quite a bit in the past 2 months, ( I have also looked at codes) > At this point, I think I understand well what __init__() is and does - > But, I have yet to see this *specifically* spelled out about the the > __init__ method for a Class; > > It is OPTIONAL, correct ? > > if I have NO start values/variables to set, no Base Class __init__ to > call --- the __init__ method is NOT required, correct ? No, __init__ is always required for new-style classes; however due to object inheritance (all new-style classes inherits from `object`), all new-style classes inherits the do-nothing __init__ from `object`. Essentially, it means __init__ can be omitted if it does the same as the super class' __init__. More generally, a method (e.g. MyClass.__init__) that does not override the superclass' method (e.g. MySuperClass.__init__) will use the superclass' definition of the method (i.e. when MyClass inherits from MySuperClass, and __init__ is not overrided in MyClass, MyClass.__init__ == MySuperClass.__init__). From stefan_ml at behnel.de Mon Jan 18 08:37:11 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 18 Jan 2010 08:37:11 +0100 Subject: [Tutor] Book for Python and XML In-Reply-To: References: Message-ID: ??????, 15.01.2010 08:28: > Someone to have good E-book for python and XMl The existing books are rather old. You might find these interesting, though: http://effbot.org/zone/element.htm http://codespeak.net/lxml/tutorial.html http://www.nmt.edu/tcc/help/pubs/pylxml Stefan From stefan_ml at behnel.de Mon Jan 18 08:40:31 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 18 Jan 2010 08:40:31 +0100 Subject: [Tutor] exit handler for C extension module In-Reply-To: <75fa0c3a1001171813n4018f561j90e66064d2ae96a@mail.gmail.com> References: <75fa0c3a1001171813n4018f561j90e66064d2ae96a@mail.gmail.com> Message-ID: Shuying Wang, 18.01.2010 03:13: > What would be an atexit equivalent for a C extension module? When my > extension module is unloaded, I would like some clean up functions to > be called from an external c library. I've had a look at the C > extension guide but I can't find anything like that, I'm not aware of anything special here. Just use the "atexit" module itself and register a Python function. At least, that's what we do in Cython for any module level cleanup. You may also consider adding some hints on what you want to use it for, maybe there is some support for your actual use case. Stefan From shuying at gmail.com Mon Jan 18 08:58:41 2010 From: shuying at gmail.com (Shuying Wang) Date: Mon, 18 Jan 2010 18:58:41 +1100 Subject: [Tutor] exit handler for C extension module In-Reply-To: References: <75fa0c3a1001171813n4018f561j90e66064d2ae96a@mail.gmail.com> Message-ID: <75fa0c3a1001172358j398086bducdb38908164cc3a1@mail.gmail.com> I found what I was after, right after I posted to this list. It's Py_AtExit. I'm accessing an old, unsupported database using it's C API. I've tried using Cython but found it hard to get my head around and I'm finding it somewhat easier to just write by hand. On Mon, Jan 18, 2010 at 6:40 PM, Stefan Behnel wrote: >> What would be an atexit equivalent for a C extension module? When my >> extension module is unloaded, I would like some clean up functions to >> be called from an external c library. I've had a look at the C >> extension guide but I can't find anything like that, > > I'm not aware of anything special here. Just use the "atexit" module itself > and register a Python function. At least, that's what we do in Cython for > any module level cleanup. > > You may also consider adding some hints on what you want to use it for, > maybe there is some support for your actual use case. > > Stefan From wescpy at gmail.com Mon Jan 18 09:09:14 2010 From: wescpy at gmail.com (wesley chun) Date: Mon, 18 Jan 2010 00:09:14 -0800 Subject: [Tutor] adding more text to a file In-Reply-To: References: <140105.87064.qm@web112901.mail.gq1.yahoo.com> Message-ID: <78b3a9581001180009t7fefb906sfee06755750d7bcc@mail.gmail.com> On Sun, Jan 17, 2010 at 5:19 PM, Alan Gauld wrote: > > "Magnus Kriel" wrote > >> It might be that when you create a file for the first time with 'a', that >> it >> will through an exception. So you will have to try with 'w', and if there >> is >> an exception, you know the file does not exist and you will have to create >> the file for the first time with 'w'. > > That should not happen. If there is no file 'a' will act like 'w' alan is correct. with 'a', if a file doesn't exist, it will create it and open it for write. if it does exist, it will go to the current EOF and open it for write starting from that point. the only time 'a' throws an exception is if the file cannot be opened, e.g., it's on a network drive that isn't there, no perms on that filesystem, etc. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From stefan_ml at behnel.de Mon Jan 18 11:28:20 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 18 Jan 2010 11:28:20 +0100 Subject: [Tutor] exit handler for C extension module In-Reply-To: <75fa0c3a1001172358j398086bducdb38908164cc3a1@mail.gmail.com> References: <75fa0c3a1001171813n4018f561j90e66064d2ae96a@mail.gmail.com> <75fa0c3a1001172358j398086bducdb38908164cc3a1@mail.gmail.com> Message-ID: Shuying Wang, 18.01.2010 08:58: > I found what I was after, right after I posted to this list. It's > Py_AtExit. I'm accessing an old, unsupported database using it's C > API. I didn't write the respective code in Cython, but there's a comment next to it saying /* Don't use Py_AtExit because that has a 32-call limit * and is called after python finalization. */ So Py_AtExit() may or may not be what you are looking for. Also note that Py3 has a C-API mechanism for safely cleaning up (and potentially unloading) modules, which likely is what you are looking for anyway. > I've tried using Cython but found it hard to get my head around > and I'm finding it somewhat easier to just write by hand. Personally, I find it a matter of developer time (basically "why write C when you can write Python?"), but your mileage may vary. Stefan From adam.jtm30 at gmail.com Mon Jan 18 12:46:27 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 18 Jan 2010 11:46:27 +0000 Subject: [Tutor] smtp project In-Reply-To: <4B5376CC.2050802@howlermonkey.net> References: <4B5376CC.2050802@howlermonkey.net> Message-ID: 2010/1/17 Kirk Z Bailey > I am writing a script that will send an email message. This will run in a > windows XP box. The box does not have a smtp server, so the script must > crete not merely a smtp client to talk to a MTA, it must BE one for the > duration of sending the message- then shut off, we don't need no bloody > op0en relays here! > > I am RTFM and having some heavy sledding, can I get an Elmer on this? This isn't quite what you're after but I wrote some code a while ago to find the changes to a wiki in the day from an update RSS feed and then send an email with these changes to a mailing list via a googlemail account. Anyway there should be some useul code in it http://cubesat.wikidot.com/wiki-change-emailer HTH Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 18 13:31:23 2010 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Jan 2010 07:31:23 -0500 Subject: [Tutor] smtp project In-Reply-To: <4B53CE29.9060307@howlermonkey.net> References: <4B5376CC.2050802@howlermonkey.net> <1c2a2c591001171607k3277aaadj4765b4a49d0f9a3d@mail.gmail.com> <4B53CE29.9060307@howlermonkey.net> Message-ID: <1c2a2c591001180431l7f5405fmb447cd07c6b8e2@mail.gmail.com> On Sun, Jan 17, 2010 at 9:57 PM, Kirk Z Bailey wrote: > There is no smtp server available, these are the cards I am delt; can you > advise on how to play them? A couple of possibilities: - I'm no expert on SMTP but don't the MTAs talk SMTP to each other on port 25? Could you use smtplib to talk to the remote MTA on port 25? - The std lib contains a simple SMTP server in smtpd.py - Lamson is a more robust SMTP server http://lamsonproject.org/ - Twisted has SMTP support http://twistedmatrix.com/trac/wiki/TwistedMail Kent PS Please Reply All to reply on list. > Kent Johnson wrote: >> >> On Sun, Jan 17, 2010 at 3:45 PM, Kirk Z Bailey >> wrote: >>> >>> I am writing a script that will send an email message. This will run in a >>> windows XP box. The box does not have a smtp server, so the script must >>> crete not merely a smtp client to talk to a MTA, it must BE one for the >>> duration of sending the message- then shut off, we don't need no bloody >>> op0en relays here! >> >> Is there no SMTP server available on another machine? Can you send >> email from a regular email client (e.g. Thunderbird)? >> >>> I am RTFM and having some heavy sledding, can I get an Elmer on this? >> >> An Elmer? >> >> Kent >> >> > > -- > end > > Very Truly yours, > ? ? ? ? ? ? ? ? - Kirk Bailey, > ? ? ? ? ? ? ? ? ? Largo Florida > > ? ? ? ? ? ? ? ? ? ? ? kniht > ? ? ? ? ? ? ? ? ? ? ?+-----+ > ? ? ? ? ? ? ? ? ? ? ?| BOX | > ? ? ? ? ? ? ? ? ? ? ?+-----+ > ? ? ? ? ? ? ? ? ? ? ? think > From modulok at gmail.com Mon Jan 18 16:54:53 2010 From: modulok at gmail.com (Modulok) Date: Mon, 18 Jan 2010 08:54:53 -0700 Subject: [Tutor] adding more text to a file In-Reply-To: <140105.87064.qm@web112901.mail.gq1.yahoo.com> References: <140105.87064.qm@web112901.mail.gq1.yahoo.com> Message-ID: <64c038661001180754g389ce789n87316d1c22ae574f@mail.gmail.com> If you're using this as an interactive command to help you populate a database, as you appear to be, don't open the file more than once. As previously suggested you should also put all your strings together and then write them to the database in one go. I don't know if you've thought about this yet, but you'll need a way to stop when you're done inputing names and ages! Here are two thoughts you can look into: 1) Check for a special character (or lack thereof). For example, if the fields are blank you could exit the loop using the 'break' statement. Or 2) Catching a 'KeyboardInterrupt' exception using the 'try...except' statements. Without doing it for you, (I assume this is homework) these are some suggested changes: out_file = open('persons.txt', 'w') while True: name = raw_input("What is the name: ") age = raw_input("What is the age: ") out_file.write("name:%s\nage: %s\n\n" (name, age)) # We'll never get this far unless we figure out a way to stop the loop! out_file.close() Keep at it and best of luck! -Modulok- From galaxywatcher at gmail.com Mon Jan 18 17:06:27 2010 From: galaxywatcher at gmail.com (galaxywatcher at gmail.com) Date: Mon, 18 Jan 2010 23:06:27 +0700 Subject: [Tutor] Python workspace - IDE and version control Message-ID: I want to share a couple of insights that I had getting started with Python that I did not come across in the literature all that often. I am discovering that there are two primary supporting tools needed in order to create an efficient and productive Python programming workspace: IDE and Version Control. I didn't realize at first how important these supporting tools for Python would be. If Python is your first programming language, you will have to learn how to use a good text editor or IDE (Integrated Development Environment). If you use textpad, it gets old very fast. I have chosen vim as my IDE and I added a few key plugins that I think help a lot (snipMate, surround, nerd-tree, and repeat). I believe that snipMate is a plugin made specifically for Python users on vim. Among other features, it auto indents your code which is very nice. So now that I can do some Python scripting, I started to notice that my scripts were not very organized. Collaboration of code is difficult. I had multiple copies of the same script in different directories on my computer, and I did not have a good way to really keep track. This is the wrong way. Version Control Systems are tried and true technologies for collaborating with others (or even yourself) on your code. After some research, I have decided to go with Git. I have never used version control before, so I don't know the distinctions of the various systems out there. I chose Git mainly because github.com is really great. Some MAJOR open source (and closed) projects are happening on there and you can download the open source code so very easily. I am told Mercurial is good too, Bazaar and SVN also came up in my research. Obviously, no tool can think for you. The real programming work of course is going on in your brain. I am curious what combination of IDE and Version Control System you use and also perhaps, what other tools I should be looking at as well. Thanks. From alan.gauld at btinternet.com Mon Jan 18 22:17:38 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Jan 2010 21:17:38 -0000 Subject: [Tutor] Python workspace - IDE and version control References: Message-ID: wrote > order to create an efficient and productive Python programming > workspace: IDE and Version Control. Both important, although an IDE is perhaps a generous description of vim! :-) > Obviously, no tool can think for you. The real programming work of > course is going on in your brain. I am curious what combination of IDE > and Version Control System you use and also perhaps, what other tools I > should be looking at as well. I tend to use vim under cygwin (which gives me all the Unix tools) as the IDE. I use plain old RCS for version control because its just me working on the code. At work where we have parallel streams I use SVN (used to be Borland $tarTeam) Because we use Eclipse at work I increasingly use Eclipse with PyDev as my IDE for larger projects - its project support is very effective and I like the debugger. Also, since I often integrate Java and Jython, Eclipse is ideal for integrating a multi-source project, especially with a UML modelling plugin added to capture the design. Finally, I use Subclipse to integrate Eclipse with SVN. Alan G. From mlee3891 at gmail.com Tue Jan 19 01:11:22 2010 From: mlee3891 at gmail.com (Matthew Lee) Date: Tue, 19 Jan 2010 11:11:22 +1100 Subject: [Tutor] Python workspace - IDE and version control In-Reply-To: References: Message-ID: <4747b22d1001181611q3bf55acfo6bb208d6a12fc8f5@mail.gmail.com> I usually just use NetBeans or the Python IDLE. I prefer to use NetBeans because it's easier to change and modify code and test. And also because I like to use Jython. Anything wrong with my setup? On Tue, Jan 19, 2010 at 8:17 AM, Alan Gauld wrote: > > wrote > > > order to create an efficient and productive Python programming workspace: >> IDE and Version Control. >> > > Both important, although an IDE is perhaps a generous > description of vim! :-) > > > Obviously, no tool can think for you. The real programming work of course >> is going on in your brain. I am curious what combination of IDE and Version >> Control System you use and also perhaps, what other tools I should be >> looking at as well. >> > > I tend to use vim under cygwin (which gives me all the Unix tools) as the > IDE. > > I use plain old RCS for version control because its just me working on the > code. > > At work where we have parallel streams I use SVN (used to be Borland > $tarTeam) > Because we use Eclipse at work I increasingly use Eclipse with PyDev as my > IDE for larger projects - its project support is very effective and I like > the debugger. Also, since I often integrate Java and Jython, Eclipse is > ideal for > integrating a multi-source project, especially with a UML modelling plugin > added to capture the design. > > Finally, I use Subclipse to integrate Eclipse with SVN. > > 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 alan.gauld at btinternet.com Tue Jan 19 01:29:32 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Jan 2010 00:29:32 -0000 Subject: [Tutor] Python workspace - IDE and version control References: <4747b22d1001181611q3bf55acfo6bb208d6a12fc8f5@mail.gmail.com> Message-ID: "Matthew Lee" wrote >I usually just use NetBeans or the Python IDLE. > I prefer to use NetBeans because it's easier to change and modify code > and > test. And also because I like to use Jython. > > Anything wrong with my setup? If it works for you then its fine. IDEs, editors etc are all very personal choices and everyone is different. I used Netbeans for a while and preferred it to Eclipse at the time, but I use Eclipse because its what we have to use at work and consistency outweighs the slight advantages I found in Netneans. If you don;t have that constraint use whatever you find works best for you! Alan G From niyas at nucoreindia.com Tue Jan 19 04:56:29 2010 From: niyas at nucoreindia.com (muhamed niyas) Date: Tue, 19 Jan 2010 09:26:29 +0530 Subject: [Tutor] Python workspace - IDE and version control In-Reply-To: References: <4747b22d1001181611q3bf55acfo6bb208d6a12fc8f5@mail.gmail.com> Message-ID: I am using Netbeans, it has many features. The following IDEs i used before Netbeanse Anjuta, Komodo, python IDLE, etc.. There is a python plugin in Netbease and also it has subversion integrated. On Tue, Jan 19, 2010 at 5:59 AM, Alan Gauld wrote: > > "Matthew Lee" wrote > > > I usually just use NetBeans or the Python IDLE. >> I prefer to use NetBeans because it's easier to change and modify code and >> test. And also because I like to use Jython. >> >> Anything wrong with my setup? >> > > If it works for you then its fine. > IDEs, editors etc are all very personal choices and everyone is different. > I used Netbeans for a while and preferred it to Eclipse at the time, but I > use > Eclipse because its what we have to use at work and consistency outweighs > the slight advantages I found in Netneans. If you don;t have that > constraint > use whatever you find works best for you! > > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Thanks & Best Regards, Muhamed Niyas C (NuCore Software Solutions Pvt Ltd) Mobile: +91 9447 468825 URL: www.nucoreindia.com Email: niyas at nucoreindia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikunjbadjatya at gmail.com Tue Jan 19 08:12:44 2010 From: nikunjbadjatya at gmail.com (nikunj badjatya) Date: Tue, 19 Jan 2010 12:42:44 +0530 Subject: [Tutor] Contribution to Opensource Message-ID: Hi, I recently joined this mailing list so as to improve my knowledge on Python. Its been 4 months I am using Python. So I decided to contribute to any Open source project. Can you help me on how to proceed on this, Whom to contact etc. Thanks, Nikunj Badjatya BTech Bangalore, India -------------- next part -------------- An HTML attachment was scrubbed... URL: From cheesman at titan.physx.u-szeged.hu Tue Jan 19 08:49:27 2010 From: cheesman at titan.physx.u-szeged.hu (andy) Date: Tue, 19 Jan 2010 08:49:27 +0100 Subject: [Tutor] Html entities, beautiful soup and unicode Message-ID: <20100119074927.GA9444@titan.physx.u-szeged.hu> Hi people I'm using beautiful soup to rip the uk headlines from the uk bbc page. This works rather well but there is the problem of html entities which appear in the xml feed. Is there an elegant/simple way to convert them into the "standard" output? By this I mean £ going to ? ? or do i have to use regexp? and where does unicode fit into all of this? Thanks for your help Andy From grflanagan at gmail.com Tue Jan 19 11:29:49 2010 From: grflanagan at gmail.com (Gerard Flanagan) Date: Tue, 19 Jan 2010 10:29:49 +0000 Subject: [Tutor] Html entities, beautiful soup and unicode In-Reply-To: <20100119074927.GA9444@titan.physx.u-szeged.hu> References: <20100119074927.GA9444@titan.physx.u-szeged.hu> Message-ID: andy wrote: > Hi people > > I'm using beautiful soup to rip the uk headlines from the uk bbc page. > This works rather well but there is the problem of html entities which > appear in the xml feed. > Is there an elegant/simple way to convert them into the "standard" > output? By this I mean £ going to ? ? or do i have to use regexp? > and where does unicode fit into all of this? > import re # Fredrik Lundh, http://effbot.org/zone/re-sub.html def unescape(text): def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3].lower() == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity import htmlentitydefs try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) print unescape('£') ? ~ From denis.spir at free.fr Tue Jan 19 11:59:09 2010 From: denis.spir at free.fr (spir) Date: Tue, 19 Jan 2010 11:59:09 +0100 Subject: [Tutor] Html entities, beautiful soup and unicode In-Reply-To: <20100119074927.GA9444@titan.physx.u-szeged.hu> References: <20100119074927.GA9444@titan.physx.u-szeged.hu> Message-ID: <20100119115909.4b93ecc9@o> On Tue, 19 Jan 2010 08:49:27 +0100 andy wrote: > Hi people > > I'm using beautiful soup to rip the uk headlines from the uk bbc page. > This works rather well but there is the problem of html entities which > appear in the xml feed. > Is there an elegant/simple way to convert them into the "standard" > output? By this I mean £ going to ? ? or do i have to use regexp? > and where does unicode fit into all of this? Ha, ha! What do you mean exactly, convert them into the "standard" output? What form do you expect, and to do what? Maybe your aim is to replace number-coded html entities in a python string by real characters in a given format, to be able to output them. Then one way may be to use a simple regex and replace with a custom function. Eg: import re def rep(result): string = result.group() # "&#xxx;" n = int(string[2:-1]) uchar = unichr(n) # matching unicode char # for you dest format may be iso-8859-2 ? return unicode.encode(uchar, "utf-8") # format-encoded char source = "xxx¡xxxÂxxxÿxxx" pat = re.compile("""&#\d+;""") print pat.sub(rep, source) Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From kent37 at tds.net Tue Jan 19 12:43:45 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Jan 2010 06:43:45 -0500 Subject: [Tutor] Python workspace - IDE and version control In-Reply-To: References: Message-ID: <1c2a2c591001190343k311e6a1fk28446afdb75c866c@mail.gmail.com> On Mon, Jan 18, 2010 at 4:17 PM, Alan Gauld wrote: > I use plain old RCS for version control because its just me working on the > code. Wow. You should take a look at Mercurial. It is so easy to set up a Mercurial repository for a local project - just hg init # create a repository hg st # show what will be checked in hg add # mark new files as to be added hg ci -m "Initial checkin" # the actual checkin and voila! you have a version-controlled project! Kent From kent37 at tds.net Tue Jan 19 18:05:59 2010 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Jan 2010 12:05:59 -0500 Subject: [Tutor] Python workspace - IDE and version control In-Reply-To: <4B55BDCA.4080500@kostyrka.org> References: <1c2a2c591001190343k311e6a1fk28446afdb75c866c@mail.gmail.com> <4B55BDCA.4080500@kostyrka.org> Message-ID: <1c2a2c591001190905u28db4464hc1d1461ad26e9a00@mail.gmail.com> On Tue, Jan 19, 2010 at 9:12 AM, Andreas Kostyrka wrote: > The cool part about git that I've not yet replicated with hg is git add -p > which allows you to seperate out > different changes in the same file. Sounds like the record and crecord extensions come close, anyway: http://mercurial.selenic.com/wiki/RecordExtension http://mercurial.selenic.com/wiki/CrecordExtension Kent From alan.gauld at btinternet.com Wed Jan 20 00:01:48 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Jan 2010 23:01:48 -0000 Subject: [Tutor] Python workspace - IDE and version control References: <1c2a2c591001190343k311e6a1fk28446afdb75c866c@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> I use plain old RCS for version control because its just me working on >> the >> code. > > hg init # create a repository md RCS in rcs > hg st # show what will be checked in > > hg add # mark new files as to be added Don't need any of that stuff > hg ci -m "Initial checkin" # the actual checkin ci foo.py in rcs > and voila! you have a version-controlled project! I prefer RCS - two commands is all you need (ci/co) :-) Alan G. From alan.gauld at btinternet.com Wed Jan 20 01:56:11 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 20 Jan 2010 00:56:11 +0000 (GMT) Subject: [Tutor] Python workspace - IDE and version control In-Reply-To: <4B5646B6.8040809@kostyrka.org> References: <1c2a2c591001190343k311e6a1fk28446afdb75c866c@mail.gmail.com> <4B5646B6.8040809@kostyrka.org> Message-ID: <90637.52563.qm@web86707.mail.ird.yahoo.com> > >>> I use plain old RCS for version control because its just me working >> I prefer RCS - two commands is all you need (ci/co) :-) > > Certainly, OTOH, you get only file based commits, no upgrade path > should you ever decide that you need to go multiuser > (and multiuser can be just you with two different places, Well, you get tags which allow you to check in/out a whole project at a time if need be. And RCS does allow multi user and server based working (just by locating the RCS folder there!). In fact the biggest project I ever worked on had around 3.5 million lines of C++ in 10,000 source files in over 200 folders and it was all controlled using RCS and makefiles. And branching and merging are all standard features too. (We had over 400 developers working off the repositories with 4 or 5 branches active at any one time - but CVS would have been much easier if it had been available at the time - v1.0 was just released the same year we started work - 1990!) But modern tools are much better I agree. And at work, as I said, we use subversion (and CVS on older projects). In my time I've also used several heavyweight version and configuration control tools - ranging in price from a few hundred pounds to several hundred thousand dollars. The best by a long shot is ClearCase on Unix, although Aide de Camp is also good. But these both cost $$$$ For my home use, the biggest Python project I've done had less than 10 files in a single folder plus some imported modules from my personal collection so RCS is more than adequate. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From katisss at gmx.de Wed Jan 20 07:52:21 2010 From: katisss at gmx.de (katrin schmid) Date: Wed, 20 Jan 2010 17:52:21 +1100 Subject: [Tutor] create an object from a class in dll with ctypes? Message-ID: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC> hi, i am getting started with ctypes in python 2.5 and was wondering if i would be able to create an object from the class in my dll somehow. I only found examples that show how to access a function but the function i want to call is part of a cpp class in my dll... Thank you, katrin -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Wed Jan 20 08:49:14 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 19 Jan 2010 23:49:14 -0800 Subject: [Tutor] create an object from a class in dll with ctypes? References: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC> Message-ID: "katrin schmid" wrote in message news:0EDDA7DDDFF84D639352526B72DBF8C7 at katisssPC... > hi, > i am getting started with ctypes in python 2.5 and was wondering if > i would be able to create an object from the class in my dll somehow. > I only found examples that show how to access a function but the > function i want to call is part of a cpp class in my dll... ctypes is for C DLLs. You might want to look at www.swig.org instead. -Mark From metolone+gmane at gmail.com Wed Jan 20 08:56:53 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 19 Jan 2010 23:56:53 -0800 Subject: [Tutor] Python workspace - IDE and version control References: <1c2a2c591001190343k311e6a1fk28446afdb75c866c@mail.gmail.com><4B55BDCA.4080500@kostyrka.org> <1c2a2c591001190905u28db4464hc1d1461ad26e9a00@mail.gmail.com> Message-ID: "Kent Johnson" wrote in message news:1c2a2c591001190905u28db4464hc1d1461ad26e9a00 at mail.gmail.com... > On Tue, Jan 19, 2010 at 9:12 AM, Andreas Kostyrka > wrote: > >> The cool part about git that I've not yet replicated with hg is git >> add -p >> which allows you to seperate out >> different changes in the same file. > > Sounds like the record and crecord extensions come close, anyway: > http://mercurial.selenic.com/wiki/RecordExtension > http://mercurial.selenic.com/wiki/CrecordExtension TortoiseHg's commit GUI allows this. -Mark From Katisss at gmx.de Wed Jan 20 10:16:48 2010 From: Katisss at gmx.de (katrin schmid) Date: Wed, 20 Jan 2010 10:16:48 +0100 Subject: [Tutor] create an object from a class in dll with ctypes? In-Reply-To: References: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC> Message-ID: <20100120091648.262720@gmx.net> hi, perfectly looks like what i want, thanks a lot. katrin -------- Original-Nachricht -------- > Datum: Tue, 19 Jan 2010 23:49:14 -0800 > Von: "Mark Tolonen" > An: tutor at python.org > Betreff: Re: [Tutor] create an object from a class in dll with ctypes? > > "katrin schmid" wrote in message > news:0EDDA7DDDFF84D639352526B72DBF8C7 at katisssPC... > > hi, > > i am getting started with ctypes in python 2.5 and was wondering if > > i would be able to create an object from the class in my dll somehow. > > I only found examples that show how to access a function but the > > function i want to call is part of a cpp class in my dll... > > ctypes is for C DLLs. You might want to look at www.swig.org instead. > > -Mark > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From raghavendra.gv.vanam at gmail.com Wed Jan 20 19:13:13 2010 From: raghavendra.gv.vanam at gmail.com (vanam) Date: Wed, 20 Jan 2010 23:43:13 +0530 Subject: [Tutor] adding more text to a file (Vanam) Message-ID: <4499cb6a1001201013w66be7d9cm40a6d9914822680b@mail.gmail.com> Below is the code which can be helpful for better insight: Sample: 1 For the below code, you can provide initially the number of entries (say 4) so that for four times name of person and age is prompted to enter.After writing to file we can read back the contents #Writing number of times the name of person to a file #Opening the file log = open('data.txt','w') x = int(raw_input('enter the number of entries')) for y in range(x): data = raw_input('enter the name of the person') age = int(raw_input('enter age of the person')) print >> log, '%s %d' % (data,age) log.close() #Reading the contents of the file with multiple entries log = open('hello.txt','r') for x in log: print x, log.close() Sample:2 Assuming your query, below is the short piece where name and age is always entered till there is no data entered for person and the same content is written back to the file. log = open('data.txt','w') while True: x = raw_input('enter name') if len(x) == 0: break y = int(raw_input('enter age')) print >> log, '%s %d' % (x,y) log.close() > > Hi, > > I am new to python, and i am trying to make a program that makes like a txt file database. so i have my whole program in a while True loop, it asks for information about the person and then writes the information about the person to a txt file, but i need it to be able to add more entries instead of just one. > > my code is like this: > > while True: > name = raw_input("what is the name ") > age = raw_input("what is the age ") > > out_file = open("persons.txt", "w") > out_file.write("name: ") > out_file.write(name) > out_file.write("\n") > out_file.write("age: ") > out_file.write(age) > out_file.write("\n") > out_file.write("\n") > out_file.close > > now i want to add like say 5 persons to the txt file, but whenever i enter a new person it just overwrites the previous, im sure its because of the "w" but how exactly do i need to change my code to add more text instead of overwriting? > > > > -- Raghavendra Vanam From sudheer.kay at gmail.com Thu Jan 21 07:57:56 2010 From: sudheer.kay at gmail.com (sudhir prasad) Date: Thu, 21 Jan 2010 12:27:56 +0530 Subject: [Tutor] keeping track of the present line in a file Message-ID: hi, is there any other way to keep track of line number in a file other than fileinput.filelineno() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 21 09:43:39 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Jan 2010 08:43:39 -0000 Subject: [Tutor] keeping track of the present line in a file References: Message-ID: "sudhir prasad" wrote > is there any other way to keep track of line number in a file other than > fileinput.filelineno() You could always do it manually by incrementing a counter every time you read a line. But what's the problem with filelineno()? If you tell us what your problem is we might be able to offer a suggestion. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From paul at assured-networks.co.uk Thu Jan 21 10:03:19 2010 From: paul at assured-networks.co.uk (Paul Melvin) Date: Thu, 21 Jan 2010 09:03:19 -0000 Subject: [Tutor] Still searching in html files Message-ID: <001901ca9a78$967f7950$c37e6bf0$@co.uk> Hi, I am still looking for information in these files and have a sort of 'clunky' solution that I would like feedback on please. The code is at http://python.codepad.org/S1ul2bh7 and the bit I would like some advice on is how to get the sorted data and where to put it. Currently I use a temporary list to store the data before writing it to another, is this OK? (lines 45 onwards) I want to expand the program to give some output which the user can interact with, e.g. 'which of this information do you want me to get?' and the user would choose. Does anyone have any tips on this? Can I just use things like raw_input and lists? Thanks paul -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Thu Jan 21 12:56:54 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 21 Jan 2010 12:56:54 +0100 Subject: [Tutor] Still searching in html files In-Reply-To: <001901ca9a78$967f7950$c37e6bf0$@co.uk> References: <001901ca9a78$967f7950$c37e6bf0$@co.uk> Message-ID: Paul Melvin, 21.01.2010 10:03: > I am still looking for information in these files and have a sort of > 'clunky' solution that I would like feedback on please. > > The code is at http://python.codepad.org/S1ul2bh7 and the bit I would like > some advice on is how to get the sorted data and where to put it. Looks like you already didn't take the good advice to use an HTML parser. > I want to expand the program to give some output which the user can interact > with, e.g. 'which of this information do you want me to get?' and the user > would choose. Does anyone have any tips on this? Can I just use things like > raw_input and lists? I'd advise against that, although this obviously depends on the type of users you expect. Likely, you'd rather want a) a command line interface so that you can also use it from other scripts (look at the optparse module for that), and b) a suitable module API so that you can use the code from other Python modules. Try to make your code reusable by splitting it into separate functions and classes, and move it out of the top module level. Stefan From neal at fourthwall.net Thu Jan 21 00:22:48 2010 From: neal at fourthwall.net (Neal Mendelsohn) Date: Wed, 20 Jan 2010 15:22:48 -0800 Subject: [Tutor] Need help, tutoring Python Message-ID: I am looking for someone who knows WordPress to spend an hour with me on the phone and with a shared screen to coach me on how WordPress can be configured using Python files. Can you refer me? Thanks, NM From m.kossner at tu-bs.de Thu Jan 21 10:06:40 2010 From: m.kossner at tu-bs.de (markus kossner) Date: Thu, 21 Jan 2010 10:06:40 +0100 Subject: [Tutor] combinatorics problem: assembling array Message-ID: <4B581920.8030907@tu-bs.de> Dear Pythonics, I have a rather algorithmic problem that obviously made a knot in my brain: Assume we have to build up all the arrays that are possible if we have a nested array containing an array of integers that are allowed for each single position. For example the nested array ( (1,2,3,89), (3,5,8), (19,30,7,100,210,1,44) ) would define all the arrays of length 3 that can be enumerated using the array of possible numbers for each position. Beforehand I will have no Idea of the length of the arrays. How do I enumerate all the possible arrays with python? Thanks for getting the knot out of my brain, Markus From kent37 at tds.net Thu Jan 21 13:42:39 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Jan 2010 07:42:39 -0500 Subject: [Tutor] keeping track of the present line in a file In-Reply-To: References: Message-ID: <1c2a2c591001210442j4b590012y3be8f33b7ae073c3@mail.gmail.com> On Thu, Jan 21, 2010 at 1:57 AM, sudhir prasad wrote: > hi, > is there any other way to keep track of line number in a file other than > fileinput.filelineno() With enumerate(): for line_number, line in enumerate(open('myfile.txt')): # etc Kent From kent37 at tds.net Thu Jan 21 13:59:51 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Jan 2010 07:59:51 -0500 Subject: [Tutor] Still searching in html files In-Reply-To: <001901ca9a78$967f7950$c37e6bf0$@co.uk> References: <001901ca9a78$967f7950$c37e6bf0$@co.uk> Message-ID: <1c2a2c591001210459g682d87e4nc4e6688668fb65e7@mail.gmail.com> On Thu, Jan 21, 2010 at 4:03 AM, Paul Melvin wrote: > The code is at http://python.codepad.org/S1ul2bh7 and the bit I would like > some advice on is how to get the sorted data and where to put it. Generally the code seems a bit disorganized, consider breaking it into functions. There is a fair amount of deadwood you could delete. Also it will be more readable if you move the initialization of variables closer to where they are used. > Currently I use a temporary list to store the data before writing it to > another, is this OK? (lines 45 onwards) for chunk in u.split(searchText): temp.append(chunk) u.split() already returns a sequence, there is no need for this loop. You could just write temp = u.split(searchText) though you might think of a more descriptive name. for item in temp[1:]: temp2 = [] temp2.append(findLink(item)) temp2.append(findTitle(item)) temp2.append(findSize(item)) cleaned.append(temp2) This could be written more concisely without temp2: cleaned.append( [ findLink(item), findTitle(item), findSize(item) ] ) or even put the whole thing into a single list comprehension (though this is perhaps too dense): cleaned = [ [ findLink(item), findTitle(item), findSize(item) ] for item in u.split(searchText)[1:] ] I think I would write it as items = u.split(searchText)[1:] cleaned = [ [ findLink(item), findTitle(item), findSize(item) ] for item in items ] > I want to expand the program to give some output which the user can interact > with, e.g. ?which of this information do you want me to get?? and the user > would choose.? Does anyone have any tips on this? Can I just use things like > raw_input and lists? That's fine, just separate out the data acquisition from the user input and processing. Kent From kent37 at tds.net Thu Jan 21 14:07:40 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Jan 2010 08:07:40 -0500 Subject: [Tutor] combinatorics problem: assembling array In-Reply-To: <4B581920.8030907@tu-bs.de> References: <4B581920.8030907@tu-bs.de> Message-ID: <1c2a2c591001210507k4b69e42cxddde3e61939b290e@mail.gmail.com> On Thu, Jan 21, 2010 at 4:06 AM, markus kossner wrote: > Dear Pythonics, > I have a rather algorithmic problem that obviously made a knot in my brain: > > Assume we have to build up all the arrays that are possible if we have a > nested array > containing an array of integers that are allowed for each single position. > For example > the nested array > ( > (1,2,3,89), > (3,5,8), > (19,30,7,100,210,1,44) > ) > would define all the arrays of length ?3 ?that can be ?enumerated ?using the > array of ?possible numbers ?for each position. See itertools.product(): http://docs.python.org/library/itertools.html#itertools.product Kent From denis.spir at free.fr Thu Jan 21 14:25:43 2010 From: denis.spir at free.fr (spir) Date: Thu, 21 Jan 2010 14:25:43 +0100 Subject: [Tutor] combinatorics problem: assembling array In-Reply-To: <4B581920.8030907@tu-bs.de> References: <4B581920.8030907@tu-bs.de> Message-ID: <20100121142543.574b942e@o> On Thu, 21 Jan 2010 10:06:40 +0100 markus kossner wrote: > Dear Pythonics, > I have a rather algorithmic problem that obviously made a knot in my brain: > > Assume we have to build up all the arrays that are possible if we have a > nested array > containing an array of integers that are allowed for each single > position. For example > the nested array > ( > (1,2,3,89), > (3,5,8), > (19,30,7,100,210,1,44) > ) > would define all the arrays of length 3 that can be enumerated using > the > array of possible numbers for each position. > Beforehand I will have no Idea of the length of the arrays. How do I > enumerate all the possible > arrays with python? > > Thanks for getting the knot out of my brain, > Markus A loop over first set of numbers, with an inner loop over second set of numbers, with an inner loop over third set of numbers. Deep inside the loops, just feed a list of combinations. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From kent37 at tds.net Thu Jan 21 15:14:51 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Jan 2010 09:14:51 -0500 Subject: [Tutor] combinatorics problem: assembling array In-Reply-To: <1c2a2c591001210507k4b69e42cxddde3e61939b290e@mail.gmail.com> References: <4B581920.8030907@tu-bs.de> <1c2a2c591001210507k4b69e42cxddde3e61939b290e@mail.gmail.com> Message-ID: <1c2a2c591001210614q3385d59an4dab1a7f5af7d8c@mail.gmail.com> On Thu, Jan 21, 2010 at 8:07 AM, Kent Johnson wrote: > On Thu, Jan 21, 2010 at 4:06 AM, markus kossner wrote: >> Dear Pythonics, >> I have a rather algorithmic problem that obviously made a knot in my brain: >> >> Assume we have to build up all the arrays that are possible if we have a >> nested array >> containing an array of integers that are allowed for each single position. >> For example >> the nested array >> ( >> (1,2,3,89), >> (3,5,8), >> (19,30,7,100,210,1,44) >> ) >> would define all the arrays of length ?3 ?that can be ?enumerated ?using the >> array of ?possible numbers ?for each position. > > See itertools.product(): > http://docs.python.org/library/itertools.html#itertools.product Here is an example: In [1]: values = ( ...: (1,2,3,89), ...: (3,5,8), ...: (19,30,7,100,210,1,44) ...: ) In [2]: from itertools import product In [3]: list(product(*values)) Out[3]: [(1, 3, 19), (1, 3, 30), (1, 3, 7), ... (2, 3, 19), (2, 3, 30), ... (89, 8, 210), (89, 8, 1), (89, 8, 44)] Kent From samueldechamplain at gmail.com Thu Jan 21 18:33:40 2010 From: samueldechamplain at gmail.com (Samuel de Champlain) Date: Thu, 21 Jan 2010 12:33:40 -0500 Subject: [Tutor] Hello Message-ID: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> This is my first message to this mailing list. I want to create a project with glade and pygtk on fedora. Can you suggest a good IDE? -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Thu Jan 21 18:45:12 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Thu, 21 Jan 2010 23:15:12 +0530 Subject: [Tutor] Hello In-Reply-To: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> References: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> Message-ID: The choice of IDE is quite objective. Many of the people use vim/emacs exclusively for all the work. Eclipse with PyDev plugin too is a good choice. On Thu, Jan 21, 2010 at 11:03 PM, Samuel de Champlain < samueldechamplain at gmail.com> wrote: > This is my first message to this mailing list. > I want to create a project with glade and pygtk on fedora. > Can you suggest a good IDE? > > _______________________________________________ > 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 invincible_patriot at hotmail.com Thu Jan 21 18:48:36 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Thu, 21 Jan 2010 17:48:36 +0000 Subject: [Tutor] need help in python In-Reply-To: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> References: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> Message-ID: hi I am a student and i need soe help regarding my assignmentif some one can help me il be glad. i wil be waiting for the reply thanks Date: Thu, 21 Jan 2010 12:33:40 -0500 From: samueldechamplain at gmail.com To: tutor at python.org Subject: [Tutor] Hello This is my first message to this mailing list. I want to create a project with glade and pygtk on fedora. Can you suggest a good IDE? _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. http://clk.atdmt.com/GBL/go/196390707/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas at kostyrka.org Thu Jan 21 19:07:42 2010 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 21 Jan 2010 19:07:42 +0100 Subject: [Tutor] need help in python In-Reply-To: References: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> Message-ID: <201001211907.43069.andreas@kostyrka.org> Am Donnerstag, 21. Januar 2010 18:48:36 schrieb invincible patriot: > hi > I am a student and i need soe help regarding my assignmentif some one can > help me il be glad. You do realize that assignments are things to be done by yourself? This is a mailing list, so just post your questions, but do not expect us to do the assignment for you. OTOH specific questions, that suggest that you've at least tried to solve the problem yourself, will probably be answered. (Consider that answering and explaining it to you will probably take more time than just creating the your assignment, but that's beside the point.) Andreas > > i wil be waiting for the reply > > thanks > > > > Date: Thu, 21 Jan 2010 12:33:40 -0500 > From: samueldechamplain at gmail.com > To: tutor at python.org > Subject: [Tutor] Hello > > This is my first message to this mailing list. > I want to create a project with glade and pygtk on fedora. > Can you suggest a good IDE? > > _________________________________________________________________ > Hotmail: Trusted email with powerful SPAM protection. > http://clk.atdmt.com/GBL/go/196390707/direct/01/ > From rabidpoobear at gmail.com Thu Jan 21 19:25:21 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 21 Jan 2010 12:25:21 -0600 Subject: [Tutor] need help in python In-Reply-To: References: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> Message-ID: Don't post messages to the list in reply to other messages, it messes up threading. Other than that, you'll have to tell us more about your assignment if you want help. -Luke On Thu, Jan 21, 2010 at 11:48 AM, invincible patriot < invincible_patriot at hotmail.com> wrote: > hi > I am a student and i need soe help regarding my assignmentif some one can > help me il be glad. > > i wil be waiting for the reply > > thanks > > > > ------------------------------ > Date: Thu, 21 Jan 2010 12:33:40 -0500 > From: samueldechamplain at gmail.com > To: tutor at python.org > Subject: [Tutor] Hello > > This is my first message to this mailing list. > I want to create a project with glade and pygtk on fedora. > Can you suggest a good IDE? > > ------------------------------ > Hotmail: Trusted email with powerful SPAM protection. Sign up now. > > _______________________________________________ > 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 webtourist at gmail.com Thu Jan 21 20:07:37 2010 From: webtourist at gmail.com (Robert) Date: Thu, 21 Jan 2010 14:07:37 -0500 Subject: [Tutor] need help in python In-Reply-To: References: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> Message-ID: <8af18dcf1001211107o768110fdr2b4e70fd65cff567@mail.gmail.com> And your question is ? On Thu, Jan 21, 2010 at 12:48 PM, invincible patriot wrote: > hi > I am a student and i need soe help regarding my assignmentif some one can > help me il be glad. > > i wil be waiting for the reply > > thanks > > From webtourist at gmail.com Thu Jan 21 20:10:13 2010 From: webtourist at gmail.com (Robert) Date: Thu, 21 Jan 2010 14:10:13 -0500 Subject: [Tutor] Hello In-Reply-To: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> References: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> Message-ID: <8af18dcf1001211110y487ae7bs34f2d2f29c87e5d9@mail.gmail.com> Check out wingware IDE and Geany. On Thu, Jan 21, 2010 at 12:33 PM, Samuel de Champlain wrote: > This is my first message to this mailing list. > I want to create a project with glade and pygtk on fedora. > Can you suggest a good IDE? > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From dextrous85 at gmail.com Thu Jan 21 20:16:05 2010 From: dextrous85 at gmail.com (vishwajeet singh) Date: Fri, 22 Jan 2010 00:46:05 +0530 Subject: [Tutor] Hello In-Reply-To: References: <10cd5a2c1001210933n1f09ea41t5f9cbd86d9a053aa@mail.gmail.com> Message-ID: <5487b3061001211116ma072660mef34b085f67bd40c@mail.gmail.com> > > On Thu, Jan 21, 2010 at 11:03 PM, Samuel de Champlain < > samueldechamplain at gmail.com> wrote: > >> This is my first message to this mailing list. >> I want to create a project with glade and pygtk on fedora. >> Can you suggest a good IDE? >> > netbeans have worked quite well for me but its heavy weight if you are looking for something light check out komodo. >> _______________________________________________ >> 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 > > -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://singhvishwajeet.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From raghavendra.gv.vanam at gmail.com Fri Jan 22 07:44:05 2010 From: raghavendra.gv.vanam at gmail.com (vanam) Date: Fri, 22 Jan 2010 12:14:05 +0530 Subject: [Tutor] Replacing the string in a file Message-ID: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> Hi all, I have been trying to write a script where in it has to replace a particular string in a file and write back to the file without intact of the contents I have tried below mentioned steps, but of no avail: 1. Created a file by name data.txt and included some text (For instance, ************************************************************************ Then, I started searching for a good book on Python. I couldn't find any! I did find some O'Reilly books but they were either too expensive or were more like a reference manual than a guide. So, I settled for the documentation that came with Python. However, it was too brief and small. It did give a good idea about Python but was not complete. I managed with it since I had previous programming experience, but it was unsuitable for newbies. ************************************************************************ 2.Read the file contents (For this opened the file in read mode -- log = open('data.txt','r') 3.Iterated through the text using for loop for reading the contents in the file -- for x in log: 4.Replaced the word Python with PYTHON as indicated --- x = x.replace('Python','PYTHON') 6.printed the full contents -- It had printed the full contents by replacing the word Python to PYTHON Python string did not get changed to PYTHON for the reasons that i did not open the file in write mode and written the string [Query]: How to write Python string to PYTHON to that file without intact of the full contents I was successful in routing the contents (with changed string to PYTHON) to a different file. And i am aware that opening the file in write mode will wipe out the previous contents. I have tried appending the content which it does but that is not my goal. 7. Closed the files outside for loop -- log.close() -- Raghavendra Vanam From anand.shashwat at gmail.com Fri Jan 22 08:12:01 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 22 Jan 2010 12:42:01 +0530 Subject: [Tutor] Replacing the string in a file In-Reply-To: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> References: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> Message-ID: You can try it by reading all data as string, replacing the string and then write it to target file via opeing it in +w mode. f = open('data.txt', 'rw').read().replace('Python', 'PYTHON') f1 = open('data.txt', 'w') f1.write(f) HTH On Fri, Jan 22, 2010 at 12:14 PM, vanam wrote: > Hi all, > > I have been trying to write a script where in it has to replace a > particular string in a file and write back to the file without intact > of the contents > > I have tried below mentioned steps, but of no avail: > > 1. Created a file by name data.txt and included some text (For > instance, > > ************************************************************************ > Then, I started searching for a good book on Python. I couldn't find > any! I did find some O'Reilly books > but they were either too expensive or were more like a reference > manual than a guide. So, I settled for > the documentation that came with Python. However, it was too brief and > small. It did give a good idea > about Python but was not complete. I managed with it since I had > previous programming experience, but > it was unsuitable for newbies. > ************************************************************************ > > 2.Read the file contents (For this opened the file in read mode -- log > = open('data.txt','r') > > 3.Iterated through the text using for loop for reading the contents in > the file -- for x in log: > > 4.Replaced the word Python with PYTHON as indicated --- x = > x.replace('Python','PYTHON') > > 6.printed the full contents -- It had printed the full contents by > replacing the word Python to PYTHON > > Python string did not get changed to PYTHON for the reasons that i did > not open the file in write mode and written the string > > [Query]: How to write Python string to PYTHON to that file without > intact of the full contents > > I was successful in routing the contents (with changed string to > PYTHON) to a different file. > > And i am aware that opening the file in write mode will wipe out the > previous contents. > > I have tried appending the content which it does but that is not my goal. > > > 7. Closed the files outside for loop -- log.close() > -- > Raghavendra Vanam > _______________________________________________ > 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 Fri Jan 22 08:37:32 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 22 Jan 2010 08:37:32 +0100 Subject: [Tutor] Replacing the string in a file In-Reply-To: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> References: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> Message-ID: vanam, 22.01.2010 07:44: > [Query]: How to write Python string to PYTHON to that file without > intact of the full contents What one would normally do is: read the file (line by line if that's ok in your case), replace the word by the new one, write the new line to a new temporary file. When done, move the new file over the old one. That also makes sure that your changes are 'atomic' (as good as it gets), i.e. your original file is still there when you encounter an error during the replacement run. Stefan From anand.shashwat at gmail.com Fri Jan 22 08:49:59 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 22 Jan 2010 13:19:59 +0530 Subject: [Tutor] Replacing the string in a file In-Reply-To: References: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> Message-ID: Editing original file can be risky at times. If @vanam wants to edit the same fie, he can open the original file, read it, rename it to say 'data.txt.bak' and then write the modified content to the file named as 'data.txt'. This way he gets the data in the file he wants and also have a backup of original file. On Fri, Jan 22, 2010 at 1:07 PM, Stefan Behnel wrote: > vanam, 22.01.2010 07:44: > > [Query]: How to write Python string to PYTHON to that file without > > intact of the full contents > > What one would normally do is: read the file (line by line if that's ok in > your case), replace the word by the new one, write the new line to a new > temporary file. When done, move the new file over the old one. That also > makes sure that your changes are 'atomic' (as good as it gets), i.e. your > original file is still there when you encounter an error during the > replacement run. > > Stefan > > _______________________________________________ > 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 at lsd.co.za Fri Jan 22 09:11:27 2010 From: stefan at lsd.co.za (Stefan Lesicnik) Date: Fri, 22 Jan 2010 10:11:27 +0200 (SAST) Subject: [Tutor] Replacing the string in a file In-Reply-To: <957316801.1030.1264147629325.JavaMail.root@zimbra> Message-ID: <1711198751.1033.1264147887914.JavaMail.root@zimbra> > > vanam, 22.01.2010 07:44: > > > [Query]: How to write Python string to PYTHON to that file without > > intact of the full contents > > What one would normally do is: read the file (line by line if that's > ok in > your case), replace the word by the new one, write the new line to a > new > temporary file. When done, move the new file over the old one. That > also > makes sure that your changes are 'atomic' (as good as it gets), i.e.. > your > original file is still there when you encounter an error during the > replacement run. > > Stefan heys, I have used the fileinput module for this quiet alot. It has an inplace option which does what you want and a backup option that keeps a backup. http://docs.python.org/library/fileinput.html http://www.doughellmann.com/PyMOTW/fileinput/index.html stefan (another stefan) From raghavendra.gv.vanam at gmail.com Fri Jan 22 09:21:31 2010 From: raghavendra.gv.vanam at gmail.com (vanam) Date: Fri, 22 Jan 2010 13:51:31 +0530 Subject: [Tutor] Replacing the string in a file In-Reply-To: References: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> Message-ID: <4499cb6a1001220021h765022f7o74be3d5cb2e32838@mail.gmail.com> Thanks for your mail. As you have suggested i have changed the mode to 'rw' but it is throwing up an error as below ******************* IOError: [Errno 22] invalid mode ('rw') or filename: 'data.txt' ******************* I am using python 2.6.4. But Script is managed to pass with 'a+' mode/r+ mode. log = open('data.txt','r+/a+') for x in log: x = x.replace('Python','PYTHON') print x, log.close() It had properly written and replaced Python to PYTHON. Thanks for your suggestion. On Fri, Jan 22, 2010 at 12:42 PM, Shashwat Anand wrote: > You can try it by reading all data as string, replacing the string and then > write it to target file via opeing it in +w mode. > > f = open('data.txt', 'rw').read().replace('Python', 'PYTHON') > f1 = open('data.txt', > 'w') > f1.write(f) > > HTH > > > On Fri, Jan 22, 2010 at 12:14 PM, vanam > wrote: >> >> Hi all, >> >> I have been trying to write a script where in it has to replace a >> particular string in a file and write back to the file without intact >> of the contents >> >> I have tried below mentioned steps, but of no avail: >> >> 1. Created a file by name data.txt and included some text (For >> instance, >> >> ************************************************************************ >> Then, I started searching for a good book on Python. I couldn't find >> any! I did find some O'Reilly books >> but they were either too expensive or were more like a reference >> manual than a guide. So, I settled for >> the documentation that came with Python. However, it was too brief and >> small. It did give a good idea >> about Python but was not complete. I managed with it since I had >> previous programming experience, but >> it was unsuitable for newbies. >> ************************************************************************ >> >> 2.Read the file contents (For this opened the file in read mode -- log >> = open('data.txt','r') >> >> 3.Iterated through the text using for loop for reading the contents in >> the file -- for x in log: >> >> 4.Replaced the word ?Python with PYTHON as indicated --- x ?= >> x.replace('Python','PYTHON') >> >> 6.printed the full contents -- It had printed the full contents by >> replacing the word Python to PYTHON >> >> Python string did not get changed to PYTHON for the reasons that i did >> not open the file in write mode and written the string >> >> [Query]: How to write Python string to PYTHON to that file without >> intact of the full contents >> >> I was successful in routing the contents (with changed string to >> PYTHON) to a different file. >> >> And i am aware that opening the file in write mode will wipe out the >> previous contents. >> >> I have tried appending the content which it does but that is not my goal. >> >> >> 7. Closed the files outside for loop -- log.close() >> -- >> Raghavendra ?Vanam >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > -- Raghavendra Vanam From anand.shashwat at gmail.com Fri Jan 22 09:24:51 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 22 Jan 2010 13:54:51 +0530 Subject: [Tutor] Replacing the string in a file In-Reply-To: <4499cb6a1001220021h765022f7o74be3d5cb2e32838@mail.gmail.com> References: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> <4499cb6a1001220021h765022f7o74be3d5cb2e32838@mail.gmail.com> Message-ID: @vanam: If you open the file again with only '+w' and not '+rw', I guess you'll not be getting this error - > IOError: [Errno 22] invalid mode ('rw') or filename: 'data.txt' On Fri, Jan 22, 2010 at 1:51 PM, vanam wrote: > Thanks for your mail. > > As you have suggested i have changed the mode to 'rw' but it is > throwing up an error as below > > ******************* > IOError: [Errno 22] invalid mode ('rw') or filename: 'data.txt' > ******************* > I am using python 2.6.4. > > But Script is managed to pass with 'a+' mode/r+ mode. > > log = open('data.txt','r+/a+') > for x in log: > x = x.replace('Python','PYTHON') > print x, > log.close() > > It had properly written and replaced Python to PYTHON. > > Thanks for your suggestion. > > > > On Fri, Jan 22, 2010 at 12:42 PM, Shashwat Anand > wrote: > > You can try it by reading all data as string, replacing the string and > then > > write it to target file via opeing it in +w mode. > > > > f = open('data.txt', 'rw').read().replace('Python', 'PYTHON') > > f1 = open('data.txt', > > 'w') > > f1.write(f) > > > > HTH > > > > > > On Fri, Jan 22, 2010 at 12:14 PM, vanam > > wrote: > >> > >> Hi all, > >> > >> I have been trying to write a script where in it has to replace a > >> particular string in a file and write back to the file without intact > >> of the contents > >> > >> I have tried below mentioned steps, but of no avail: > >> > >> 1. Created a file by name data.txt and included some text (For > >> instance, > >> > >> ************************************************************************ > >> Then, I started searching for a good book on Python. I couldn't find > >> any! I did find some O'Reilly books > >> but they were either too expensive or were more like a reference > >> manual than a guide. So, I settled for > >> the documentation that came with Python. However, it was too brief and > >> small. It did give a good idea > >> about Python but was not complete. I managed with it since I had > >> previous programming experience, but > >> it was unsuitable for newbies. > >> ************************************************************************ > >> > >> 2.Read the file contents (For this opened the file in read mode -- log > >> = open('data.txt','r') > >> > >> 3.Iterated through the text using for loop for reading the contents in > >> the file -- for x in log: > >> > >> 4.Replaced the word Python with PYTHON as indicated --- x = > >> x.replace('Python','PYTHON') > >> > >> 6.printed the full contents -- It had printed the full contents by > >> replacing the word Python to PYTHON > >> > >> Python string did not get changed to PYTHON for the reasons that i did > >> not open the file in write mode and written the string > >> > >> [Query]: How to write Python string to PYTHON to that file without > >> intact of the full contents > >> > >> I was successful in routing the contents (with changed string to > >> PYTHON) to a different file. > >> > >> And i am aware that opening the file in write mode will wipe out the > >> previous contents. > >> > >> I have tried appending the content which it does but that is not my > goal. > >> > >> > >> 7. Closed the files outside for loop -- log.close() > >> -- > >> Raghavendra Vanam > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > > > > > > > > -- > Raghavendra Vanam > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Fri Jan 22 09:46:19 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 22 Jan 2010 09:46:19 +0100 Subject: [Tutor] Replacing the string in a file In-Reply-To: <1711198751.1033.1264147887914.JavaMail.root@zimbra> References: <957316801.1030.1264147629325.JavaMail.root@zimbra> <1711198751.1033.1264147887914.JavaMail.root@zimbra> Message-ID: Stefan Lesicnik, 22.01.2010 09:11: > I have used the fileinput module for this quiet alot. It has an inplace > option which does what you want and a backup option that keeps a backup. > > http://docs.python.org/library/fileinput.html > http://www.doughellmann.com/PyMOTW/fileinput/index.html Ah, right, I almost forgot about this one: http://xkcd.com/413/ Stefan From anand.shashwat at gmail.com Fri Jan 22 10:28:33 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 22 Jan 2010 14:58:33 +0530 Subject: [Tutor] Replacing the string in a file In-Reply-To: References: <957316801.1030.1264147629325.JavaMail.root@zimbra> <1711198751.1033.1264147887914.JavaMail.root@zimbra> Message-ID: and there is the everlasting : http://xkcd.com/353/ :D On Fri, Jan 22, 2010 at 2:16 PM, Stefan Behnel wrote: > Stefan Lesicnik, 22.01.2010 09:11: > > I have used the fileinput module for this quiet alot. It has an inplace > > option which does what you want and a backup option that keeps a backup. > > > > http://docs.python.org/library/fileinput.html > > http://www.doughellmann.com/PyMOTW/fileinput/index.html > > Ah, right, I almost forgot about this one: > > http://xkcd.com/413/ > > Stefan > > _______________________________________________ > 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 davea at ieee.org Fri Jan 22 12:23:53 2010 From: davea at ieee.org (Dave Angel) Date: Fri, 22 Jan 2010 06:23:53 -0500 Subject: [Tutor] Replacing the string in a file In-Reply-To: <4499cb6a1001220021h765022f7o74be3d5cb2e32838@mail.gmail.com> References: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> <4499cb6a1001220021h765022f7o74be3d5cb2e32838@mail.gmail.com> Message-ID: <4B598AC9.6090608@ieee.org> vanam wrote: > Thanks for your mail. > > As you have suggested i have changed the mode to 'rw' but it is > throwing up an error as below > > ******************* > IOError: [Errno 22] invalid mode ('rw') or filename: 'data.txt' > ******************* > I am using python 2.6.4. > > But Script is managed to pass with 'a+' mode/r+ mode. > > log = open('data.txt','r+/a+') > for x in log: > x = x.replace('Python','PYTHON') > print x, > log.close() > > It had properly written and replaced Python to PYTHON. > > Thanks for your suggestion. > > > > That won't work. Better test it some more. Without some form of write() call, you're not changing the file. There are several workable suggestions in this thread, and I think fileinput is the easiest one. DaveA From andreas at kostyrka.org Fri Jan 22 12:53:00 2010 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 22 Jan 2010 12:53:00 +0100 Subject: [Tutor] Replacing the string in a file In-Reply-To: <4B598AC9.6090608@ieee.org> References: <4499cb6a1001212244x5b93647bva5e5bb9f91a332a0@mail.gmail.com> <4499cb6a1001220021h765022f7o74be3d5cb2e32838@mail.gmail.com> <4B598AC9.6090608@ieee.org> Message-ID: <201001221253.00270.andreas@kostyrka.org> The modes for updating files are + suffixed. r+ Open for reading and writing. The stream is positioned at the beginning of the file. w+ Open for reading and writing. The file is created if it does not exist, otherwise it is trun? cated. The stream is positioned at the beginning of the file. a+ Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file. The bigger issue here is, that depending upon your filesystem it might be faster to just write a new file with the changed content. If you want to replace it inplace, I'd consider something like that: import mmap f = open("/tmp/test.txt", "r+") m = mmap.mmap(f.fileno(), 0) idx = 0 count = 0 while True: idx = m.find("file", idx) if idx >= 0: m[idx:idx + 4] = "FILE" count += 1 idx += 1 else: print "%d file => FILE replaces" % count break m.close() f.close() andreas at andidesk:/tmp$ python ./test.py 39 file => FILE replaces You've got basically 3 strategies: 1) read the file completely into memory via read => uses memory. 2) read the file block-wise => complicated because you need to recognize matches that are split between blocks. 3) memory map the file => uses address space, but the OS does know that you are using that "memory" to access the file. 1 is the shortest code, most resource usage. 2 is complicated code, low resource usage, 3 is slightly longer (because mmap objects have no .replace method), and comparable resource usage to 2. Andreas Andreas Am Freitag, 22. Januar 2010 12:23:53 schrieb Dave Angel: > vanam wrote: > > Thanks for your mail. > > > > As you have suggested i have changed the mode to 'rw' but it is > > throwing up an error as below > > > > ******************* > > IOError: [Errno 22] invalid mode ('rw') or filename: 'data.txt' > > ******************* > > I am using python 2.6.4. > > > > But Script is managed to pass with 'a+' mode/r+ mode. > > > > log = open('data.txt','r+/a+') > > for x in log: > > x = x.replace('Python','PYTHON') > > print x, > > log.close() > > > > It had properly written and replaced Python to PYTHON. > > > > Thanks for your suggestion. > > > > > > > > That won't work. Better test it some more. Without some form of > write() call, you're not changing the file. > > > There are several workable suggestions in this thread, and I think > fileinput is the easiest one. > > DaveA > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From norman at khine.net Fri Jan 22 14:11:42 2010 From: norman at khine.net (Norman Khine) Date: Fri, 22 Jan 2010 14:11:42 +0100 Subject: [Tutor] parse text file Message-ID: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> Hello, I have the following http://paste.lisp.org/display/93732 txt file. >From this I would like to extract ... 'ACP' + '
En savoir plus' ); ... map.addOverlay(marqueur[1]);var latlng = new GLatLng(9.696333, 122.985992); so that i get a CSV file: "ACP", "acp.html" , "9.69633", "122.985992" This is what I have so far: >>> file=open('google_map_code.txt', 'r') >>> data = repr( file.read().decode('utf-8') ) >>> from BeautifulSoup import BeautifulStoneSoup >>> soup = BeautifulStoneSoup(data) >>> strongs = soup.findAll('strong') >>> strongs [ALTER TRADE CORPORATION, ANAPQUI, APICOOP / VALVIDIA, APIKRI, ... >>> path = soup.findAll('a') >>> path [En savoir plus, En savoir plus, ... but my problem comes when i try to list the GLatLng: GLatLng(9.696333, 122.985992); >>> StartingWithGLatLng = soup.findAll(re.compile('GLatLng')) >>> StartingWithGLatLng [] Thanks Norman From Katisss at gmx.de Fri Jan 22 22:44:50 2010 From: Katisss at gmx.de (katrin schmid) Date: Fri, 22 Jan 2010 22:44:50 +0100 Subject: [Tutor] create an object from a class in dll with ctypes? In-Reply-To: References: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC> Message-ID: <20100122214450.5320@gmx.net> hi, it worked great, i am just wondering if the resulting .pyd is plattform dependent? If i create one on windows would linux user need another one? Thank you, katrin -------- Original-Nachricht -------- > Datum: Tue, 19 Jan 2010 23:49:14 -0800 > Von: "Mark Tolonen" > An: tutor at python.org > Betreff: Re: [Tutor] create an object from a class in dll with ctypes? > > "katrin schmid" wrote in message > news:0EDDA7DDDFF84D639352526B72DBF8C7 at katisssPC... > > hi, > > i am getting started with ctypes in python 2.5 and was wondering if > > i would be able to create an object from the class in my dll somehow. > > I only found examples that show how to access a function but the > > function i want to call is part of a cpp class in my dll... > > ctypes is for C DLLs. You might want to look at www.swig.org instead. > > -Mark > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Haiti-Nothilfe! Helfen Sie per SMS: Sende UIHAITI an die Nummer 81190. Von 5 Euro je SMS (zzgl. SMS-Geb?hr) gehen 4,83 Euro an UNICEF. From norman at khine.net Sat Jan 23 00:22:41 2010 From: norman at khine.net (Norman Khine) Date: Sat, 23 Jan 2010 00:22:41 +0100 Subject: [Tutor] parse text file In-Reply-To: <20100122194422.5ab7ea2e@o> References: <9c2c8ffb1001220511v25581c48x118ff743a0db1c21@mail.gmail.com> <20100122194422.5ab7ea2e@o> Message-ID: <9c2c8ffb1001221522h15a375d6h81f7ff2bc09ca92@mail.gmail.com> 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 > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ > -- %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From alan.gauld at btinternet.com Sat Jan 23 01:13:53 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Jan 2010 00:13:53 -0000 Subject: [Tutor] create an object from a class in dll with ctypes? References: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC> <20100122214450.5320@gmx.net> Message-ID: "katrin schmid" wrote > if the resulting .pyd is plattform dependent? > If i create one on windows would linux user need another one? A Windows DLL will not work on Linux and a Linux library will not work on Windows. You need one per OS. Alan G. From Katisss at gmx.de Sat Jan 23 03:15:22 2010 From: Katisss at gmx.de (katrin schmid) Date: Sat, 23 Jan 2010 03:15:22 +0100 Subject: [Tutor] create an object from a class in dll with ctypes? In-Reply-To: References: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC> <20100122214450.5320@gmx.net> Message-ID: <20100123021522.155730@gmx.net> hi, so how about 32 and 64 bit, do they need separat versions, too? So a pyd is an "actual" dll? Regrads, katrin -------- Original-Nachricht -------- > Datum: Sat, 23 Jan 2010 00:13:53 -0000 > Von: "Alan Gauld" > An: tutor at python.org > Betreff: Re: [Tutor] create an object from a class in dll with ctypes? > > "katrin schmid" wrote > > if the resulting .pyd is plattform dependent? > > If i create one on windows would linux user need another one? > > A Windows DLL will not work on Linux and a Linux library > will not work on Windows. You need one per OS. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Haiti-Nothilfe! Helfen Sie per SMS: Sende UIHAITI an die Nummer 81190. Von 5 Euro je SMS (zzgl. SMS-Geb?hr) gehen 4,83 Euro an UNICEF. From metolone+gmane at gmail.com Sat Jan 23 05:42:17 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 22 Jan 2010 20:42:17 -0800 Subject: [Tutor] create an object from a class in dll with ctypes? References: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC><20100122214450.5320@gmx.net> <20100123021522.155730@gmx.net> Message-ID: "katrin schmid" wrote in message news:20100123021522.155730 at gmx.net... > hi, > so how about 32 and 64 bit, > do they need separat versions, too? > So a pyd is an "actual" dll? > Regrads, > katrin Yes, to both questions. -Mark From Katisss at gmx.de Sat Jan 23 06:43:50 2010 From: Katisss at gmx.de (katrin schmid) Date: Sat, 23 Jan 2010 06:43:50 +0100 Subject: [Tutor] create an object from a class in dll with ctypes? In-Reply-To: References: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC><20100122214450.5320@gmx.net> <20100123021522.155730@gmx.net> Message-ID: <20100123054350.155720@gmx.net> hi, and there is no portable way of distributing it? I could tranlate the cpp code to python but its really lame.... Regards, katrin -------- Original-Nachricht -------- > Datum: Fri, 22 Jan 2010 20:42:17 -0800 > Von: "Mark Tolonen" > An: tutor at python.org > Betreff: Re: [Tutor] create an object from a class in dll with ctypes? > > "katrin schmid" wrote in message > news:20100123021522.155730 at gmx.net... > > hi, > > so how about 32 and 64 bit, > > do they need separat versions, too? > > So a pyd is an "actual" dll? > > Regrads, > > katrin > > Yes, to both questions. > > -Mark > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Haiti-Nothilfe! Helfen Sie per SMS: Sende UIHAITI an die Nummer 81190. Von 5 Euro je SMS (zzgl. SMS-Geb?hr) gehen 4,83 Euro an UNICEF. From Katisss at gmx.de Sat Jan 23 06:49:35 2010 From: Katisss at gmx.de (katrin schmid) Date: Sat, 23 Jan 2010 06:49:35 +0100 Subject: [Tutor] create an object from a class in dll with ctypes? In-Reply-To: References: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC> <20100122214450.5320@gmx.net> Message-ID: <20100123054935.155760@gmx.net> hi, so could i build a 64-bit windows version on win 32? And how? I have just been asked ... Regards, katrin -------- Original-Nachricht -------- > Datum: Sat, 23 Jan 2010 00:13:53 -0000 > Von: "Alan Gauld" > An: tutor at python.org > Betreff: Re: [Tutor] create an object from a class in dll with ctypes? > > "katrin schmid" wrote > > if the resulting .pyd is plattform dependent? > > If i create one on windows would linux user need another one? > > A Windows DLL will not work on Linux and a Linux library > will not work on Windows. You need one per OS. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Haiti-Nothilfe! Helfen Sie per SMS: Sende UIHAITI an die Nummer 81190. Von 5 Euro je SMS (zzgl. SMS-Geb?hr) gehen 4,83 Euro an UNICEF. -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser From alan.gauld at btinternet.com Sat Jan 23 08:31:02 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Jan 2010 07:31:02 -0000 Subject: [Tutor] create an object from a class in dll with ctypes? References: <0EDDA7DDDFF84D639352526B72DBF8C7@katisssPC><20100122214450.5320@gmx.net> <20100123021522.155730@gmx.net> <20100123054350.155720@gmx.net> Message-ID: "katrin schmid" wrote > and there is no portable way of distributing it? > I could tranlate the cpp code to python but its really lame.... Native code is native code I'm afraid. You have to rebuild it for every platform. Thats one reason interpreted languages are becoming more popular because they are portable. The downside of portability is loss of speed. Alan G. From dwightdhutto at yahoo.com Sun Jan 24 07:14:50 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Sat, 23 Jan 2010 22:14:50 -0800 (PST) Subject: [Tutor] The magic parentheses Message-ID: <900352.59666.qm@web45310.mail.sp1.yahoo.com> Hi, This is my first post to the list, so tell me if I'm posting incorrectly. I'm creating a script, http://python.codepad.org/mHyqbJ2z that gives the area of two circles, based on their radius, and displays the difference between the two results. My problem is when the results are printed, I get this: Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 IDLE 2.6.4????? ==== No Subprocess ==== >>> ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') >>> ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') >>> .. The parentheses, as well as the apostrophes and commas. I'm sure it's the way I'm having the results printed after it's through, but not sure how to correct it. I tried writing the 'Variable 1' and '2', as well as the 'is greater than' within the y, and z local variables in the def return_difference_of12, and got the same result as when I listed the portions of the printed result's sentence in the non-local variables I have now(I'm new to Python, so I'm not sure if this would be the correct term). Any help would be appreciated. Thanks in advance. David -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Jan 24 08:48:43 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 24 Jan 2010 18:48:43 +1100 Subject: [Tutor] The magic parentheses In-Reply-To: <900352.59666.qm@web45310.mail.sp1.yahoo.com> References: <900352.59666.qm@web45310.mail.sp1.yahoo.com> Message-ID: On 01/24/10 17:14, David Hutto wrote: > Hi, > > This is my first post to the list, so tell me if I'm posting incorrectly. > > I'm creating a script, http://python.codepad.org/mHyqbJ2z that gives the area of two circles, based on their radius, and displays the difference between the two results. > > My problem is when the results are printed, I get this: > > Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 > IDLE 2.6.4 ==== No Subprocess ==== >>>> > ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') >>>> > ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') >>>> > ... > The parentheses, as well as the apostrophes and commas. I'm sure it's the way I'm having the results printed after it's through, but not sure how to correct it. > > I tried writing the 'Variable 1' and '2', as well as the 'is greater > than' within the y, and z local variables in the def return_difference_of12, and got the same result as when I > listed the portions of the printed result's sentence in the non-local variables I have now(I'm new to Python, so I'm not sure if this would be the correct term). > > Any help would be appreciated. Thanks in advance. > OT: for short snippets like this, you should just paste it in the post rather than using codepad """ y = v1,var1,v3,v2,var2,period print y """ is not the same as """ print v1,var1,v3,v2,var2,period """ the first code creates a tuple, assign it to y, then prints the tuple; the latter prints the bunch of items separated with space. From hugo.yoshi at gmail.com Sun Jan 24 08:49:08 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 24 Jan 2010 08:49:08 +0100 Subject: [Tutor] The magic parentheses In-Reply-To: <900352.59666.qm@web45310.mail.sp1.yahoo.com> References: <900352.59666.qm@web45310.mail.sp1.yahoo.com> Message-ID: <29179d161001232349x105f2780x96ba0fdc754db4c9@mail.gmail.com> On Sun, Jan 24, 2010 at 7:14 AM, David Hutto wrote: > Hi, > > This is my first post to the list, so tell me if I'm posting incorrectly. > > I'm creating a script, http://python.codepad.org/mHyqbJ2z that gives the > area of two circles, based on their radius, and displays the difference > between the two results. > > My problem is when the results are printed, I get this: > > Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit > (Intel)] on win32 > IDLE 2.6.4 ==== No Subprocess ==== > >>> > ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') > >>> > ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') > >>> > . > The parentheses, as well as the apostrophes and commas. I'm sure it's the > way I'm having the results printed after it's through, but not sure how to > correct it. > > I tried writing the 'Variable 1' and '2', as well as the 'is greater than' > within the y, and z local variables in the def return_difference_of12, and > got the same result as when I listed the portions of the printed result's > sentence in the non-local variables I have now(I'm new to Python, so I'm not > sure if this would be the correct term). > > Any help would be appreciated. Thanks in advance. > > > David > > y = v1,var1,v3,v2,var2,period print y The first line assigns a tuple to y. The parentheses and commas is the way tuples are printed. To avoid those, you could either pass all the arguments directly to print, or use some string formatting instead of constructing a tuple: >>> a = 'this', 'is', 'a tuple' >>> a ('this', 'is' , 'a tuple') >>> print a (1, 2, 3) >>> print 'this', 'is passed', 'to print directly' 1 2 3 >>> print "this is {0}".format("formatted") this is formatted Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 24 08:53:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Jan 2010 07:53:59 -0000 Subject: [Tutor] The magic parentheses References: <900352.59666.qm@web45310.mail.sp1.yahoo.com> Message-ID: "David Hutto" wrote > This is my first post to the list, so tell me if I'm posting incorrectly. You are doing fine. Welcome. > My problem is when the results are printed, I get this: > > >>> > ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') > The parentheses, as well as the apostrophes and commas. > I'm sure it's the way I'm having the results printed after it's > through, but not sure how to correct it. You have two problems in your code(at least!) ---------------def area2(radius): area2r = 3.14159 * mainvar2**2 return area2r print area2r --------The print statement will never be called because the return statement forces an exit from the function. ------------------------- def return_difference_of12(var1,var2): if var1 - var2 > 0: y = v1,var1,v3,v2,var2,period print y elif var2 - var1 > 0: z = v2,var2,v3,v2,var1,period print z ----------------------------The assignments to y and z create tuples (a,b,c...)So you are asking to print a tuple and Python represents tuples by putting parens around the contents.To print them as a string use the join() method of a string using an empty string:print ''.join([str(s) for s in y])However this is an unusual way to print this type of output,It would be more normal to use a format string:print "Variable2: %f id greater than Variable1: %f." % (var1,var2)This reduces the number of variables needed and also gives you much more control over layout because the %f markers can be augmented with width specifiers, justificationhints etc.You can store the entire format string in a variable if you wish - especiaslly if you want to use it multiple times - but in your case the strings only appear once so I wouldn't bother.HTH,-- Alan GauldAuthor of the Learn to Program web sitehttp://www.alan-g.me.uk/ From dwightdhutto at yahoo.com Sun Jan 24 09:17:50 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Sun, 24 Jan 2010 00:17:50 -0800 (PST) Subject: [Tutor] The magic parentheses Message-ID: <78513.70608.qm@web45304.mail.sp1.yahoo.com> Thanks for the solutions and the quick responses. I just removed the variable and used print, I thought they would be considered the same whether as? a variable, or as a direct line, guess not. Thanks again, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Sun Jan 24 09:24:37 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 24 Jan 2010 13:54:37 +0530 Subject: [Tutor] The magic parentheses In-Reply-To: References: <900352.59666.qm@web45310.mail.sp1.yahoo.com> Message-ID: @David, Alan and rest have clarified your doubt I guess. However let me point you towards some other mistakes. def area1(radius): area1r = 3.14159 * mainvar1**2 return area1r print area1r def area2(radius): area2r = 3.14159 * mainvar2**2 return area2r print area2r Here you created two functions for the single purpose of calculating area. Why not just do, def area(radius): return math.pi * radius * radius Functions are created for doing repetitive tasks IMHO. But you just created them for the heck of it. Ofcourse there is issue of writing dead-code (i.e. lines that will never be executed), the print after return as Alan already pointed out. Also you created, a function that displays the difference between the two results. def return_difference_of12(var1,var2): if var1 - var2 > 0: y = v1,var1,v3,v2,var2,period print y elif var2 - var1 > 0: z = v2,var2,v3,v2,var1,period print z Why not create something simple like this : def return_difference(var1, var2): if var1 > var2: print 'Variable 1', var1, 'is greater than Variable 2', var2, '.' elif var2 > var1: print 'Variable 2', var2, 'is greater than Variable 1', var1, '.' else: print 'Variable 1', var1, 'is equal Variable 2', var2, '.' No need for explicit formation of tuple if all you wish is just a print statement. Regards, ~Shashwat On Sun, Jan 24, 2010 at 1:23 PM, Alan Gauld wrote: > > "David Hutto" wrote > > This is my first post to the list, so tell me if I'm posting incorrectly. >> > > You are doing fine. Welcome. > > My problem is when the results are printed, I get this: >> >> >>> >> ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') >> > > The parentheses, as well as the apostrophes and commas. >> I'm sure it's the way I'm having the results printed after it's >> through, but not sure how to correct it. >> > > You have two problems in your code(at least!) > ---------------def area2(radius): > area2r = 3.14159 * mainvar2**2 > return area2r > print area2r > --------The print statement will never be called because the return > statement forces an exit from the function. > ------------------------- > def return_difference_of12(var1,var2): > if var1 - var2 > 0: > > y = v1,var1,v3,v2,var2,period > print y > elif var2 - var1 > 0: > z = v2,var2,v3,v2,var1,period > print z > ----------------------------The assignments to y and z create tuples > (a,b,c...)So you are asking to print a tuple and Python represents tuples by > putting parens around the contents.To print them as a string use the join() > method of a string using an empty string:print ''.join([str(s) for s in > y])However this is an unusual way to print this type of output,It would be > more normal to use a format string:print "Variable2: %f id greater than > Variable1: %f." % (var1,var2)This reduces the number of variables needed and > also gives you much more control over layout because the %f markers can be > augmented with width specifiers, justificationhints etc.You can store the > entire format string in a variable if you wish - especiaslly if you want to > use it multiple times - but in your case the strings only appear once so I > wouldn't bother.HTH,-- Alan GauldAuthor of the Learn to Program web > sitehttp://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 bermanrl at cfl.rr.com Sun Jan 24 17:13:37 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 24 Jan 2010 11:13:37 -0500 Subject: [Tutor] Is it pythonesque Message-ID: <002f01ca9d10$2fe08000$8fa18000$@rr.com> Good morning, Given the following code snippets: def getuserinput(): while True: s1 = raw_input('Enter fraction as N,D or 0,0 to exit>>') delim = s1.find(',') if delim < 0: print 'invalid user input' else: n = int(s1[0:delim]) d = int(s1[delim+1::]) return n,d def main(): while True: n,d = getuserinput() if n == 0 or d == 0: return 0 n and d are always returned provided the input is given as n,d. n/d will print an error message and the loop will reiterate until the user format is correct. Please note there is no true ending return for getuserinput() as it is hung off an if statement and if by some chance it breaks, it should return None which will abort the program. While I suspect this style is devious, is it dangerous or 'wrong' to use. Comments and other renditions are most welcome. Thank you, Robert Berman -------------- next part -------------- An HTML attachment was scrubbed... URL: From shantanoo at gmail.com Sun Jan 24 17:30:11 2010 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Sun, 24 Jan 2010 22:00:11 +0530 Subject: [Tutor] Is it pythonesque In-Reply-To: <002f01ca9d10$2fe08000$8fa18000$@rr.com> References: <002f01ca9d10$2fe08000$8fa18000$@rr.com> Message-ID: <9CF9BEBD-D99B-4EEF-8FB3-F0122D1E59F4@gmail.com> If the input has more than one ',', e.g. '1,2,3'. You may like to use 'split' function, and avoid find. On 24-Jan-2010, at 9:43 PM, Robert Berman wrote: > Good morning, > > Given the following code snippets: > > def getuserinput(): > while True: > s1 = raw_input('Enter fraction as N,D or 0,0 to exit>>') > delim = s1.find(',') > if delim < 0: > print 'invalid user input' > else: > n = int(s1[0:delim]) > d = int(s1[delim+1::]) > return n,d > > def main(): > while True: > n,d = getuserinput() > if n == 0 or d == 0: return 0 > > n and d are always returned provided the input is given as n,d. n/d will print an error message and the loop will reiterate until the user format is correct. Please note there is no true ending return for getuserinput() as it is hung off an if statement and if by some chance it breaks, it should return None which will abort the program. While I suspect this style is devious, is it dangerous or ?wrong? to use. Comments and other renditions are most welcome. > > Thank you, > > Robert Berman > > _______________________________________________ > 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 Sun Jan 24 18:08:04 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Jan 2010 17:08:04 -0000 Subject: [Tutor] The magic parentheses References: <900352.59666.qm@web45310.mail.sp1.yahoo.com> <29179d161001232349x105f2780x96ba0fdc754db4c9@mail.gmail.com> Message-ID: "Hugo Arts" wrote >>>> print "this is {0}".format("formatted") > this is formatted Caveat: this style only works in Python 3.0 upwards (or maybe in 2.6/2.7?) Alan G. From alan.gauld at btinternet.com Sun Jan 24 18:17:26 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Jan 2010 17:17:26 -0000 Subject: [Tutor] Is it pythonesque References: <002f01ca9d10$2fe08000$8fa18000$@rr.com> Message-ID: "Robert Berman" wrote > def getuserinput(): > while True: > s1 = raw_input('Enter fraction as N,D or 0,0 to exit>>') > delim = s1.find(',') > if delim < 0: > print 'invalid user input' > else: > n = int(s1[0:delim]) > d = int(s1[delim+1::]) > return n,d Personally I'd do this with try: n,d = s1.split(',') return int(n),int(d) except ValueError: print 'invalid user input' continue Note ValueError works for both the int conversion and the split() assignment > def main(): > while True: > n,d = getuserinput() > if n == 0 or d == 0: return 0 > correct. Please note there is no true ending return for getuserinput() as > it > is hung off an if statement and if by some chance it breaks, it should > return None which will abort the program. Since you are inside an infinite loop you should only break if you get an uncaught exception which will generate a stack trace anyhow That seems fair enough to me... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bermanrl at cfl.rr.com Sun Jan 24 20:10:41 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 24 Jan 2010 14:10:41 -0500 Subject: [Tutor] Is it pythonesque In-Reply-To: References: <002f01ca9d10$2fe08000$8fa18000$@rr.com> Message-ID: <004401ca9d28$ebd6b550$c3841ff0$@rr.com> Thank you for the snippet and the insight. Robert -----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 Alan Gauld Sent: Sunday, January 24, 2010 12:17 PM To: tutor at python.org Subject: Re: [Tutor] Is it pythonesque "Robert Berman" wrote > def getuserinput(): > while True: > s1 = raw_input('Enter fraction as N,D or 0,0 to exit>>') > delim = s1.find(',') > if delim < 0: > print 'invalid user input' > else: > n = int(s1[0:delim]) > d = int(s1[delim+1::]) > return n,d Personally I'd do this with try: n,d = s1.split(',') return int(n),int(d) except ValueError: print 'invalid user input' continue Note ValueError works for both the int conversion and the split() assignment > def main(): > while True: > n,d = getuserinput() > if n == 0 or d == 0: return 0 > correct. Please note there is no true ending return for getuserinput() as > it > is hung off an if statement and if by some chance it breaks, it should > return None which will abort the program. Since you are inside an infinite loop you should only break if you get an uncaught exception which will generate a stack trace anyhow That seems fair enough to me... 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 From kent37 at tds.net Sun Jan 24 21:28:44 2010 From: kent37 at tds.net (Kent Johnson) Date: Sun, 24 Jan 2010 15:28:44 -0500 Subject: [Tutor] The magic parentheses In-Reply-To: References: <900352.59666.qm@web45310.mail.sp1.yahoo.com> <29179d161001232349x105f2780x96ba0fdc754db4c9@mail.gmail.com> Message-ID: <1c2a2c591001241228k4e47c0d9ref0256ae7c3086a0@mail.gmail.com> On Sun, Jan 24, 2010 at 12:08 PM, Alan Gauld wrote: > > "Hugo Arts" wrote >>>>> >>>>> print "this is {0}".format("formatted") >> >> this is formatted > > Caveat: > this style only works in Python 3.0 upwards ?(or maybe in 2.6/2.7?) It's in 2.6 http://docs.python.org/library/stdtypes.html#str.format Kent From lie.1296 at gmail.com Mon Jan 25 00:21:57 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 25 Jan 2010 10:21:57 +1100 Subject: [Tutor] The magic parentheses In-Reply-To: <78513.70608.qm@web45304.mail.sp1.yahoo.com> References: <78513.70608.qm@web45304.mail.sp1.yahoo.com> Message-ID: On 01/24/10 19:17, David Hutto wrote: > Thanks > for the solutions and the quick responses. I just removed the variable > and used print, I thought they would be considered the same whether as > a variable, or as a direct line, guess not. > what is equivalent: print (a, b, c) and x = a, b, c print x both construct a tuple and prints a,b,c as tuple From alan.gauld at btinternet.com Mon Jan 25 02:06:45 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Jan 2010 01:06:45 -0000 Subject: [Tutor] The magic parentheses References: <78513.70608.qm@web45304.mail.sp1.yahoo.com> Message-ID: "Lie Ryan" wrote >> and used print, I thought they would be considered the same whether as >> a variable, or as a direct line, guess not. > what is equivalent: > print (a, b, c) > > and > x = a, b, c > print x > > both construct a tuple and prints a,b,c as tuple Not quite: >>> a = 1 >>> b = 2 >>> c = 3 >>> x = a,b,c >>> print a,b,c 1 2 3 >>> print x (1, 2, 3) >>> The first form prints multiple values the second prints the repr of a single tuple value. The output is different. Alan G. From alan.gauld at btinternet.com Mon Jan 25 02:11:21 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Jan 2010 01:11:21 -0000 Subject: [Tutor] Updated topic on my tutorial Message-ID: I don't normally announce new toppics as I translate them to v3 however I've done quite a bit of rework/expansion to my OOP topic, including adding some basic stuff about UML diagrams. I'm interested in any feedback, especially whether the UML helps or hinders understanding! And of course any errors you see - there will almost certainly be a few! The direct link is http://www.alan-g.me.uk/l2p/tutclass.htm Regards, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dwightdhutto at yahoo.com Mon Jan 25 03:31:05 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Sun, 24 Jan 2010 18:31:05 -0800 (PST) Subject: [Tutor] The magic parentheses Message-ID: <171264.84738.qm@web45315.mail.sp1.yahoo.com> Re: [Tutor] The magic parentheses Sunday, January 24, 2010 9:28 PM From: "David Hutto" Add sender to Contacts To: "Alan Gauld" --- On Sun, 1/24/10, Alan Gauld wrote: > From: Alan Gauld > Subject: Re: [Tutor] The magic parentheses > To: tutor at python.org > Date: Sunday, January 24, 2010, 8:06 PM > > "Lie Ryan" > wrote > >> and used print, I thought they would be considered > the same whether as a variable, or as a direct line, guess > not. > > what is equivalent: > > print (a, b, c) > > > > and > > x = a, b, c > > print x > > > > both construct a tuple and prints a,b,c as tuple > > Not quite: > > >>> a = 1 > >>> b = 2 > >>> c = 3 > >>> x = a,b,c > >>> print a,b,c > 1 2 3 > >>> print x > (1, 2, 3) > >>> > > The first form prints multiple values the second prints the > repr of a single tuple value. The output is different. > > Alan G. > So 'print a,b,c' says display the values of a,b,c in the sequence of a,b,c given. 'print x' says print the value of x, x grabs a's value, b's value, and c's value, and displays the values for print. So the sequence becomes a tuple because it's a value of values, and it's sum comes back in the form of a tuple, not an actual end variable. In other words the second leap to find the values of a,b,c for value x, makes the result printed for x(x becomes an array of other data a tuple, correct? Now if I want to turn the first values listed under x into tuples(or use the format function that I think was named in another reply to return the non-tuple version of the value for x and I'm going to try it in a few min) of the other two variables, like below: g = f a = b,c b = a,c c = a,g x = a,b,c This is off the topic I think, so I'll repost under another if necessary, but how do I avoid going into the loop of tuples/variables. If a is dependent on knowing what b,c are, and b is dependent on knowing what a and c are, and c is dependent on knowing what a and b are, how do I prevent from going into a defining loop for each. This is just basically playing with Python's functions, I was just wondering how to approach such a problem where variables must come in order but might be dependent on a following variable who's positioning is needed to maintain the hierarchy of other variables it might represent. In the above, if I want to know c it requires knowing a,g. But in order to know a, a needs to know b,c-so I can't list c above a or a above c, because I get the error that the value of the other is not known when I try to run the script. David From kwaku.nuamah at gmail.com Mon Jan 25 07:25:14 2010 From: kwaku.nuamah at gmail.com (Kwaku Nuamah) Date: Mon, 25 Jan 2010 06:25:14 +0000 Subject: [Tutor] Tutor Digest, Vol 71, Issue 62 In-Reply-To: References: Message-ID: <65f1767a1001242225s7abe3592r5f5f67b58348297b@mail.gmail.com> On 1/24/10, tutor-request at python.org 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. Re: The magic parentheses (Shashwat Anand) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 24 Jan 2010 13:54:37 +0530 > From: Shashwat Anand > To: Alan Gauld > Cc: tutor at python.org > Subject: Re: [Tutor] The magic parentheses > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > @David, > > Alan and rest have clarified your doubt I guess. However let me point you > towards some other mistakes. > > def area1(radius): > area1r = 3.14159 * mainvar1**2 > return area1r > print area1r > > def area2(radius): > area2r = 3.14159 * mainvar2**2 > return area2r > print area2r > > Here you created two functions for the single purpose of calculating area. > Why not just do, > def area(radius): > return math.pi * radius * radius > > Functions are created for doing repetitive tasks IMHO. But you just created > them for the heck of it. Ofcourse there is issue of writing dead-code (i.e. > lines that will never be executed), the print after return as Alan already > pointed out. > Also you created, a function that displays the difference between the two > results. > > def return_difference_of12(var1,var2): > if var1 - var2 > 0: > y = v1,var1,v3,v2,var2,period > print y > elif var2 - var1 > 0: > z = v2,var2,v3,v2,var1,period > print z > > > Why not create something simple like this : > > def return_difference(var1, var2): > if var1 > var2: > print 'Variable 1', var1, 'is greater than Variable 2', var2, '.' > elif var2 > var1: > print 'Variable 2', var2, 'is greater than Variable 1', var1, '.' > else: > print 'Variable 1', var1, 'is equal Variable 2', var2, '.' > > No need for explicit formation of tuple if all you wish is just a print > statement. > > Regards, > ~Shashwat > > > On Sun, Jan 24, 2010 at 1:23 PM, Alan Gauld > wrote: > >> >> "David Hutto" wrote >> >> This is my first post to the list, so tell me if I'm posting incorrectly. >>> >> >> You are doing fine. Welcome. >> >> My problem is when the results are printed, I get this: >>> >>> >>> >>> ('Variable 2,', 490.0, 'is greater than', 'Variable 2,', 8.0, '.') >>> >> >> The parentheses, as well as the apostrophes and commas. >>> I'm sure it's the way I'm having the results printed after it's >>> through, but not sure how to correct it. >>> >> >> You have two problems in your code(at least!) >> ---------------def area2(radius): >> area2r = 3.14159 * mainvar2**2 >> return area2r >> print area2r >> --------The print statement will never be called because the return >> statement forces an exit from the function. >> ------------------------- >> def return_difference_of12(var1,var2): >> if var1 - var2 > 0: >> >> y = v1,var1,v3,v2,var2,period >> print y >> elif var2 - var1 > 0: >> z = v2,var2,v3,v2,var1,period >> print z >> ----------------------------The assignments to y and z create tuples >> (a,b,c...)So you are asking to print a tuple and Python represents tuples >> by >> putting parens around the contents.To print them as a string use the >> join() >> method of a string using an empty string:print ''.join([str(s) for s in >> y])However this is an unusual way to print this type of output,It would be >> more normal to use a format string:print "Variable2: %f id greater than >> Variable1: %f." % (var1,var2)This reduces the number of variables needed >> and >> also gives you much more control over layout because the %f markers can be >> augmented with width specifiers, justificationhints etc.You can store the >> entire format string in a variable if you wish - especiaslly if you want >> to >> use it multiple times - but in your case the strings only appear once so I >> wouldn't bother.HTH,-- Alan GauldAuthor of the Learn to Program web >> sitehttp://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: > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 71, Issue 62 > ************************************* > -- Sent from my mobile device From alan.gauld at btinternet.com Mon Jan 25 09:36:24 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Jan 2010 08:36:24 -0000 Subject: [Tutor] The magic parentheses References: <171264.84738.qm@web45315.mail.sp1.yahoo.com> Message-ID: "David Hutto" wrote >> >>> a = 1 >> >>> b = 2 >> >>> c = 3 >> >>> x = a,b,c >> >>> print a,b,c >> 1 2 3 >> >>> print x >> (1, 2, 3) > So 'print a,b,c' says display the values of a,b,c in the sequence of > a,b,c given. > 'print x' says print the value of x, x grabs a's value, b's value, and > c's value, > and displays the values for print. Not quite. x is a tuple - a collection of values - it does not grab those values, it is given them Once given them it keeps them. If we subsequently change 'a' that change will not be reflected in x! (Note it gets more complex if 'a' is a mutable type.) >>> a = 1 >>> b = 2 >>> c = 3 >>> x = a,b,c >>> print a,b,c 1 2 3 >>> print x (1, 2, 3) >>> a = 66 >>> x (1, 2, 3) So no change in x even though a has changed. print always just displays the string representation of the values passed to it. So when passed a,b,c it prints the string version of a, the string version of b and the string version of c. When passed x it prints the string version of x which is a tuple. tuples in Python are represented as a sequence of values inside parentheses. But x does not go and fetch the latest values of a,b and c, it uses the values provided when x was created. > So the sequence becomes a tuple because it's a value of values, x is a tuple because that's what we created when we assigned the 3 values. Any sequence of values outside brackets or quotes is a tuple >>> t1 = 1,2,3 >>> t2 = 'a','b','c' >>> t3 = (2,,4,6) >>> t4 = (t1,t2) > and it's sum comes back in the form of a tuple, It was a tuple, it does not create itself dynamically. > not an actual end variable. A tuple is an "end variable". It is just as much a valid type as an integer, a string or a list. It is just another data type. > In other words the second leap to find the values of a,b,c for value x, There is no second leap. It stores and uses the values passed to it in the original assignment. > Now if I want to turn the first values listed under x into tuples > (or use the format function that I think was named in another > reply to return the non-tuple version of the value for x and > I'm going to try it in a few min) of the other two variables, I'm not sure what you mean here. The values in x are the original values of a,b and c. You can access those values using x[0],x[1],x[2]. Is that what you mean? > g = f > a = b,c This will fail because b and c don;t exist yet. > b = a,c this will fail because c does not exist yet > c = a,g > x = a,b,c > This is off the topic I think, so I'll repost under another if necessary, > but how do I avoid going into the loop of tuples/variables. There is no loop, it is not a dynamic lookup. The tuple stores the values at the time of creation. If the values don;t exist yet(as above) the assignment will fail to create a tuple and you will get an error. > If a is dependent on knowing what b,c are, and b is dependent > on knowing what a and c are, and c is dependent on knowing > what a and b are, how do I prevent from going into a defining > loop for each. Python won;t let you create variables using other variables that have not been defined yet. It is your responsibility as the programmer to define valriables before using them. > This is just basically playing with Python's functions, I was > just wondering how to approach such a problem where variables > must come in order but might be dependent on a following variable It will fail. You must create the variables before use. We, can do some clever things with functions that can defer the evaluation of variables until later in the program but thats an advanced topic that I won't go into here! > In the above, if I want to know c it requires knowing a,g. But > in order to know a, a needs to know b,c-so I can't list c > above a or a above c, because I get the error that the > value of the other is not known when I try to run the script. Correct, you must find a way to order them such that the dependencies are sorted out before assignment. Take a look at the sections on variables and collections, especially tuples, in the Raw Materials topic of my tutor for more information.. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From denis.spir at free.fr Mon Jan 25 12:25:05 2010 From: denis.spir at free.fr (spir) Date: Mon, 25 Jan 2010 12:25:05 +0100 Subject: [Tutor] Is it pythonesque In-Reply-To: <002f01ca9d10$2fe08000$8fa18000$@rr.com> References: <002f01ca9d10$2fe08000$8fa18000$@rr.com> Message-ID: <20100125122505.0b5787f7@o> On Sun, 24 Jan 2010 11:13:37 -0500 "Robert Berman" wrote: > Good morning, > > > > Given the following code snippets: > > > > def getuserinput(): > > while True: > > s1 = raw_input('Enter fraction as N,D or 0,0 to exit>>') > > delim = s1.find(',') > > if delim < 0: > > print 'invalid user input' > > else: > > n = int(s1[0:delim]) > > d = int(s1[delim+1::]) > > return n,d > > > > def main(): > > while True: > > n,d = getuserinput() > > if n == 0 or d == 0: return 0 > > > > n and d are always returned provided the input is given as n,d. n/d will > print an error message and the loop will reiterate until the user format is > correct. Please note there is no true ending return for getuserinput() as it > is hung off an if statement and if by some chance it breaks, it should > return None which will abort the program. While I suspect this style is > devious, is it dangerous or 'wrong' to use. Comments and other renditions > are most welcome. > > > > Thank you, > > > > Robert Berman -0- Blank lines between statament is certainly not pythonesque ;-) -1- Why not chose '/' as delimiter? -2- You may check there is a single delimiter. -3- You may consider a user-friendly (eg ''), rather than a programmer-friendly ("0,0") code for breking the loop. It'd cost you a pair of lines of code. For instance: FRACT = '/' def getUserInput(): while True: s1 = raw_input('Enter fraction as N/D or enter to exit > 1') if s1 == '': return None # will trigger exit in main nDelims = s1.count(FRACT) # only 1 is valid if nDelims == 1: n,d = s1.split(FRACT) return int(n),int(d) # remaining issue print 'invalid user input' getUserInput() An issue issue remains, namely that what around FRACT may not be valid integers. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From hassan.baig at alumni.duke.edu Mon Jan 25 08:32:59 2010 From: hassan.baig at alumni.duke.edu (Hassan Baig) Date: Mon, 25 Jan 2010 12:32:59 +0500 Subject: [Tutor] Python/Django issue In-Reply-To: <6fa835a81001242318s48e134b5ma9975af5bdd1e462@mail.gmail.com> References: <6fa835a81001242318s48e134b5ma9975af5bdd1e462@mail.gmail.com> Message-ID: <6fa835a81001242332pf7152a0tfffd6d6183d080ac@mail.gmail.com> Dear List Members, I hope you're well. I was wondering if you could help out in a basic query. I'm a Facebook developer and I'm facing the following problem: I have a flash file which calls up a url say http://test.com/createXML/ which is caught and used up by a *python/django* code and it creates and redirects to an XML. which is loaded by flash, to get values from the database. The setup works fine when outside facebook, but as soon as I put the setup in facebook, it stops loading the XML completely. Any clues? -Hassan Baig -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Mon Jan 25 12:31:02 2010 From: denis.spir at free.fr (spir) Date: Mon, 25 Jan 2010 12:31:02 +0100 Subject: [Tutor] The magic parentheses In-Reply-To: References: <78513.70608.qm@web45304.mail.sp1.yahoo.com> Message-ID: <20100125123102.13df3a95@o> On Mon, 25 Jan 2010 01:06:45 -0000 "Alan Gauld" wrote: > > "Lie Ryan" wrote > > >> and used print, I thought they would be considered the same whether as > >> a variable, or as a direct line, guess not. > > what is equivalent: > > print (a, b, c) > > > > and > > x = a, b, c > > print x > > > > both construct a tuple and prints a,b,c as tuple > > Not quite: > > >>> a = 1 > >>> b = 2 > >>> c = 3 > >>> x = a,b,c > >>> print a,b,c > 1 2 3 > >>> print x > (1, 2, 3) > >>> > > The first form prints multiple values the second prints the repr of a > single tuple value. The output is different. > > Alan G. Lie's example actually was: >>> a,b,c = 1,2,3 >>> print (a,b,c) # here parenthesized (1, 2, 3) >>> x = a,b,c >>> print x (1, 2, 3) Both output values are tuples. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From alan.gauld at btinternet.com Mon Jan 25 18:32:37 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Jan 2010 17:32:37 -0000 Subject: [Tutor] The magic parentheses References: <78513.70608.qm@web45304.mail.sp1.yahoo.com> <20100125123102.13df3a95@o> Message-ID: "spir" wrote > Lie's example actually was: > >>>> a,b,c = 1,2,3 >>>> print (a,b,c) # here parenthesized > (1, 2, 3) Oops, I've been using Python 3 too much, I mentally blanked out the parens! Sorry about that. Alan G. From bill at celestial.net Tue Jan 26 02:55:53 2010 From: bill at celestial.net (Bill Campbell) Date: Mon, 25 Jan 2010 17:55:53 -0800 Subject: [Tutor] email module, convert non multipart to multipart message Message-ID: <20100126015553.GA3961@ayn.mi.celestial.com> Is there a simple way to convert a MIMENonMultipart message parsed into a MIMEMultipart message? My goal is to take a message from the TouchTerm iPhone App with an openssh public key that has been mangled by intervening mailers, and convert it into a multipart message with the original text in one part and the cleaned up key as an application/base64 part that can be easily saved by a non- technical user. I have written a routine that does this by creating a new multipart container, copying all (well almost all) the headers into the new container then attaching the original body and the clean key, but I think there ought to be a neater way. Thanks. 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 There is no worse tyranny than to force a man to pay for what he does not want merely because you think it would be good for him. -- Robert Heinlein From lie.1296 at gmail.com Tue Jan 26 04:08:29 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 26 Jan 2010 14:08:29 +1100 Subject: [Tutor] The magic parentheses In-Reply-To: <171264.84738.qm@web45315.mail.sp1.yahoo.com> References: <171264.84738.qm@web45315.mail.sp1.yahoo.com> Message-ID: Do you know python's object model? A lot of these things will make much more sense once you do: http://effbot.org/zone/python-objects.htm From blurayhk at yahoo.com.hk Tue Jan 26 08:40:19 2010 From: blurayhk at yahoo.com.hk (Raymond Kwok) Date: Tue, 26 Jan 2010 15:40:19 +0800 (HKT) Subject: [Tutor] Need help with functions! Message-ID: <797600.40934.qm@web19001.mail.hk2.yahoo.com> Hello all, I have started to learn Python a few months ago and I'm loving it! I am creating a mini-game - the one that scrambles an English word and asks you what the originalword should be, e.g. yhptno ---> python So, I have a function called get_word() that does the random word thing and returns two things - 1) original word and 2) scrambled word, namely "originalword" and "jumble" respectively.? So every time I run the get_word() function, it gives me a new word.? The code is: jumble = get_word()[0] originalword = get_word()[1] print (jumble) answer = input ("What do you think this word is? ") while answer != originalword:????????? ??? answer = input ("No! Guess again please.") print ("\nThat's right! The word is",originalword) The while loop keeps running until the user guesses the right answer and it will display the original word.? The thing is when it shows the original word, it has in fact become a new word since the "get_word()" function has been run again and returned a new word.? Does anyone know how to solve this problem ? I hope it is not too confusing... -Ray Yahoo!???????????????????! ??? http://hk.promo.yahoo.com/security/ ????! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 26 09:32:28 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Jan 2010 08:32:28 -0000 Subject: [Tutor] Need help with functions! References: <797600.40934.qm@web19001.mail.hk2.yahoo.com> Message-ID: "Raymond Kwok" wrote > I have a function called get_word() that does the random word thing and > returns two things - 1) original word and 2) scrambled word, > > jumble = get_word()[0] > originalword = get_word()[1] You need to store the return value once and access the two values. words = get_word() jumble = words[0] originalword = words[1] OR, use the neat Python trick of unpacking into two variables at once, like this: jumble,original_word = get_word() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From eike.welk at gmx.net Wed Jan 27 14:04:06 2010 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 27 Jan 2010 14:04:06 +0100 Subject: [Tutor] python closures In-Reply-To: <20091130112445.7451eaf6@o> References: <20091130112445.7451eaf6@o> Message-ID: <201001271404.06750.eike.welk@gmx.net> Hello Denis! On Monday November 30 2009 11:24:45 spir wrote: > which seems to indicate python really embeds "symbolic references" (*) to > outer *variables*, when creating a closure for g0. Not "pointer > references" (**), otherwise the replacement of x would not be seen by the > closure --like in the case of default-parameter. Actually, I find this > _Bad_. Obviously, the func's behaviour and result depend on arbitrary > external values (referentially opaque). What do you think? > > Denis > > (*) by name, indirect access, second table lookup > (**) by address, direct access, no second lookup I just skimmed over introductions to Oz and Ocaml, and both programming languages seem to behave the way that you prefer. The closure consists of pointers to the objects and can't be modified. (Both languages however have special syntax for global variables that can be modified.) So, Python's behavior is just a design decision; and more people dislike it, like you. Learning exotic programming languages seems to widen my horizon. Eike. From neven.gorsic at gmail.com Wed Jan 27 14:57:13 2010 From: neven.gorsic at gmail.com (=?UTF-8?B?TmV2ZW4gR29yxaFpxIc=?=) Date: Wed, 27 Jan 2010 14:57:13 +0100 Subject: [Tutor] Is wxPython (development) dead? Message-ID: <8acd28da1001270557gd99ac56g4d1efd230c959f5d@mail.gmail.com> Since May of 2009 there has not been any update and now web page is not available any more ... -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 27 15:29:01 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Jan 2010 14:29:01 -0000 Subject: [Tutor] Is wxPython (development) dead? References: <8acd28da1001270557gd99ac56g4d1efd230c959f5d@mail.gmail.com> Message-ID: "Neven Gorsic" wrote > Since May of 2009 there has not been any update and now web page is not > available any more ... I'll be very surprised if the whole project is dead - its probably the second most used GUI for Python - but the web site does seem to be down. FWIW The wxPython mailing list is very much still alive, with 5 new threads today so far. Maybe you could ask whats going on there? Alan G. From anand.shashwat at gmail.com Wed Jan 27 18:31:15 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Wed, 27 Jan 2010 23:01:15 +0530 Subject: [Tutor] Google Summer of Code, 2010 Message-ID: Leslie Hawthorne, the spokesperson from google announced the commencement of GSoC,2010 today : http://groups.google.com/group/google-summer-of-code-discuss/browse_thread/thread/d839c0b02ac15b3f It's a golden opportunity for an undergraduate engineering student with Computer Science as major and python as interest to contribute to open-source and utilize summer vacation. I am a bit biased towards python and I'll attempt nothing else other then python. I got the last year list of organization related with python here : http://delicious.com/gsoc2009/pythonbut I would love to hear suggestion from experienced members here. Please feel free to guide me up. Thanks, ~ Shashwat -------------- next part -------------- An HTML attachment was scrubbed... URL: From kbailey at howlermonkey.net Wed Jan 27 23:25:54 2010 From: kbailey at howlermonkey.net (Kirk Z Bailey) Date: Wed, 27 Jan 2010 17:25:54 -0500 Subject: [Tutor] length of a string? Advice saught Message-ID: <4B60BD72.5000505@howlermonkey.net> I wrote a program to let me edit web-pages without bothering with ftp; it loads up a simple form with the page guts in it, and saves it through another script. Until yesterday, EditMyPage worked fine. Alas, I had a rather long winded page and it truncated it- completely omitted the last 1/4 of the original file, creating big problems. Looking everything over, I can only conclude that somehow python 2.23 (ok, it's an old server; shoot me, I'm poor) has a limit on a simple string variable. Can I declare the variable as a long winded version and save the trouble, or do AI need a witchdoctor here? -- end Very Truly yours, - Kirk Bailey, Largo Florida kniht +-----+ | BOX | +-----+ think From alan.gauld at btinternet.com Thu Jan 28 00:57:45 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Jan 2010 23:57:45 -0000 Subject: [Tutor] length of a string? Advice saught References: <4B60BD72.5000505@howlermonkey.net> Message-ID: "Kirk Z Bailey" wrote >I wrote a program to let me edit web-pages without bothering with ftp; it >loads up a simple form with the page guts in it, and saves it through >another script. > truncated it- completely omitted the last 1/4 of the original file, > creating big problems. Looking everything over, I can only conclude that > somehow python 2.23 (ok, it's an old server; shoot me, I'm poor) has a > limit on a simple string variable. Since you don't give us any clues as to how your program works I can only guess, but I suspect the problem lies not in the string variable but in the means of populating it. Did you use read()? And if so from where? read() functions usually have an optional buffersize parameter set to a "reasonable" size. If you try to read more than that it will be truncated. This is explained in the read() documentation for files. The urllib module has a similar limitation as indicated by this quote from the docs: ---------------------- One caveat: the read() method, if the size argument is omitted or negative, may not read until the end of the data stream; there is no good way to determine that the entire stream from a socket has been read in the general case. ------------------------ I don;t know if you are using either a file read() or urlib.read() but that may be the cause of the problem? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Thu Jan 28 01:02:00 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 27 Jan 2010 18:02:00 -0600 Subject: [Tutor] Fwd: length of a string? Advice saught In-Reply-To: References: <4B60BD72.5000505@howlermonkey.net> Message-ID: ---------- Forwarded message ---------- From: Luke Paireepinart Date: Wed, 27 Jan 2010 18:01:35 -0600 Subject: Re: [Tutor] length of a string? Advice saught To: Kirk Z Bailey Are you using the post or the get method to submit the form? That's likely your problem. Strings in Python are only limited by your memory and your program will crash with a memoryerror exception if that's the problem you're running into (doubtful for user-entered txt unless your server only has 1k of ram or something.) On 1/27/10, Kirk Z Bailey wrote: > I wrote a program to let me edit web-pages without bothering with > ftp; it loads up a simple form with the page guts in it, and > saves it through another script. Until yesterday, EditMyPage > worked fine. Alas, I had a rather long winded page and it > truncated it- completely omitted the last 1/4 of the original > file, creating big problems. Looking everything over, I can only > conclude that somehow python 2.23 (ok, it's an old server; shoot > me, I'm poor) has a limit on a simple string variable. Can I > declare the variable as a long winded version and save the > trouble, or do AI need a witchdoctor here? > > -- > end > > Very Truly yours, > - Kirk Bailey, > Largo Florida > > kniht > +-----+ > | BOX | > +-----+ > think > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sent from my mobile device -- Sent from my mobile device From ali.jan at gmail.com Thu Jan 28 07:22:48 2010 From: ali.jan at gmail.com (Muhammad Ali) Date: Thu, 28 Jan 2010 11:22:48 +0500 Subject: [Tutor] multiply and sum two lists with list comprehension? Message-ID: <8acb5ef81001272222n31405914rf2868de52d9085d4@mail.gmail.com> Hi, I am multipliying two lists so that each of list As elements get multiplied to the corresponding list Bs. Then I am summing the product. For example, A= [1, 2, 3] and B=[2, 2, 2] so that I get [2, 4, 6] after multiplication and then sum it to get 12. I can do it using map like this: sum(map(lambda i,j:i*j, A, B)) But map is being dropped out in python 3? or has it already been dropped? And I have heard Guido say that list comprehension do a better job than map so how would we do this with list comps? Thanks, Ali -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Jan 28 07:27:52 2010 From: emile at fenx.com (Emile van Sebille) Date: Wed, 27 Jan 2010 22:27:52 -0800 Subject: [Tutor] length of a string? Advice saught In-Reply-To: <4B60BD72.5000505@howlermonkey.net> References: <4B60BD72.5000505@howlermonkey.net> Message-ID: On 1/27/2010 2:25 PM Kirk Z Bailey said... > I wrote a program to let me edit web-pages without bothering with ftp; > it loads up a simple form with the page guts in it, and saves it through > another script. Until yesterday, EditMyPage worked fine. Alas, I had a > rather long winded page and it truncated it- completely omitted the last > 1/4 of the original file, creating big problems. Looking everything > over, I can only conclude that somehow python 2.23 (ok, it's an old > server; shoot me, I'm poor) has a limit on a simple string variable. Can > I declare the variable as a long winded version and save the trouble, or > do AI need a witchdoctor here? > Also consider that closing a connection before the buffer is fully flushed can cause loss of data. Emile From ghartshaw at gmail.com Thu Jan 28 07:44:00 2010 From: ghartshaw at gmail.com (Garrett Hartshaw) Date: Thu, 28 Jan 2010 01:44:00 -0500 Subject: [Tutor] multiply and sum two lists with list comprehension? In-Reply-To: <8acb5ef81001272222n31405914rf2868de52d9085d4@mail.gmail.com> References: <8acb5ef81001272222n31405914rf2868de52d9085d4@mail.gmail.com> Message-ID: <8b40e7de1001272244t2780f19dxaf7c04edfb6c8cd6@mail.gmail.com> > > > Hi, > > I am multipliying two lists so that each of list As elements get multiplied > to the corresponding list Bs. Then I am summing the product. > > For example, A= [1, 2, 3] and B=[2, 2, 2] so that I get [2, 4, 6] after > multiplication and then sum it to get 12. I can do it using map like this: > > sum(map(lambda i,j:i*j, A, B)) > > But map is being dropped out in python 3? or has it already been dropped? > It appears to still work in 3.1.1. I don't know if it is going to be dropped. > And I have heard Guido say that list comprehension do a better job than > map so how would we do this with list comps? > This should be equivalent. Python 3.1.1+ (r311:74480, Nov 2 2009, 15:45:00) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> A=[1,2,3] >>> B=[2,2,2] >>> [i*j for i,j in zip(A,B)] [2, 4, 6] >>> sum([i*j for i,j in zip(A,B)]) 12 > Thanks, > Ali > > _______________________________________________ > 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 adam.jtm30 at gmail.com Thu Jan 28 11:44:01 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Thu, 28 Jan 2010 10:44:01 +0000 Subject: [Tutor] Is wxPython (development) dead? In-Reply-To: <8acd28da1001270557gd99ac56g4d1efd230c959f5d@mail.gmail.com> References: <8acd28da1001270557gd99ac56g4d1efd230c959f5d@mail.gmail.com> Message-ID: On 27 January 2010 13:57, Neven Gor?i? wrote: > Since May of 2009 there has not been any update and now web page is not > available any more ... > The website is back up now. I guess there was a server issue of some sort. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Jan 28 12:13:20 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 28 Jan 2010 22:13:20 +1100 Subject: [Tutor] multiply and sum two lists with list comprehension? In-Reply-To: <8acb5ef81001272222n31405914rf2868de52d9085d4@mail.gmail.com> References: <8acb5ef81001272222n31405914rf2868de52d9085d4@mail.gmail.com> Message-ID: On 01/28/10 17:22, Muhammad Ali wrote: > Hi, > > I am multipliying two lists so that each of list As elements get multiplied > to the corresponding list Bs. Then I am summing the product. > > For example, A= [1, 2, 3] and B=[2, 2, 2] so that I get [2, 4, 6] after > multiplication and then sum it to get 12. I can do it using map like this: > > sum(map(lambda i,j:i*j, A, B)) > > But map is being dropped out in python 3? or has it already been dropped? > And I have heard Guido say that list comprehension do a better job than map > so how would we do this with list comps? No, `map` will not be dropped in the foreseeable future. `lambda`, `map`, `filter`, and `reduce` will stay; but `reduce` will be moved into functools module (from previously a built-in function). http://www.artima.com/weblogs/viewpost.jsp?thread=98196 From denis.spir at free.fr Thu Jan 28 12:16:52 2010 From: denis.spir at free.fr (spir) Date: Thu, 28 Jan 2010 12:16:52 +0100 Subject: [Tutor] get (x)range borders Message-ID: <20100128121652.6c71b6d3@o> Hello, Is there a way to retrieve an (x)range's borders? (Eg if I want to print out "m..n" instead of "xrange(m, n)".) Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From alan.plum at uni-koeln.de Thu Jan 28 13:37:28 2010 From: alan.plum at uni-koeln.de (Alan Plum) Date: Thu, 28 Jan 2010 13:37:28 +0100 Subject: [Tutor] get (x)range borders In-Reply-To: <20100128121652.6c71b6d3@o> References: <20100128121652.6c71b6d3@o> Message-ID: <1264682248.2878.5.camel@kallisti> On Do, 2010-01-28 at 12:16 +0100, spir wrote: > Is there a way to retrieve an (x)range's borders? > (Eg if I want to print out "m..n" instead of "xrange(m, n)".) You mean like this? >>> m = 20 >>> n = 30 >>> a = xrange(m, n) >>> a xrange(20, 30) >>> a[0] 20 >>> a[-1] 29 Please note that the border will always be one step off if you're looking for the values you originally provided: the endpoint is always given as exclusive. If you want to know the step, you probably need to calculate it: >>> a = xrange(20, 30, 2) >>> step = a[1] - a[0] >>> step 2 Cheers, Alan Plum From denis.spir at free.fr Thu Jan 28 14:32:10 2010 From: denis.spir at free.fr (spir) Date: Thu, 28 Jan 2010 14:32:10 +0100 Subject: [Tutor] get (x)range borders In-Reply-To: <1264682248.2878.5.camel@kallisti> References: <20100128121652.6c71b6d3@o> <1264682248.2878.5.camel@kallisti> Message-ID: <20100128143210.1df6dcf6@o> On Thu, 28 Jan 2010 13:37:28 +0100 Alan Plum wrote: > You mean like this? > > >>> m = 20 > >>> n = 30 > >>> a = xrange(m, n) > >>> a > xrange(20, 30) > >>> a[0] > 20 > >>> a[-1] > 29 !!! Did not even think at that (looked for attributes of xrange instances). Thank you. Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From kent37 at tds.net Thu Jan 28 14:36:12 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Jan 2010 08:36:12 -0500 Subject: [Tutor] length of a string? Advice saught In-Reply-To: References: <4B60BD72.5000505@howlermonkey.net> Message-ID: <1c2a2c591001280536ifcca70dg5c80f341432814d@mail.gmail.com> On Wed, Jan 27, 2010 at 6:57 PM, Alan Gauld wrote: > read() functions usually have an optional buffersize parameter > set to a "reasonable" size. If you try to read more than that it > will be truncated. This is explained in the read() documentation > for files. ?? files have a buffer size that sets how much is read from the disk at once; I don't think it affects how much is read by file.read(). The docs for that say, "If the size argument is negative or omitted, read all data until EOF is reached." Kent From kent37 at tds.net Thu Jan 28 14:38:31 2010 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Jan 2010 08:38:31 -0500 Subject: [Tutor] multiply and sum two lists with list comprehension? In-Reply-To: <8acb5ef81001272222n31405914rf2868de52d9085d4@mail.gmail.com> References: <8acb5ef81001272222n31405914rf2868de52d9085d4@mail.gmail.com> Message-ID: <1c2a2c591001280538q61edc56v63d052cf30536c6c@mail.gmail.com> On Thu, Jan 28, 2010 at 1:22 AM, Muhammad Ali wrote: > > Hi, > > I am multipliying two lists so that each of list As elements get multiplied > to the corresponding list Bs. Then I am summing the product. > > For example, A= [1, 2, 3] and B=[2, 2, 2] so that I get [2, 4, 6] after > multiplication and then sum it to get 12. I can do it using map like this: > > sum(map(lambda i,j:i*j, A, B)) You don't need a lambda, use operator.mul(): sum(map(operator.mul, A, B)) Kent From samueldechamplain at gmail.com Thu Jan 28 17:53:57 2010 From: samueldechamplain at gmail.com (Samuel de Champlain) Date: Thu, 28 Jan 2010 11:53:57 -0500 Subject: [Tutor] I love python Message-ID: <10cd5a2c1001280853w7f87e15bn705dc78a0d1f6525@mail.gmail.com> I am presently doing the "Dive into Python tutorial", and I wanted to share these lines with you. "As a former philosophy major, it disturbs me to think that things disappear when no one is looking at them, but that's exactly what happens in Python. In general, you can simply forget about memory management and let Pythonclean up after you. " - Mark Pilgrim I love python. -------------- next part -------------- An HTML attachment was scrubbed... URL: From raghavendra.gv.vanam at gmail.com Thu Jan 28 18:19:48 2010 From: raghavendra.gv.vanam at gmail.com (vanam) Date: Thu, 28 Jan 2010 22:49:48 +0530 Subject: [Tutor] [File Input Module]Replacing string in a file Message-ID: <4499cb6a1001280919m1b51ada8t7d4a01fbf33379e1@mail.gmail.com> Hi all, As it was suggested before in the mailing list about the query regarding replacing string in the file, i have used the module File input for replacing the string in the file. For understanding and execution purpose, i have just included Python as a string in the file and want it to be replaced to PYTHON. Below are my queries and code: (Correct me if my understanding is wrong???????) 1)) import fileinput x = fileinput.input('data.txt',inplace=0) for line in x: line = line.replace('Python','PYTHON) print line, x.close() The above piece of code will not create any backup file but it will replace PYTHON (Print on the console) but not physically write to the file. 2))) import fileinput x = fileinput.input('data.txt',inplace=1) for line in x: line = line.replace('Python','PYTHON') print line, x.close() The above piece of code will create backup file but hidden (in the form of bak file) and it will physically write to the file -- I have verified the contents of data.txt after the file operation and it had written successfully.But why it is not printing line i.e. string in the file on the console. 3))) import fileinput x = fileinput.input('data.txt',inplace=1) for line in x: line = line.replace('Python','PYTHON') x.close() The above piece of code after execution is wiping out the full contents. But addition of print line, is exactly replacing the string, what exactly addition of print is making difference??? 4))) import fileinput x = fileinput.input('data.txt',inplace=1,backup='content.txt') for line in x: line = line.replace('Python','PYTHON') print line, x.close() The above piece is creating a backup file by name data.txtcontent.txt (I am not sure whether created file name is correct or not?) and to the back up file it had added previous content i.e., Python and it had replaced the contents in data.txt to PYTHON 5))) Suppose if data.txt has string Python written in Font size 72 and when i display the string on the console ie. by below piece of code import fileinput x = fileinput.input('data.txt',inplace=0) for line in x: print line, x.close() It wouldnt print with the same Font size on the console (This wont prove anything wrong as the same font could be backed with a different file name) Do let me know if my understanding is correct. -- Raghavendra Vanam From alan.gauld at btinternet.com Thu Jan 28 19:19:25 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 28 Jan 2010 18:19:25 +0000 (GMT) Subject: [Tutor] length of a string? Advice saught In-Reply-To: <1c2a2c591001280536ifcca70dg5c80f341432814d@mail.gmail.com> References: <4B60BD72.5000505@howlermonkey.net> <1c2a2c591001280536ifcca70dg5c80f341432814d@mail.gmail.com> Message-ID: <548144.14499.qm@web86707.mail.ird.yahoo.com> >> set to a "reasonable" size. If you try to read more than that it >> will be truncated. This is explained in the read() documentation >> for files. > > ?? files have a buffer size that sets how much is read from the disk > at once; I don't think it affects how much is read by file.read(). The > docs for that say, > "If the size argument is negative or omitted, read all data until EOF > is reached." Oops, wrong again! :-) But the comment re urllib.read() still seems apropos. Alan G. From alan.gauld at btinternet.com Thu Jan 28 19:36:53 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Jan 2010 18:36:53 -0000 Subject: [Tutor] [File Input Module]Replacing string in a file References: <4499cb6a1001280919m1b51ada8t7d4a01fbf33379e1@mail.gmail.com> Message-ID: "vanam" wrote > Suppose if data.txt has string Python written in Font size 72 and when > i display the string on the console ie. by below piece of code Text files don't have font sizes, just text. To store formatting information requires that data to be stored (separate to the text) in the file and then the rendering program (word processor, browser etc) to interpret the style information and display appropriately. But the text is always independant of the formatting. > It wouldnt print with the same Font size on the console (This wont > prove anything wrong as the same font could be backed with a different > file name) It has nothing to do with the file name, the font size is all to do with the presentation application and any format data stored within the file. eg in HTML it will be in a style attribute of the text HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Thu Jan 28 20:06:01 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 28 Jan 2010 13:06:01 -0600 Subject: [Tutor] I love python In-Reply-To: <10cd5a2c1001280853w7f87e15bn705dc78a0d1f6525@mail.gmail.com> References: <10cd5a2c1001280853w7f87e15bn705dc78a0d1f6525@mail.gmail.com> Message-ID: Glad you like it. I do too. I'm taking a graduate course "Crafting Compilers" and my prof. said I could use Python to write my compiler. It'll be the first one for his class that wasn't written in C/C++. On Thu, Jan 28, 2010 at 10:53 AM, Samuel de Champlain < samueldechamplain at gmail.com> wrote: > I am presently doing the "Dive into Python tutorial", and I wanted to share > these lines with you. > > "As a former philosophy major, it disturbs me to think that things > disappear when no one is looking at them, but that's exactly what happens in > Python. In general, you can simply forget about memory management and let > Python clean up after you. " - Mark Pilgrim > > I love 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 anand.shashwat at gmail.com Thu Jan 28 20:12:22 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Fri, 29 Jan 2010 00:42:22 +0530 Subject: [Tutor] I love python In-Reply-To: References: <10cd5a2c1001280853w7f87e15bn705dc78a0d1f6525@mail.gmail.com> Message-ID: Whoaa...even me too have Compilers as a graduate course this sem, (lex, flex, yacc stuff) but the labs have not started yet. Will see how much pythonic I can make this lab :D On Fri, Jan 29, 2010 at 12:36 AM, Luke Paireepinart wrote: > Glad you like it. I do too. I'm taking a graduate course "Crafting > Compilers" and my prof. said I could use Python to write my compiler. It'll > be the first one for his class that wasn't written in C/C++. > > On Thu, Jan 28, 2010 at 10:53 AM, Samuel de Champlain < > samueldechamplain at gmail.com> wrote: > >> I am presently doing the "Dive into Python tutorial", and I wanted to >> share these lines with you. >> >> "As a former philosophy major, it disturbs me to think that things >> disappear when no one is looking at them, but that's exactly what happens in >> Python. In general, you can simply forget about memory management and let >> Python clean up after you. " - Mark Pilgrim >> >> I love python. >> >> _______________________________________________ >> 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 rabidpoobear at gmail.com Thu Jan 28 20:42:22 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 28 Jan 2010 13:42:22 -0600 Subject: [Tutor] I love python In-Reply-To: References: <10cd5a2c1001280853w7f87e15bn705dc78a0d1f6525@mail.gmail.com> Message-ID: Yeah, I'm really excited. The graduate school teachers are much more willing to let me use Python than the undergrads were. I'm also doing my Internet Information Processing course using Python, as well as my Data Mining one. :) On Thu, Jan 28, 2010 at 1:12 PM, Shashwat Anand wrote: > Whoaa...even me too have Compilers as a graduate course this sem, (lex, > flex, yacc stuff) but the labs have not started yet. Will see how much > pythonic I can make this lab :D > > > On Fri, Jan 29, 2010 at 12:36 AM, Luke Paireepinart < > rabidpoobear at gmail.com> wrote: > >> Glad you like it. I do too. I'm taking a graduate course "Crafting >> Compilers" and my prof. said I could use Python to write my compiler. It'll >> be the first one for his class that wasn't written in C/C++. >> >> On Thu, Jan 28, 2010 at 10:53 AM, Samuel de Champlain < >> samueldechamplain at gmail.com> wrote: >> >>> I am presently doing the "Dive into Python tutorial", and I wanted to >>> share these lines with you. >>> >>> "As a former philosophy major, it disturbs me to think that things >>> disappear when no one is looking at them, but that's exactly what happens in >>> Python. In general, you can simply forget about memory management and >>> let Python clean up after you. " - Mark Pilgrim >>> >>> I love python. >>> >>> _______________________________________________ >>> 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 davea at ieee.org Thu Jan 28 21:25:46 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 28 Jan 2010 15:25:46 -0500 Subject: [Tutor] [File Input Module]Replacing string in a file In-Reply-To: <4499cb6a1001280919m1b51ada8t7d4a01fbf33379e1@mail.gmail.com> References: <4499cb6a1001280919m1b51ada8t7d4a01fbf33379e1@mail.gmail.com> Message-ID: <4B61F2CA.5050209@ieee.org> vanam wrote: > Hi all, > > As it was suggested before in the mailing list about the query > regarding replacing string in the file, i have used the module File > input for replacing the string in the file. > > For understanding and execution purpose, i have just included Python > as a string in the file and want it to be replaced to PYTHON. > > Below are my queries and code: (Correct me if my understanding is wrong???????) > > 1)) > > import fileinput > x = fileinput.input('data.txt',inplace=0) > for line in x: > line = line.replace('Python','PYTHON) > print line, > x.close() > > The above piece of code will not create any backup file but it will > replace PYTHON (Print on the console) but not physically write to the > file. > > 2))) > > import fileinput > x = fileinput.input('data.txt',inplace=1) > for line in x: > line = line.replace('Python','PYTHON') > print line, > x.close() > > The above piece of code will create backup file but hidden (in the > form of bak file) and it will physically write to the file -- I have > verified the contents of data.txt after the file operation and it had > written successfully.But why it is not printing line i.e. string in > the file on the console. > > When you use the inplace=true option, it will redirect standard output to the file. So print is going there, and *not* to the console. I don't know whether close() restores the original console or not. > 3))) > > import fileinput > x = fileinput.input('data.txt',inplace=1) > for line in x: > line = line.replace('Python','PYTHON') > x.close() > > The above piece of code after execution is wiping out the full > contents. But addition of print line, is exactly replacing the string, > what exactly addition of print is making difference??? > > See above. Since you print nothing to sys.stdout, the output file is empty. > 4))) > > import fileinput > x = fileinput.input('data.txt',inplace=1,backup='content.txt') > for line in x: > line = line.replace('Python','PYTHON') > print line, > x.close() > > The above piece is creating a backup file by name data.txtcontent.txt > (I am not sure whether created file name is correct or not?) and to > the back up file it had added previous content i.e., Python and it had > replaced the contents in data.txt to PYTHON > > 5))) > > Suppose if data.txt has string Python written in Font size 72 and when > i display the string on the console ie. by below piece of code > > import fileinput > x = fileinput.input('data.txt',inplace=0) > for line in x: > print line, > x.close() > > It wouldnt print with the same Font size on the console (This wont > prove anything wrong as the same font could be backed with a different > file name) > > Text files have no concept of fonts or color. Sometimes there are extra annotations in a file (eg. escape sequences) which can be interpreted by particular software as commands to change font, or change color, or even to reposition. Examples of this would be html, postscript, rich-text, and ANSI escape sequences. But those escape sequences will only be meaningful to a program that understands them. So if you print html files out to the console, you'll see lots of angle brackets and such, rather than seeing the pretty display intended to show in a browser. If you print to a console, it's up to that console to process some escape sequences (eg. ANSI) or not. > Do let me know if my understanding is correct. > From denis.spir at free.fr Fri Jan 29 14:03:22 2010 From: denis.spir at free.fr (spir) Date: Fri, 29 Jan 2010 14:03:22 +0100 Subject: [Tutor] hash value input Message-ID: <20100129140322.62b711b0@o> Hello, What actually is hashed when a data item is used a dict key? If possible, I would also like some clues on the method used to produce the hash value. (Maybe a pointer to the the relevant part of the python source, if clear and/or commented.) The reason why I ask is the well known limitation for dict keys to be immutable data (same for sets, indeed). This seems to imply that the value itself is used as source for the hash func. Or am I wrong on this? I recently discovered that Lua uses the data's address (read: id) as input to the hash func. This allows Lua tables (a kind of more versatile associative array) to use _anything_ as key, since the id is guaranteed not to change, per definition. [Aside this consideration, hashing addresses ensures a constant type as input (so allows a specific efficient hash method) and the simplest possible one.] So, how does python do this? Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From szabolcs.bobak at gmail.com Fri Jan 29 14:15:19 2010 From: szabolcs.bobak at gmail.com (=?UTF-8?Q?BOB=C3=81K_Szabolcs?=) Date: Fri, 29 Jan 2010 14:15:19 +0100 Subject: [Tutor] sqlite query problem Message-ID: Dear List Members, I need help in a mystic problem (I hope just for me) with python and sqlite3. Running enviroment: OS: Windows 2003 ENG 64bit, Windows XP HUN 32bit Python: ActiveState Python 2.6.4 32bit (It's a must because of PyWin extension in the future and I didn't have any issue with it on 64bit Win) It's a little program wich collects the data of files on the given partition or in given directories (and in the future should watch/monitoring the changes). It stores the data in sqlite3 database via python. It works quite well. My problem is with the query. I see that I am a little bit confused with passing variables to queries. Mostly it works but when I want to query the files which last modification date is lesser than a given date it not works. The strange is when I do the same via command line (prebuilt sqlite3 windows binary: 3.6.22) it works perfectly. The table structure: sql_command_create = 'create table '+sql_tablename+' (dirname text, fullpath text, size_in_byte integer, creationdate integer, lastmoddate integer, lastaccdate integer, archivalhato text)' # the archivalhato field is a remain too sql_cursor.execute(sql_command_create) Insert command: sql_command_insert = 'insert into '+sql_tablename+' values (?, ?, ?, ?, ?, ?, ?)' sql_cursor.execute(sql_command_insert, (sql_dirname, sql_fullpath, sql_size, sql_creationdate, sql_lastmoddate, sql_lastaccdate, sql_archive_field)) sql_conn.commit() These were my workarounds to pass variable values to queries. I just wonder if there were better solution, but these work well. The query: sql_tablename_orig = 'pyfilestat_drive_e_2010_01_27_16_48_31' sql_conn = sqlite3.connect(sql_file) sql_cursor = sql_conn.cursor() sql_command_stat = 'SELECT COUNT(*) FROM '+sql_tablename_orig sql_cursor.execute(sql_command_stat) print 'Az osszes sor szama: '+str(sql_cursor.fetchone()) #prints the number of rows This also works, but this not: sql_command_stat = 'SELECT COUNT(lastmoddate) FROM '+sql_tablename_orig+'WHERE lastmoddate < '+str(lastmod_date1) sql_cursor.execute(sql_command_stat) This was my original try, but tried various in various formula. sql_command_stat = 'SELECT COUNT(lastmoddate) FROM '+sql_tablename_orig+'WHERE lastmoddate < %d' sql_cursor.execute(sql_command_stat, %lastmod_date1) sql_command_stat = 'SELECT COUNT(lastmoddate) FROM '+sql_tablename_orig+'WHERE lastmoddate < (?)' sql_cursor.execute(sql_command_stat, (lastmod_date1)) But always the same error message: sqlite3.OperationalError: near "<": syntax error File "C:\python\stat.py", line 42, in sql_cursor.execute(sql_command_stat) >From the three attempt I concluded that it's the same if I pass the variable value as a string or an integer (maybe I am wrong). Anyway it wasn't clear which is the best (securest) way. I thought that the first and third. Maybe the form of the date is not the best, but the program is an update of text file based version, so it's a remain. And when I try this query from command line, it works. Thank you for your help in advance! P.S. Excuse me for my bad English. -- Bob?k Szabolcs -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Fri Jan 29 17:23:37 2010 From: emile at fenx.com (Emile van Sebille) Date: Fri, 29 Jan 2010 08:23:37 -0800 Subject: [Tutor] hash value input In-Reply-To: <20100129140322.62b711b0@o> References: <20100129140322.62b711b0@o> Message-ID: On 1/29/2010 5:03 AM spir said... > Hello, > > What actually is hashed when a data item is used a dict key? If possible, I would also like some clues on the method used to produce the hash value. (Maybe a pointer to the the relevant part of the python source, if clear and/or commented.) > > The reason why I ask is the well known limitation for dict keys to be immutable data (same for sets, indeed). This seems to imply that the value itself is used as source for the hash func. Or am I wrong on this? > I recently discovered that Lua uses the data's address (read: id) as input to the hash func. This allows Lua tables (a kind of more versatile associative array) to use _anything_ as key, since the id is guaranteed not to change, per definition. > [Aside this consideration, hashing addresses ensures a constant type as input (so allows a specific efficient hash method) and the simplest possible one.] > > So, how does python do this? > Start here... http://effbot.org/zone/python-hash.htm Emile From hugo.yoshi at gmail.com Fri Jan 29 17:53:52 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 29 Jan 2010 17:53:52 +0100 Subject: [Tutor] sqlite query problem In-Reply-To: References: Message-ID: <29179d161001290853k6dc194a7k1641a67b8a9dea6e@mail.gmail.com> 2010/1/29 BOB?K Szabolcs : > > This also works, but this not: > sql_command_stat = 'SELECT COUNT(lastmoddate) FROM > '+sql_tablename_orig+'WHERE lastmoddate < '+str(lastmod_date1) > sql_cursor.execute(sql_command_stat) > > This was my original try, but tried various in various formula. > sql_command_stat = 'SELECT COUNT(lastmoddate) FROM > '+sql_tablename_orig+'WHERE lastmoddate < %d' > sql_cursor.execute(sql_command_stat, %lastmod_date1) > > sql_command_stat = 'SELECT COUNT(lastmoddate) FROM > '+sql_tablename_orig+'WHERE lastmoddate < (?)' > sql_cursor.execute(sql_command_stat, (lastmod_date1)) > > But always the same error message: > sqlite3.OperationalError: near "<": syntax error > File "C:\python\stat.py", line 42, in > sql_cursor.execute(sql_command_stat) > > From the three attempt I concluded that it's the same if I pass the variable > value as a string or an integer (maybe I am wrong). Your error isn't where you expect it to be. Let's take a look at the string you're actually passing: >>> sql_tablename_orig = 'pyfilestat_drive_e_2010_01_27_16_48_31' >>> sql_command_stat = 'SELECT COUNT(lastmoddate) FROM '+sql_tablename_orig+'WHERE lastmoddate < %d' >>> sql_command_stat 'SELECT COUNT(lastmoddate) FROM pyfilestat_drive_e_2010_01_27_16_48_31WHERE lastmoddate < %d' well, hello. we seem to be having a missing space, right in between the table name and 'WHERE.' Also, you should use the third form, using the parameters argument of execute(). it's the only secure one. Hugo From kent37 at tds.net Fri Jan 29 17:54:51 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Jan 2010 11:54:51 -0500 Subject: [Tutor] hash value input In-Reply-To: <20100129140322.62b711b0@o> References: <20100129140322.62b711b0@o> Message-ID: <1c2a2c591001290854w3568e38cq898de293722c50ef@mail.gmail.com> On Fri, Jan 29, 2010 at 8:03 AM, spir wrote: > I recently discovered that Lua uses the data's address (read: id) as input to the hash func. This allows Lua tables (a kind of more versatile associative array) to use _anything_ as key, since the id is guaranteed not to change, per definition. > [Aside this consideration, hashing addresses ensures a constant type as input (so allows a specific efficient hash method) and the simplest possible one.] This sounds like a bad idea to me. You generally want key lookup to be based on value, not identity. For example, if I say d = dict() d['key'] = value and later print d['key'] I want this to print 'value' regardless of whether I use the same instance of the string 'key' in both cases. Maybe Lua has some mechanism for ensuring that this can't happen? In general, for a hash table to work as expected, two keys that are equal in value should have the same hash value. Here is an explanation of why (for Java, but it pretty much applies to any hash table implementation): http://www.javaworld.com/javaqa/2002-06/01-qa-0621-hashtable.html Kent From szabolcs.bobak at gmail.com Fri Jan 29 19:21:12 2010 From: szabolcs.bobak at gmail.com (=?UTF-8?Q?BOB=C3=81K_Szabolcs?=) Date: Fri, 29 Jan 2010 19:21:12 +0100 Subject: [Tutor] sqlite query problem In-Reply-To: <29179d161001290853k6dc194a7k1641a67b8a9dea6e@mail.gmail.com> References: <29179d161001290853k6dc194a7k1641a67b8a9dea6e@mail.gmail.com> Message-ID: Dear Hugo, Thank you for your fast help and the sharp eyes. I was almost hopeless. It is working now, but only with the first formula, and I also voted to the third one, so I will try a little bit more. Thank you very much! 2010. janu?r 29. 17:53 Hugo Arts ?rta, : > 2010/1/29 BOB?K Szabolcs : > > > > This also works, but this not: > > sql_command_stat = 'SELECT COUNT(lastmoddate) FROM > > '+sql_tablename_orig+'WHERE lastmoddate < '+str(lastmod_date1) > > sql_cursor.execute(sql_command_stat) > > > > This was my original try, but tried various in various formula. > > sql_command_stat = 'SELECT COUNT(lastmoddate) FROM > > '+sql_tablename_orig+'WHERE lastmoddate < %d' > > sql_cursor.execute(sql_command_stat, %lastmod_date1) > > > > sql_command_stat = 'SELECT COUNT(lastmoddate) FROM > > '+sql_tablename_orig+'WHERE lastmoddate < (?)' > > sql_cursor.execute(sql_command_stat, (lastmod_date1)) > > > > But always the same error message: > > sqlite3.OperationalError: near "<": syntax error > > File "C:\python\stat.py", line 42, in > > sql_cursor.execute(sql_command_stat) > > > > From the three attempt I concluded that it's the same if I pass the > variable > > value as a string or an integer (maybe I am wrong). > > Your error isn't where you expect it to be. Let's take a look at the > string you're actually passing: > > >>> sql_tablename_orig = 'pyfilestat_drive_e_2010_01_27_16_48_31' > >>> sql_command_stat = 'SELECT COUNT(lastmoddate) FROM > '+sql_tablename_orig+'WHERE lastmoddate < %d' > >>> sql_command_stat > 'SELECT COUNT(lastmoddate) FROM > pyfilestat_drive_e_2010_01_27_16_48_31WHERE lastmoddate < %d' > > well, hello. we seem to be having a missing space, right in between > the table name and 'WHERE.' > > Also, you should use the third form, using the parameters argument of > execute(). it's the only secure one. > > Hugo > -- Bob?k Szabolcs -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Fri Jan 29 19:20:39 2010 From: roadierich at googlemail.com (Rich Lovely) Date: Fri, 29 Jan 2010 18:20:39 +0000 Subject: [Tutor] hash value input In-Reply-To: <1c2a2c591001290854w3568e38cq898de293722c50ef@mail.gmail.com> References: <20100129140322.62b711b0@o> <1c2a2c591001290854w3568e38cq898de293722c50ef@mail.gmail.com> Message-ID: On 29 January 2010 16:54, Kent Johnson wrote: > On Fri, Jan 29, 2010 at 8:03 AM, spir wrote: > >> I recently discovered that Lua uses the data's address (read: id) as input to the hash func. This allows Lua tables (a kind of more versatile associative array) to use _anything_ as key, since the id is guaranteed not to change, per definition. >> [Aside this consideration, hashing addresses ensures a constant type as input (so allows a specific efficient hash method) and the simplest possible one.] > > This sounds like a bad idea to me. You generally want key lookup to be > based on value, not identity. For example, if I say > > d = dict() > d['key'] = value > > and later > print d['key'] > > I want this to print 'value' regardless of whether I use the same > instance of the string 'key' in both cases. > > Maybe Lua has some mechanism for ensuring that this can't happen? > > In general, for a hash table to work as expected, two keys that are > equal in value should have the same hash value. Here is an explanation > of why (for Java, but it pretty much applies to any hash table > implementation): > http://www.javaworld.com/javaqa/2002-06/01-qa-0621-hashtable.html > > Kent > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I've played with this a little. The following class was quite handy for this: class BrokenHash(object): def __init__(self, hashval): self.hashval = hashval def __hash__(self): return self.hashval It basically implements the python hashable interface, but in a manner that is "broken" - it allows you control over what the object points to. >From this, we can tell that chaning the value of an object's hash changes its "bucket": >>> b = BrokenHash(1) >>> d = {b:1} >>> b.hashval=2 >>> d[b] Traceback (most recent call last): File "", line 1, in KeyError: <__main__.BrokenHash object at 0x657d70> But it's more than just the objects hash: >>> b2 = BrokenHash(hash("foo")) >>> hash(b2) == hash("foo") True >>> d2 = {b2: "bar", "foo": "baz"} >>> print d2 {<__main__.BrokenHash object at 0x657e10>: 'bar', 'foo': 'baz'} (If they both fell into the same bucket, d2['foo'] would overwrite d2[b2] It appears to be some combination of identity and hash. It is not, however, dependant on type: >>> b3 = BrokenHash(hash("foo")) #same hash as b2 >>> d2[b3] Traceback (most recent call last): File "", line 1, in KeyError: <__main__.BrokenHash object at 0x657e90> Don't know if that's helped at all. -- 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. From scottp at juniper.net Fri Jan 29 18:49:20 2010 From: scottp at juniper.net (Scott Pritchard) Date: Fri, 29 Jan 2010 09:49:20 -0800 Subject: [Tutor] Python and Ajax classes at Foothill College Message-ID: <4B631FA0.1000203@juniper.net> I would like to take your python class @ middlefield foothill campus. Can I sign up for the next class? When will it start? Thanks much, Scott From roadierich at googlemail.com Fri Jan 29 19:38:57 2010 From: roadierich at googlemail.com (Rich Lovely) Date: Fri, 29 Jan 2010 18:38:57 +0000 Subject: [Tutor] Python and Ajax classes at Foothill College In-Reply-To: <4B631FA0.1000203@juniper.net> References: <4B631FA0.1000203@juniper.net> Message-ID: I think you've got the wrong mailing list. This is an online "helpline" for anybody who is learning python, not a list for a specific class. On 29 January 2010 17:49, Scott Pritchard wrote: > > I would like to take your python class @ middlefield > foothill campus. > > Can I sign up for the next class? When will it start? > > Thanks much, > Scott > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- 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. From kent37 at tds.net Fri Jan 29 19:41:50 2010 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Jan 2010 13:41:50 -0500 Subject: [Tutor] hash value input In-Reply-To: References: <20100129140322.62b711b0@o> <1c2a2c591001290854w3568e38cq898de293722c50ef@mail.gmail.com> Message-ID: <1c2a2c591001291041m4712e827m1e122c51ab24ea69@mail.gmail.com> On Fri, Jan 29, 2010 at 1:20 PM, Rich Lovely wrote: > I've played with this a little. ?The following class was quite handy for this: > > class BrokenHash(object): > ? ?def __init__(self, hashval): > ? ? ? ?self.hashval = hashval > ? ?def __hash__(self): > ? ? ? ?return self.hashval > > It basically implements the python hashable interface, but in a manner > that is "broken" - it allows you control over what the object points > to. > > From this, we can tell that chaning the value of an object's hash > changes its "bucket": > >>>> b = BrokenHash(1) >>>> d = {b:1} >>>> b.hashval=2 >>>> d[b] > Traceback (most recent call last): > ?File "", line 1, in > KeyError: <__main__.BrokenHash object at 0x657d70> > > But it's more than just the objects hash: > >>>> b2 = BrokenHash(hash("foo")) >>>> hash(b2) == hash("foo") > True >>>> d2 = {b2: "bar", "foo": "baz"} >>>> print d2 > {<__main__.BrokenHash object at 0x657e10>: 'bar', 'foo': 'baz'} > > (If they both fell into the same bucket, d2['foo'] would overwrite d2[b2] Only if they compared equal. Placement and retrieval of items in hash tables depends on both the hash value and equality comparisons. The hash value determines the bucket, equality is used to disambiguate keys with the same hash value. > It appears to be some combination of identity and hash. ?It is not, > however, dependant on type: > >>>> b3 = BrokenHash(hash("foo")) #same hash as b2 Same hash but not equal. Kent >>>> d2[b3] > Traceback (most recent call last): > ?File "", line 1, in > KeyError: <__main__.BrokenHash object at 0x657e90> > > Don't know if that's helped at all. > > -- > Rich "Roadie Rich" Lovely From scottp at juniper.net Fri Jan 29 19:45:07 2010 From: scottp at juniper.net (Scott Pritchard) Date: Fri, 29 Jan 2010 10:45:07 -0800 Subject: [Tutor] Python and Ajax classes at Foothill College In-Reply-To: References: <4B631FA0.1000203@juniper.net> Message-ID: <4B632CB3.6040500@juniper.net> Oh, sorry about that. Rich Lovely wrote: > I think you've got the wrong mailing list. This is an online > "helpline" for anybody who is learning python, not a list for a > specific class. > > On 29 January 2010 17:49, Scott Pritchard wrote: > >> I would like to take your python class @ middlefield >> foothill campus. >> >> Can I sign up for the next class? When will it start? >> >> Thanks much, >> Scott >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > From wescpy at gmail.com Fri Jan 29 20:52:45 2010 From: wescpy at gmail.com (wesley chun) Date: Fri, 29 Jan 2010 11:52:45 -0800 Subject: [Tutor] Python and Ajax classes at Foothill College In-Reply-To: <4B632CB3.6040500@juniper.net> References: <4B631FA0.1000203@juniper.net> <4B632CB3.6040500@juniper.net> Message-ID: <78b3a9581001291152r2338f498t9a30376b4726024e@mail.gmail.com> for future reference, you can go sign up for the courses at http://foothill.edu ... i'll be delivering the intermediate Python course next year FWIW. cheers, -wesley On Fri, Jan 29, 2010 at 10:45 AM, Scott Pritchard wrote: > Oh, sorry about that. > > Rich Lovely wrote: >> >> I think you've got the wrong mailing list. ?This is an online >> "helpline" for anybody who is learning python, not a list for a >> specific class. >> >> On 29 January 2010 17:49, Scott Pritchard wrote: >> >>> >>> I would like to take your python class @ middlefield >>> foothill campus. >>> >>> Can I sign up for the next class? When will it start? >>> >>> Thanks much, >>> Scott -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From david at pythontoo.com Fri Jan 29 21:15:10 2010 From: david at pythontoo.com (David Abbott) Date: Fri, 29 Jan 2010 15:15:10 -0500 Subject: [Tutor] [OT] Python Study Group Message-ID: <1264796110.27014.27.camel@opteron.dwabbott.com> A group of beginners and intermediate Pythonerrs and getting together to study the book Core Python Programming by Wesley Chun. We are starting on chapter one on Feb first. We are hoping to do a chapter every 2 weeks, but some we can devote a month to as needed. It is a self study group so really no deadline. If you would like to join please email me off list or just sign up at the wiki; http://asterisklinks.com/wiki/doku.php?id=core:start#members thanks, david -- David Abbott From zstumgoren at gmail.com Fri Jan 29 21:26:24 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 29 Jan 2010 15:26:24 -0500 Subject: [Tutor] [OT] Python Study Group In-Reply-To: <1264796110.27014.27.camel@opteron.dwabbott.com> References: <1264796110.27014.27.camel@opteron.dwabbott.com> Message-ID: Sounds like a cool idea David. Is this an online study group or do the folks who signed up live near each other geographically as well? On Fri, Jan 29, 2010 at 3:15 PM, David Abbott wrote: > A group of beginners and intermediate Pythonerrs and getting together to > study the book Core Python Programming by Wesley Chun. We are starting > on chapter one on Feb first. We are hoping to do a chapter every 2 > weeks, but some we can devote a month to as needed. It is a self study > group so really no deadline. If you would like to join please email me > off list or just sign up at the wiki; > http://asterisklinks.com/wiki/doku.php?id=core:start#members > > thanks, > david > > > -- > David Abbott > > _______________________________________________ > 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 david at pythontoo.com Fri Jan 29 21:42:58 2010 From: david at pythontoo.com (David Abbott) Date: Fri, 29 Jan 2010 15:42:58 -0500 Subject: [Tutor] [OT] Python Study Group In-Reply-To: References: <1264796110.27014.27.camel@opteron.dwabbott.com> Message-ID: <1264797778.27014.31.camel@opteron.dwabbott.com> On Fri, 2010-01-29 at 15:26 -0500, Serdar Tumgoren wrote: > Sounds like a cool idea David. Is this an online study group or do the > folks who signed up live near each other geographically as well? Its all online, we have people from India to Germany as an example. -- David Abbott From wescpy at gmail.com Fri Jan 29 23:59:58 2010 From: wescpy at gmail.com (wesley chun) Date: Fri, 29 Jan 2010 14:59:58 -0800 Subject: [Tutor] [OT] Python Study Group In-Reply-To: References: <1264796110.27014.27.camel@opteron.dwabbott.com> Message-ID: <78b3a9581001291459n34a1603fy9df8784312a0607e@mail.gmail.com> for some reason, i can't do anything other than to wholeheartedly support this project. :-) let me know how i can help. also, if you have older editions/printings, be sure to check the Errata at the book's website http://corepython.com i am starting to do some research for the 3rd edition of the book now and would love to get as much feedback from you all as i can. best regards, -wesley On Fri, Jan 29, 2010 at 12:26 PM, Serdar Tumgoren wrote: > Sounds like a cool idea David. Is this an online study group or do the folks > who signed up live near each other geographically as well? > > On Fri, Jan 29, 2010 at 3:15 PM, David Abbott wrote: >> >> A group of beginners and intermediate Pythonerrs and getting together to >> study the book Core Python Programming by Wesley Chun. We are starting >> on chapter one on Feb first. We are hoping to do a chapter every 2 >> weeks, but some we can devote a month to as needed. It is a self study >> group so really no deadline. If you would like to join please email me >> off list or just sign up at the wiki; >> http://asterisklinks.com/wiki/doku.php?id=core:start#members >> >> thanks, >> david -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From denis.spir at free.fr Sat Jan 30 10:56:46 2010 From: denis.spir at free.fr (spir) Date: Sat, 30 Jan 2010 10:56:46 +0100 Subject: [Tutor] hash value input In-Reply-To: References: <20100129140322.62b711b0@o> Message-ID: <20100130105646.1f93ed74@o> On Fri, 29 Jan 2010 08:23:37 -0800 Emile van Sebille wrote: > > So, how does python do this? > > > > Start here... > > http://effbot.org/zone/python-hash.htm Great, thank you! From the above pointed page: ======= For ordinary integers, the hash value is simply the integer itself (unless it?s -1). class int: def __hash__(self): value = self if value == -1: value == -2 return value ======= I'm surprised of this, for this should create as many indexes (in the underlying array actually holding the values) as there are integer keys. With possibly huge holes in the array. Actually, there will certainly be a predefined number of indexes N, and the integers be further "modulo-ed" N. Or what? I would love to know how to sensibly chose the number of indexes. Pointers welcome (my searches did not bring any clues on the topic). > Emile Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From davea at ieee.org Sat Jan 30 12:31:33 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 30 Jan 2010 06:31:33 -0500 Subject: [Tutor] hash value input In-Reply-To: <20100130105646.1f93ed74@o> References: <20100129140322.62b711b0@o> <20100130105646.1f93ed74@o> Message-ID: <4B641895.1040204@ieee.org> spir wrote: > On Fri, 29 Jan 2010 08:23:37 -0800 > Emile van Sebille wrote: > > >>> So, how does python do this? >>> >>> >> Start here... >> >> http://effbot.org/zone/python-hash.htm >> > > Great, thank you! > From the above pointed page: > > ====For ordinary integers, the hash value is simply the integer itself (unless it?s -1). > > class int: > def __hash__(self): > value =elf > if value =-1: > value =-2 > return value > ==== > I'm surprised of this, for this should create as many indexes (in the underlying array actually holding the values) as there are integer keys. With possibly huge holes in the array. Actually, there will certainly be a predefined number of indexes N, and the integers be further "modulo-ed" N. Or what? > I would love to know how to sensibly chose the number of indexes. Pointers welcome (my searches did not bring any clues on the topic). > > >> Emile >> > > Denis > ________________________________ > > la vita e estrany > > http://spir.wikidot.com/ > > I haven't seen the sources, so I'm making an educated guess based on things I have seen. The index size grows as the size of the dictionary grows, and the formula is not linear. Neither are the sizes obvious powers of two or suchlike. I doubt if you have any control over it, however. The hash() function returns an int (32 bits on 32bit python), which is then converted to the bucket number, probably by a simple modulo function. In the case of integers, it's the modulo which distributes the integers among the buckets. If all the integer keys are consecutive, then modulo distributes them perfectly. If they're random, then it'll usually work pretty well, but you could hit a pattern which puts lots of values in one bucket, and not many in the others. If the index size is 22, and all your numbers are multiple of 22, then it might degenerate to effectively one bucket. BTW, the referenced article does have a contradiction. For a long int whose value is between 16 and 31 bits, the described approach will not generate the same hash as the int of the same value. So that 15 bit shift algorithm must have some other subtlety to it, perhaps only starting with bit 31 or so. DaveA From kent37 at tds.net Sat Jan 30 13:35:56 2010 From: kent37 at tds.net (Kent Johnson) Date: Sat, 30 Jan 2010 07:35:56 -0500 Subject: [Tutor] hash value input In-Reply-To: <20100130105646.1f93ed74@o> References: <20100129140322.62b711b0@o> <20100130105646.1f93ed74@o> Message-ID: <1c2a2c591001300435h40eeb127off35cf17add5ee2c@mail.gmail.com> On Sat, Jan 30, 2010 at 4:56 AM, spir wrote: > I'm surprised of this, for this should create as many indexes (in the underlying array actually holding the values) as there are integer keys. With possibly huge holes in the array. Actually, there will certainly be a predefined number of indexes N, and the integers be further "modulo-ed" N. Or what? > I would love to know how to sensibly chose the number of indexes. Pointers welcome (my searches did not bring any clues on the topic). Wikipedia has an extensive article on hash tables. For details of the Python implementation, there are many comments in the source: http://svn.python.org/view/python/trunk/Objects/dictobject.c?view=markup and more implementation notes here: http://svn.python.org/view/python/trunk/Objects/dictnotes.txt?view=markup Kent From erimendz at gmail.com Sat Jan 30 03:33:07 2010 From: erimendz at gmail.com (Eri Mendz) Date: Sat, 30 Jan 2010 05:33:07 +0300 Subject: [Tutor] [OT] Python Study Group In-Reply-To: <78b3a9581001291459n34a1603fy9df8784312a0607e@mail.gmail.com> References: <1264796110.27014.27.camel@opteron.dwabbott.com> <78b3a9581001291459n34a1603fy9df8784312a0607e@mail.gmail.com> Message-ID: <88d91f011001291833i3590ac87k3d0037576592265f@mail.gmail.com> You have no choice Wesley, after all this is your book haha. I have joined in since i have your book 2nd edition. I even have your livelessons CD, i thought i get it as well to complement the thick 2nd ed. book. Looking forward to meet you all soon. -- Best Regards Jonathan Swift - "May you live every day of your life." - http://www.brainyquote.com/quotes/authors/j/jonathan_swift.html On Sat, Jan 30, 2010 at 1:59 AM, wesley chun wrote: > for some reason, i can't do anything other than to wholeheartedly > support this project. :-) let me know how i can help. also, if you > have older editions/printings, be sure to check the Errata at the > book's website http://corepython.com > > i am starting to do some research for the 3rd edition of the book now > and would love to get as much feedback from you all as i can. > > best regards, > -wesley > > > On Fri, Jan 29, 2010 at 12:26 PM, Serdar Tumgoren wrote: >> Sounds like a cool idea David. Is this an online study group or do the folks >> who signed up live near each other geographically as well? >> >> On Fri, Jan 29, 2010 at 3:15 PM, David Abbott wrote: >>> >>> A group of beginners and intermediate Pythonerrs and getting together to >>> study the book Core Python Programming by Wesley Chun. We are starting >>> on chapter one on Feb first. We are hoping to do a chapter every 2 >>> weeks, but some we can devote a month to as needed. It is a self study >>> group so really no deadline. If you would like to join please email me >>> off list or just sign up at the wiki; >>> http://asterisklinks.com/wiki/doku.php?id=core:start#members >>> >>> thanks, >>> david > > > -- > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Python Web Development with Django", Addison Wesley, (c) 2009 > ? ?http://withdjango.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From nikunjbadjatya at gmail.com Sat Jan 30 20:15:36 2010 From: nikunjbadjatya at gmail.com (nikunj badjatya) Date: Sun, 31 Jan 2010 00:45:36 +0530 Subject: [Tutor] Future of Python Programmers In-Reply-To: References: Message-ID: Dear all PyPers, . I have one important question to ask to all of you, I am a fresher, recently completed my graduation, had started working on python 2 months back..!! and I just fell in love with the language. I want to learn more about it. The only concern is there arent enough companies which work on Python. ( Kindly correct if I am wrong?? ) and also kindly tell me the core application areas of the language, ( Is there any where Python is dominating compared to other languages? ) I followed up a link ( http://www.dmh2000.com/cjpr/ ) which nicely illustrates difference between many languages. Is there any chance where the development of Python will make it as fast as C++ or JAVA, (or it is at its optimum level? ) . P.S. I have recently joined the group, dont know if similar discussions held before. I dont know if this is the right way to ask these type of questions . Sincerely, Nikunj Badjatya BTech Bangalore, India -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sat Jan 30 20:37:18 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 30 Jan 2010 13:37:18 -0600 Subject: [Tutor] Future of Python Programmers In-Reply-To: References: Message-ID: <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com> On Sat, Jan 30, 2010 at 1:15 PM, nikunj badjatya wrote: > > Dear all PyPers, > . > I have one important question to ask to all of you, > I am a fresher, recently completed my graduation, had started working on > python 2 months back..!! and I just fell in love with the language. I want > to learn more about it. > The only concern is there arent enough companies which work on Python. ( > Kindly correct if I am wrong?? ) > and also kindly tell me the core application areas of the language, ( Is > there any where Python is dominating compared to other languages? ) > I followed up a link ( http://www.dmh2000.com/cjpr/ ) which nicely > illustrates difference between many languages. > Is there any chance where the development of Python will make it as fast as > C++ or JAVA, (or it is at its optimum level? ) . > > P.S. I have recently joined the group, dont know if similar discussions > held before. > I dont know if this is the right way to ask these type of questions > . > That's a perfectly acceptable way to ask the questions, and probably at least a decent place to ask them. I know there have been a few questions of that nature. As far as I know and can tell - for the most part, many of the Python libraries are implemented in C. This makes it nearly/as fast as C. There are many companies that work with Python, though for some of us pythonistas there's no such thing as enough ;) -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From invincible_patriot at hotmail.com Sat Jan 30 22:33:37 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Sat, 30 Jan 2010 21:33:37 +0000 Subject: [Tutor] can any one help In-Reply-To: <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com> References: , , <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com> Message-ID: hii am stuck in few tasks can some one help me in thathere are first few tasks 1how can i print the following series, using a loop151311...31-1========2Write a small Python program that generates the list of all pairs of characters c andits doubling 2  c, where c moves through all the letters of the string "foobar" and prints it out.The result will look like:[(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)] please help me out in these two tasks _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. http://clk.atdmt.com/GBL/go/196390707/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fubarninja at hotmail.com Sat Jan 30 23:17:50 2010 From: fubarninja at hotmail.com (jim serson) Date: Sat, 30 Jan 2010 17:17:50 -0500 Subject: [Tutor] Problem creating a search Message-ID: Hi I am pretty new to python and programming in general. I am trying to create a search that takes a user input for a file location and user input to find a group of numbers or a phrase in that file count how many times it appears then display it. I have gone through a tutorials and searched I/O to find the code I need. Although I have not been able to make it work properly yet. I am able to open and read from the file the user would input but cant seem to make the other input retrieve the numbers or phrase from the file or have it count how many time it appears. If anyone can help or point me in the right direction I would appreciate it. Thanks for your time. look_in = raw_input ("Enter the search file to look in ") search = raw_input ("Enter your search item ") count = 0 file = open(look_in, "r") line = file.readline() while line: print line line = file.readline() search == line if search in line: search = count + 1 print count print search, "your search was found" else: print ("your search was not found") file.close() _________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Sat Jan 30 23:26:56 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 31 Jan 2010 03:56:56 +0530 Subject: [Tutor] can any one help In-Reply-To: References: <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com> Message-ID: seems like homework ;) Can you paste your approach here ? On Sun, Jan 31, 2010 at 3:03 AM, invincible patriot < invincible_patriot at hotmail.com> wrote: > > hi > i am stuck in few tasks can some one help me in that > here are first few tasks > > 1 > how can i print the following series, using a loop > 15 > 13 > 11 > ... > 3 > 1 > -1 > ======== > 2 > Write a small Python program that generates the list of all pairs of > characters c and > its doubling 2 c, where c moves through all the letters of the string > "foobar" and prints it out. > The result will look like: > [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, > ?rr?)] > > please help me out in these two tasks > > > ------------------------------ > Hotmail: Trusted email with powerful SPAM protection. Sign up now. > > _______________________________________________ > 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 Sat Jan 30 23:35:09 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 31 Jan 2010 04:05:09 +0530 Subject: [Tutor] can any one help In-Reply-To: References: <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com> Message-ID: Tips: 1. range can be stepped down in reverse order ex -> >>> range(10, 1, -2) [10, 8, 6, 4, 2] 2. you can directly get chars of string. ex -> >>> [i for i in 'foobar'] ['f', 'o', 'o', 'b', 'a', 'r'] also >>> 2 * 'f' 'ff' On Sun, Jan 31, 2010 at 3:56 AM, Shashwat Anand wrote: > seems like homework ;) > Can you paste your approach here ? > > On Sun, Jan 31, 2010 at 3:03 AM, invincible patriot < > invincible_patriot at hotmail.com> wrote: > >> >> hi >> i am stuck in few tasks can some one help me in that >> here are first few tasks >> >> 1 >> how can i print the following series, using a loop >> 15 >> 13 >> 11 >> ... >> 3 >> 1 >> -1 >> ======== >> 2 >> Write a small Python program that generates the list of all pairs of >> characters c and >> its doubling 2 c, where c moves through all the letters of the string >> "foobar" and prints it out. >> The result will look like: >> [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, >> ?rr?)] >> >> please help me out in these two tasks >> >> >> ------------------------------ >> Hotmail: Trusted email with powerful SPAM protection. Sign up now. >> >> _______________________________________________ >> 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 Sat Jan 30 23:42:45 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 31 Jan 2010 04:12:45 +0530 Subject: [Tutor] Problem creating a search In-Reply-To: References: Message-ID: On Sun, Jan 31, 2010 at 3:47 AM, jim serson wrote: > Hi I am pretty new to python and programming in general. I am trying to > create a search that takes a user input for a file location and user input > to find a group of numbers or a phrase in that file count how many times it > appears then display it. > > I have gone through a tutorials and searched I/O to find the code I need. > Although I have not been able to make it work properly yet. > > I am able to open and read from the file the user would input but cant seem > to make the other input retrieve the numbers or phrase from the file or have > it count how many time it appears. If anyone can help or point me in the > right direction I would appreciate it. Thanks for your time. > > 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) print c if c: print search, "your search was found" else: print "your search was not found" ''' line = file.readline() while line: print line line = file.readline() search == line if search in line: search = count + 1 print count print search, "your search was found" else: print ("your search was not found") file.close() ''' ------------------------------ Spread the cheer with Messenger for mobile. Learn more. > > _______________________________________________ > 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 Sat Jan 30 23:46:40 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Sun, 31 Jan 2010 04:16:40 +0530 Subject: [Tutor] can any one help In-Reply-To: References: <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com> Message-ID: I got the question. I just gave you hints, so as you can try yourself. Also please use 'Reply all' On Sun, Jan 31, 2010 at 4:08 AM, invincible patriot < invincible_patriot at hotmail.com> wrote: > I want to use WHILE LOOP in the first one and in the second question we > need to take a string 'foobar' and then we should make the prog to get the > following out put > let me tel u the exact question > > Write a small Python program that generates the list of all pairs of > characters c and > its doubling 2 c, where c moves through all the letters of the string > "foobar" and prints it out. > The result will look like: > [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, > ?rr?)] > > thatz the exact 2nd question > also let me know aboutthe first one > > thanks allot > > ------------------------------ > From: anand.shashwat at gmail.com > Date: Sun, 31 Jan 2010 04:05:09 +0530 > > Subject: Re: [Tutor] can any one help > To: invincible_patriot at hotmail.com > CC: tutor at python.org > > Tips: > > 1. > range can be stepped down in reverse order > ex -> > >>> range(10, 1, -2) > [10, 8, 6, 4, 2] > > 2. > you can directly get chars of string. > ex -> > >>> [i for i in 'foobar'] > ['f', 'o', 'o', 'b', 'a', 'r'] > also > >>> 2 * 'f' > 'ff' > > > On Sun, Jan 31, 2010 at 3:56 AM, Shashwat Anand wrote: > > seems like homework ;) > Can you paste your approach here ? > > On Sun, Jan 31, 2010 at 3:03 AM, invincible patriot < > invincible_patriot at hotmail.com> wrote: > > > hi > i am stuck in few tasks can some one help me in that > here are first few tasks > > 1 > how can i print the following series, using a loop > 15 > 13 > 11 > ... > 3 > 1 > -1 > ======== > 2 > Write a small Python program that generates the list of all pairs of > characters c and > its doubling 2 c, where c moves through all the letters of the string > "foobar" and prints it out. > The result will look like: > [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, > ?rr?)] > > please help me out in these two tasks > > > ------------------------------ > Hotmail: Trusted email with powerful SPAM protection. Sign up now. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > ------------------------------ > Hotmail: Trusted email with powerful SPAM protection. Sign up now. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From invincible_patriot at hotmail.com Sat Jan 30 23:49:58 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Sat, 30 Jan 2010 22:49:58 +0000 Subject: [Tutor] can any one help In-Reply-To: References: , , <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com>, , , , Message-ID: ya definately, just give me the hinti made a prog for the first one but it when ran, saying RESTART in active shell def fibn(n): a,b=15,2 while a>n: print a, a,b=a,a+b fibn(-1) whatz rong in this prog that the error is saying no break point thanks From: anand.shashwat at gmail.com Date: Sun, 31 Jan 2010 04:16:40 +0530 Subject: Re: [Tutor] can any one help To: invincible_patriot at hotmail.com CC: tutor at python.org I got the question. I just gave you hints, so as you can try yourself. Also please use 'Reply all' On Sun, Jan 31, 2010 at 4:08 AM, invincible patriot wrote: I want to use WHILE LOOP in the first one and in the second question we need to take a string 'foobar' and then we should make the prog to get the following out putlet me tel u the exact question Write a small Python program that generates the list of all pairs of characters c andits doubling 2 c, where c moves through all the letters of the string "foobar" and prints it out. The result will look like:[(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)] thatz the exact 2nd questionalso let me know aboutthe first one thanks allot From: anand.shashwat at gmail.com Date: Sun, 31 Jan 2010 04:05:09 +0530 Subject: Re: [Tutor] can any one help To: invincible_patriot at hotmail.com CC: tutor at python.org Tips: 1. range can be stepped down in reverse order ex -> >>> range(10, 1, -2) [10, 8, 6, 4, 2] 2. you can directly get chars of string. ex -> >>> [i for i in 'foobar'] ['f', 'o', 'o', 'b', 'a', 'r'] also >>> 2 * 'f' 'ff' On Sun, Jan 31, 2010 at 3:56 AM, Shashwat Anand wrote: seems like homework ;) Can you paste your approach here ? On Sun, Jan 31, 2010 at 3:03 AM, invincible patriot wrote: hii am stuck in few tasks can some one help me in thathere are first few tasks 1how can i print the following series, using a loop1513 11...31-1========2Write a small Python program that generates the list of all pairs of characters c andits doubling 2 c, where c moves through all the letters of the string "foobar" and prints it out. The result will look like:[(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)] please help me out in these two tasks Hotmail: Trusted email with powerful SPAM protection. Sign up now. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hotmail: Trusted email with powerful SPAM protection. Sign up now. _________________________________________________________________ Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. http://clk.atdmt.com/GBL/go/196390709/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From evosweet at hotmail.com Sat Jan 30 23:51:08 2010 From: evosweet at hotmail.com (Rayon) Date: Sat, 30 Jan 2010 18:51:08 -0400 Subject: [Tutor] python 2.6 and MySQL fail Message-ID: I have installed python 2.6.4 on my windows7 laptop and MySQL dB. Every time I try to import the module I get this error. File "C:\Python26\lib\site-packages\MySQLdb\__init__.py", line 19, in import _mysql ImportError: DLL load failed: The specified module could not be found. I need to know why and if there is a fix I can use. This works fine on python2.5. -------------- next part -------------- An HTML attachment was scrubbed... URL: From grigor.kolev at gmail.com Sun Jan 31 00:21:15 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Sun, 31 Jan 2010 01:21:15 +0200 Subject: [Tutor] can any one help In-Reply-To: References: , , <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com> , , , , Message-ID: <1264893675.6587.29.camel@dedal-laptop> ? 22:49 +0000 ?? 30.01.2010 (??), invincible patriot ??????: > ya definately, just give me the hint > > i made a prog for the first one but it when ran, saying RESTART in > active shell > > > def fibn(n): > a,b=15,2 > while a>n: > print a, > a,b=a,a+b > fibn(-1) > > > whatz rong in this prog that the error is saying no break point > > > thanks > > ______________________________________________________________________ > From: anand.shashwat at gmail.com > Date: Sun, 31 Jan 2010 04:16:40 +0530 > Subject: Re: [Tutor] can any one help > To: invincible_patriot at hotmail.com > CC: tutor at python.org > > I got the question. I just gave you hints, so as you can try yourself. > Also please use 'Reply all' > > > On Sun, Jan 31, 2010 at 4:08 AM, invincible patriot > wrote: > > I want to use WHILE LOOP in the first one and in the second > question we need to take a string 'foobar' and then we should > make the prog to get the following out put > > let me tel u the exact question > > > Write a small Python program that generates the list of all > pairs of characters c and > its doubling 2 c, where c moves through all the letters of the > string "foobar" and prints it out. > The result will look like: > [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, > ?aa?), (?r?, ?rr?)] > > > thatz the exact 2nd question > also let me know aboutthe first one > > > thanks allot > > > ______________________________________________________________ > From: anand.shashwat at gmail.com > > > Date: Sun, 31 Jan 2010 04:05:09 +0530 > > > Subject: Re: [Tutor] can any one help > To: invincible_patriot at hotmail.com > CC: tutor at python.org > > > > Tips: > > 1. > range can be stepped down in reverse order > ex -> > >>> range(10, 1, -2) > [10, 8, 6, 4, 2] > > 2. > you can directly get chars of string. > ex -> > >>> [i for i in 'foobar'] > ['f', 'o', 'o', 'b', 'a', 'r'] > also > >>> 2 * 'f' > 'ff' > > > > On Sun, Jan 31, 2010 at 3:56 AM, Shashwat Anand > wrote: > > seems like homework ;) > Can you paste your approach here ? > > > > On Sun, Jan 31, 2010 at 3:03 AM, invincible patriot > wrote: > > > > hi > > i am stuck in few tasks can some one help me > in that > here are first few tasks > > > 1 > how can i print the following series, using a > loop > 15 > 13 > 11 > ... > 3 > 1 > -1 > ======== > 2 > Write a small Python program that generates > the list of all pairs of characters c and > its doubling 2 c, where c moves through all > the letters of the string "foobar" and prints > it out. > The result will look like: > [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, > ?bb?), (?a?, ?aa?), (?r?, ?rr?)] > > > please help me out in these two tasks > > > > > ______________________________________________ > Hotmail: Trusted email with powerful SPAM > protection. Sign up now. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > ______________________________________________________________ > Hotmail: Trusted email with powerful SPAM protection. Sign up > now. > > > > > > > ______________________________________________________________________ > Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. Sign up > now. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor def fibn(n): a,b=15,2 while a>n: print a, # it is same like print a, a, b = a, a+b You can not print this. SyntaxError: invalid syntax a,b=a,a+b fibn(-1) -- Grigor Kolev -------------- next part -------------- An HTML attachment was scrubbed... URL: From invincible_patriot at hotmail.com Sun Jan 31 00:24:18 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Sat, 30 Jan 2010 23:24:18 +0000 Subject: [Tutor] can any one help In-Reply-To: <1264893675.6587.29.camel@dedal-laptop> References: ,, ,, <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com>,, , , , ,, ,, , , <1264893675.6587.29.camel@dedal-laptop> Message-ID: ???? didnt got what u replied Subject: Re: [Tutor] can any one help From: grigor.kolev at gmail.com To: invincible_patriot at hotmail.com CC: anand.shashwat at gmail.com; tutor at python.org Date: Sun, 31 Jan 2010 01:21:15 +0200 ? 22:49 +0000 ?? 30.01.2010 (??), invincible patriot ??????: ya definately, just give me the hint i made a prog for the first one but it when ran, saying RESTART in active shell def fibn(n): a,b=15,2 while a>n: print a, a,b=a,a+b fibn(-1) whatz rong in this prog that the error is saying no break point thanks From: anand.shashwat at gmail.com Date: Sun, 31 Jan 2010 04:16:40 +0530 Subject: Re: [Tutor] can any one help To: invincible_patriot at hotmail.com CC: tutor at python.org I got the question. I just gave you hints, so as you can try yourself. Also please use 'Reply all' On Sun, Jan 31, 2010 at 4:08 AM, invincible patriot wrote: I want to use WHILE LOOP in the first one and in the second question we need to take a string 'foobar' and then we should make the prog to get the following out put let me tel u the exact question Write a small Python program that generates the list of all pairs of characters c and its doubling 2 c, where c moves through all the letters of the string "foobar" and prints it out. The result will look like: [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)] thatz the exact 2nd question also let me know aboutthe first one thanks allot From: anand.shashwat at gmail.com Date: Sun, 31 Jan 2010 04:05:09 +0530 Subject: Re: [Tutor] can any one help To: invincible_patriot at hotmail.com CC: tutor at python.org Tips: 1. range can be stepped down in reverse order ex -> >>> range(10, 1, -2) [10, 8, 6, 4, 2] 2. you can directly get chars of string. ex -> >>> [i for i in 'foobar'] ['f', 'o', 'o', 'b', 'a', 'r'] also >>> 2 * 'f' 'ff' On Sun, Jan 31, 2010 at 3:56 AM, Shashwat Anand wrote: seems like homework ;) Can you paste your approach here ? On Sun, Jan 31, 2010 at 3:03 AM, invincible patriot wrote: hi i am stuck in few tasks can some one help me in that here are first few tasks 1 how can i print the following series, using a loop 15 13 11 ... 3 1 -1 ======== 2 Write a small Python program that generates the list of all pairs of characters c and its doubling 2 c, where c moves through all the letters of the string "foobar" and prints it out. The result will look like: [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)] please help me out in these two tasks Hotmail: Trusted email with powerful SPAM protection. Sign up now. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hotmail: Trusted email with powerful SPAM protection. Sign up now. Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. Sign up now. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor def fibn(n): a,b=15,2 while a>n: print a, # it is same like print a, a, b = a, a+b You can not print this. SyntaxError: invalid syntax a,b=a,a+b fibn(-1) -- Grigor Kolev _________________________________________________________________ Hotmail: Powerful Free email with security by Microsoft. http://clk.atdmt.com/GBL/go/196390710/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From grigor.kolev at gmail.com Sun Jan 31 00:40:41 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Sun, 31 Jan 2010 01:40:41 +0200 Subject: [Tutor] can any one help In-Reply-To: References: ,, ,, <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com> ,, , ,, ,, ,, , ,<1264893675.6587.29.camel@dedal-laptop> Message-ID: <1264894841.6587.39.camel@dedal-laptop> Excuse me but I have question too. Why when i write this function in python shell not work says SyntaxError: invalid syntax but when I use IDLE make endless loop Sorry I also teach Python. > def fibn(n): > a,b=15,2 > while a>n: > print a, # it is same like print a, a, b = a, a+b > You can not print this. SyntaxError: invalid syntax > a,b=a,a+b > fibn(-1) -- Grigor Kolev From invincible_patriot at hotmail.com Sun Jan 31 00:46:30 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Sat, 30 Jan 2010 23:46:30 +0000 Subject: [Tutor] please help me In-Reply-To: <1264894841.6587.39.camel@dedal-laptop> References: ,,, ,,, <333efb451001301137i356ac18as6cfb9138b2f9787@mail.gmail.com>,,, , , , , , ,,, ,,, , , , , <1264893675.6587.29.camel@dedal-laptop>, , <1264894841.6587.39.camel@dedal-laptop> Message-ID: hii am stuck in these questions can someone please help me in solving and writing programme for these tasks please help me 1 1.1 Write a Python program with a loop that prints out a sequence of numbers as follows:151311...31-1 1.2 Write a small Python program that generates the list of all pairs of characters c andits doubling 2  c, where c moves through all the letters of the string "foobar" and prints it out.The result will look like:[(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)]Hint: use list comprehensions. 1.3 Write a small Python program that 1. prints out the length of the string?taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu? 2. prints out how many different characters this string contains 3. replaces all the non-?t? characters in above string with dots ?.?. So, if the word were?tattoo?, it would print ?t.tt..?.Hints: (a) use a function to t-ify the string (b) there are various ways to construct the string, either using the join method or by runninga loop accumulating substrings. (c) check also out what happens if you apply the conversion list(s) to a string s. 2 2.1 Write a function count char(s, c) that takes a string s, and a character c and returnshow often the character c appears in the string.For example count_char("tattoo", "t") should return 3. 2.2 Write a Python function char_freqency(s)that returns a dictionary which, for eachcharacter of s as a key, stores as value how often this character appears.For example, char_frequency("tattoo") could return {?a?: 1, ?t?: 3, ?o?: 2} (the order ofkey:value pairs does not matter here). Hint: Consider using the function count_char defined in 2.1. 2.3 Write a program that translates a given string (of arbitrary length) of DNA bases intothe RNA strand that it will produce. For this, research which DNA bases correspond to RNA basesand create a translation table (not an if...else clause!) in the Python program. [4 marks] 3 3.1 consider the following list of base sequences:ACGTACCTTACTTACCATATCGTACCTCTTACTCATThe task consists of writing a Python program that performs a simple alignment algorithm onthese two strings and prints out this alignment in a suitable readable form. Give a brief commentexplaining the output format.Hints:1. Matching means the following: for a given sequence to be matched, your program should denotewhich bases correspond to bases in the reference sequence and which do not; in addition, markgaps where the reference sequence contains bases which are not present in the sample sequence.For a given sample sequence, your matching algorithm will attempt to match as many basesas possible to those of the reference sequence.2. This is a difficult assignment. Do not attempt it before you have solved the others.3. For this purpose, you are allowed to research and implement publicly documented versions ofthe Needleman-Wunsch algorithm or similar algorithms (however, make sure that you refer-ence them properly!). Also make sure that your program prints out the matches/mismatchesbetween the sequences. You should demonstrate at least two different alignments by usingdifferent gap penalties.Instead of following this hint, you can develop an alternative solution to the matching problem,e.g. based on the Levenshtein distance. please help me _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. http://clk.atdmt.com/GBL/go/196390706/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From aneftaoratos at gmail.com Sun Jan 31 01:11:27 2010 From: aneftaoratos at gmail.com (Aneftaoratos Aneftaoratos) Date: Sun, 31 Jan 2010 02:11:27 +0200 Subject: [Tutor] Tutor Digest, Vol 71, Issue 78 In-Reply-To: References: Message-ID: #1 1.1 Write a Python program with a loop that prints out a sequence of numbers as follows:151311...31-1 A simple approach with a for loop: def MyRange(start, end, step): for n in range(start, end, step): if n == 0: print -1 break else: print n return #call the function MyRange(151311, -1, -31) Hope that helps! 2010/1/31 : > 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. Re: can any one help (invincible patriot) > ? 2. Re: can any one help (Grigor Kolev) > ? 3. please help me (invincible patriot) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 30 Jan 2010 23:24:18 +0000 > From: invincible patriot > To: > Cc: tutor at python.org > Subject: Re: [Tutor] can any one help > Message-ID: > Content-Type: text/plain; charset="windows-1251" > > > ???? didnt got what u replied > > > Subject: Re: [Tutor] can any one help > From: grigor.kolev at gmail.com > To: invincible_patriot at hotmail.com > CC: anand.shashwat at gmail.com; tutor at python.org > Date: Sun, 31 Jan 2010 01:21:15 +0200 > > > > > > > > > > > ? 22:49 +0000 ?? 30.01.2010 (??), invincible patriot ??????: > > > ? ?ya definately, just give me the hint > > > ? ?i made a prog for the first one but it when ran, saying RESTART in active shell > > > > > > > > > ? ?def fibn(n): > > > ? ?a,b=15,2 > > > ? ?while a>n: > > > ? ?print a, > > > ? ?a,b=a,a+b > > > ? ?fibn(-1) > > > > > > > > > ? ?whatz rong in this prog that the error is saying no break point > > > > > > > > > ? ?thanks > > > > > > ? ?From: anand.shashwat at gmail.com > > ? ?Date: Sun, 31 Jan 2010 04:16:40 +0530 > > ? ?Subject: Re: [Tutor] can any one help > > ? ?To: invincible_patriot at hotmail.com > > ? ?CC: tutor at python.org > > > > ? ?I got the question. I just gave you hints, so as you can try yourself. Also please use 'Reply all' > > > > > > ? ?On Sun, Jan 31, 2010 at 4:08 AM, invincible patriot wrote: > > > > ? ? ? ?I want to use WHILE LOOP in the first one and in the second question we need to take a string 'foobar' and then we should make the prog to get the following out put > > > > > ? ? ? ?let me tel u the exact question > > > > > > > > > > > > > ? ? ? ?Write a small Python program that generates the list of all pairs of characters c and > > > > > ? ? ? ?its doubling 2 c, where c moves through all the letters of the string "foobar" and prints it out. > > > > > ? ? ? ?The result will look like: > > > > > ? ? ? ?[(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)] > > > > > > > > > > > > > ? ? ? ?thatz the exact 2nd question > > > > > ? ? ? ?also let me know aboutthe first one > > > > > > > > > > > > > ? ? ? ?thanks allot > > > > > > > > > > > ? ? ? ?From: anand.shashwat at gmail.com > > > > > > > > ? ? ? ?Date: Sun, 31 Jan 2010 04:05:09 +0530 > > > > > > > ? ? ? ?Subject: Re: [Tutor] can any one help > > ? ? ? ?To: invincible_patriot at hotmail.com > > ? ? ? ?CC: tutor at python.org > > > > > > > > > > > > > > > > ? ? ? ?Tips: > > > > ? ? ? ?1. > > ? ? ? ?range can be stepped down in reverse order > > ? ? ? ?ex -> > > ? ? ? ?>>> range(10, 1, -2) > > ? ? ? ?[10, 8, 6, 4, 2] > > > > ? ? ? ?2. > > ? ? ? ?you can directly get chars of string. > > ? ? ? ?ex -> > > ? ? ? ?>>> [i for i in 'foobar'] > > ? ? ? ?['f', 'o', 'o', 'b', 'a', 'r'] > > ? ? ? ?also > > ? ? ? ?>>> 2 * 'f' > > ? ? ? ?'ff' > > > > > > > > > > ? ? ? ?On Sun, Jan 31, 2010 at 3:56 AM, Shashwat Anand wrote: > > > ? ? ? ? ? ?seems like homework ;) > > ? ? ? ? ? ?Can you paste your approach here ? > > > > > > > > > > > > > > > > > > ? ? ? ? ? ?On Sun, Jan 31, 2010 at 3:03 AM, invincible patriot wrote: > > > > > > > > > > > > > > > > > > > > > > > ? ? ? ? ? ? ? ?hi > > > > > > > > > ? ? ? ? ? ? ? ?i am stuck in few tasks can some one help me in that > > > > > > > > > ? ? ? ? ? ? ? ?here are first few tasks > > > > > > > > > > > > > > > > > > > > > ? ? ? ? ? ? ? ?1 > > > > > > > > > ? ? ? ? ? ? ? ?how can i print the following series, using a loop > > > > > > > > > ? ? ? ? ? ? ? ?15 > > > > > > > > > ? ? ? ? ? ? ? ?13 > > > > > > > > > ? ? ? ? ? ? ? ?11 > > > > > > > > > ? ? ? ? ? ? ? ?... > > > > > > > > > ? ? ? ? ? ? ? ?3 > > > > > > > > > ? ? ? ? ? ? ? ?1 > > > > > > > > > ? ? ? ? ? ? ? ?-1 > > > > > > > > > ? ? ? ? ? ? ? ?======== > > > > > > > > > ? ? ? ? ? ? ? ?2 > > > > > > > > > ? ? ? ? ? ? ? ?Write a small Python program that generates the list of all pairs of characters c and > > > > > > > > > ? ? ? ? ? ? ? ?its doubling 2 c, where c moves through all the letters of the string "foobar" and prints it out. > > > > > > > > > ? ? ? ? ? ? ? ?The result will look like: > > > > > > > > > ? ? ? ? ? ? ? ?[(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)] > > > > > > > > > > > > > > > > > > > > > ? ? ? ? ? ? ? ?please help me out in these two tasks > > > > > > > > > > > > > > > > > > > > > > > > > > > ? ? ? ? ? ? ? ?Hotmail: Trusted email with powerful SPAM protection. Sign up now. > > > > > > > > > > > > > > > > > > > > > ? ? ? ? ? ? ? ?_______________________________________________ > > ? ? ? ? ? ? ? ?Tutor maillist ?- ?Tutor at python.org > > ? ? ? ? ? ? ? ?To unsubscribe or change subscription options: > > ? ? ? ? ? ? ? ?http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > ? ? ? ?Hotmail: Trusted email with powerful SPAM protection. Sign up now. > > > > > > > > > > > > > > > > ? ?Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. Sign up now. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > > > def fibn(n): > > ? ? ? ?a,b=15,2 > > ? ? ? ?while a>n: > > ? ? ? ? ? ? ? ?print a, ? ? # it is same like ? ? ? ? print a, a, b = a, a+b ? ? ? ?You can not print this. SyntaxError: invalid syntax > > ? ? ? ? ? ? ? ?a,b=a,a+b > > fibn(-1) > > > > > -- > > Grigor Kolev > > > > _________________________________________________________________ > Hotmail: Powerful Free email with security by Microsoft. > http://clk.atdmt.com/GBL/go/196390710/direct/01/ > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 2 > Date: Sun, 31 Jan 2010 01:40:41 +0200 > From: Grigor Kolev > To: invincible patriot > Cc: tutor at python.org > Subject: Re: [Tutor] can any one help > Message-ID: <1264894841.6587.39.camel at dedal-laptop> > Content-Type: text/plain > > Excuse me but I have question too. > Why when i write this function in python shell not work says > SyntaxError: invalid syntax > but when I use IDLE make endless loop > Sorry I also teach Python. >> def fibn(n): >> a,b=15,2 >> while a>n: >> print a, ? ? # it is same like ? ? ? ? print a, a, b = a, a+b >> You can not print this. SyntaxError: invalid syntax >> a,b=a,a+b >> fibn(-1) > -- > Grigor Kolev > > > > ------------------------------ > > Message: 3 > Date: Sat, 30 Jan 2010 23:46:30 +0000 > From: invincible patriot > To: > Subject: [Tutor] please help me > Message-ID: > Content-Type: text/plain; charset="windows-1252" > > > hii am stuck in these questions can someone please help me in solving and writing programme for these tasks > please help me > > > > > 1 1.1 Write a Python program with a loop that prints out a sequence of numbers as follows:151311...31-1 > > 1.2 Write a small Python program that generates the list of all pairs of characters c andits doubling 2 ? c, where c moves through all the letters of the string "foobar" and prints it out.The result will look like:[(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)]Hint: use list comprehensions. > 1.3 Write a small Python program that > 1. prints out the length of the string?taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu? > 2. prints out how many different characters this string contains > 3. replaces all the non-?t? characters in above string with dots ?.?. So, if the word were?tattoo?, it would print ?t.tt..?.Hints: > (a) use a function to t-ify the string > (b) there are various ways to construct the string, either using the join method or by runninga loop accumulating substrings. > (c) check also out what happens if you apply the conversion list(s) to a string s. > 2 2.1 Write a function count char(s, c) that takes a string s, and a character c and returnshow often the character c appears in the string.For example count_char("tattoo", "t") should return 3. > > 2.2 Write a Python function char_freqency(s)that returns a dictionary which, for eachcharacter of s as a key, stores as value how often this character appears.For example, char_frequency("tattoo") could return {?a?: 1, ?t?: 3, ?o?: 2} (the order ofkey:value pairs does not matter here). > Hint: Consider using the function count_char defined in 2.1. > 2.3 Write a program that translates a given string (of arbitrary length) of DNA bases intothe RNA strand that it will produce. For this, research which DNA bases correspond to RNA basesand create a translation table (not an if...else clause!) in the Python program. [4 marks] > > > 3 > 3.1 consider the following list of base sequences:ACGTACCTTACTTACCATATCGTACCTCTTACTCATThe task consists of writing a Python program that performs a simple alignment algorithm onthese two strings and prints out this alignment in a suitable readable form. Give a brief commentexplaining the output format.Hints:1. Matching means the following: for a given sequence to be matched, your program should denotewhich bases correspond to bases in the reference sequence and which do not; in addition, markgaps where the reference sequence contains bases which are not present in the sample sequence.For a given sample sequence, your matching algorithm will attempt to match as many basesas possible to those of the reference sequence.2. This is a difficult assignment. Do not attempt it before you have solved the others.3. For this purpose, you are allowed to research and implement publicly documented versions ofthe Needleman-Wunsch algorithm or similar algorithms (however, make sure that you r > ?efer-ence them properly!). Also make sure that your program prints out the matches/mismatchesbetween the sequences. You should demonstrate at least two different alignments by usingdifferent gap penalties.Instead of following this hint, you can develop an alternative solution to the matching problem,e.g. based on the Levenshtein distance. > > > please help me > _________________________________________________________________ > Hotmail: Trusted email with Microsoft?s powerful SPAM protection. > http://clk.atdmt.com/GBL/go/196390706/direct/01/ > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 71, Issue 78 > ************************************* > From rabidpoobear at gmail.com Sun Jan 31 02:36:30 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 30 Jan 2010 19:36:30 -0600 Subject: [Tutor] can any one help In-Reply-To: <1264894841.6587.39.camel@dedal-laptop> References: <1264893675.6587.29.camel@dedal-laptop> <1264894841.6587.39.camel@dedal-laptop> Message-ID: On Sat, Jan 30, 2010 at 5:40 PM, Grigor Kolev wrote: > Excuse me but I have question too. > Why when i write this function in python shell not work says > SyntaxError: invalid syntax > but when I use IDLE make endless loop > Your tabbing is probably messed up or something. You guys both need to be a lot more clear with your questions. If it doesn't seem like you put in the effort for a proper post then you're unlikely to get a proper reply. -Luke > Sorry I also teach Python. > > def fibn(n): > > a,b=15,2 > > while a>n: > > print a, # it is same like print a, a, b = a, a+b > > You can not print this. SyntaxError: invalid syntax > > a,b=a,a+b > > fibn(-1) > -- > Grigor Kolev > > _______________________________________________ > 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 Sun Jan 31 02:39:05 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 30 Jan 2010 19:39:05 -0600 Subject: [Tutor] please help me In-Reply-To: References: <1264893675.6587.29.camel@dedal-laptop> <1264894841.6587.39.camel@dedal-laptop> Message-ID: [snip homework] > > > please help me > > This is a tutor mailing list. Tutor means we will help you learn, not that we will write your homework assignments for you for free. That is the opposite of learning. Try all of the programs. Give us what you have tried and what didn't work, why you thought it would work, why you think it didn't work, and anything else helpful (eg. if you get an error message include the whole traceback, don't paraphrase it.) In other words, if you don't have code that you've tried and a specific problem you're having, you're not going to get a reply. We're busy people, make it easy for us to help you. -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Jan 31 02:45:04 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 30 Jan 2010 19:45:04 -0600 Subject: [Tutor] Problem creating a search In-Reply-To: References: Message-ID: On Sat, Jan 30, 2010 at 4:42 PM, Shashwat Anand wrote: > > > On Sun, Jan 31, 2010 at 3:47 AM, jim serson wrote: > >> Hi I am pretty new to python and programming in general. I am trying to >> create a search that takes a user input for a file location and user input >> to find a group of numbers or a phrase in that file count how many times it >> appears then display it. >> >> I have gone through a tutorials and searched I/O to find the code I need. >> Although I have not been able to make it work properly yet. >> >> I am able to open and read from the file the user would input but cant >> seem to make the other input retrieve the numbers or phrase from the file or >> have it count how many time it appears. If anyone can help or point me in >> the right direction I would appreciate it. Thanks for your time. >> >> 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) > print c > if c: print search, "your search was found" > else: print "your search was not found" > > As Anand pointed out, in Python if you have a problem that you would think would have a common (/ simple) solution, it probably does. In this case you can just read the whole file into a string and use a string method to count the occurrences. The disadvantage is that the file is then residing completely in memory, which may not be ideal for larger files. So in that case you'll have to iterate over the file line-by-line, but you can still use the count method to determine how many times an item occurs in each line. For example you could easily do something like this: infile = raw_input("Input file: ") search = raw_input("search term: ") count = 0 for line in infile: count += line.count(search) The key here is the "for line in infile" will not keep the whole file in memory (at least I don't think it will, I believe that it's a generator so it's yielding each line). It probably will run more slowly than Anand's solution, though. Depends on your requirements. Good luck with Python and hopefully we can help you with any other stumbling blocks you might encounter while learning this wonderful language :) -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 31 10:26:19 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Jan 2010 09:26:19 -0000 Subject: [Tutor] Future of Python Programmers References: Message-ID: "nikunj badjatya" wrote > I have one important question to ask to all of you, > I am a fresher, recently completed my graduation, had started working on > python 2 months back..!! and I just fell in love with the language. > The only concern is there arent enough companies which work on Python. How many companies do you need? One is enough if you fork for that one... > Is there any chance where the development of Python will make it as fast > as > C++ or JAVA, (or it is at its optimum level? ) . No, just as there is no chance that Java will ever be as fast as C++ or C++ as fast as C or C as fast as assembler. You can construct test cases where they approach each other but raw speed is related to how close you can get to the machine. The trade off is that raw speed requires guru level skill and a lot of development time. So if you measure speed in terms of productivity Python is already faster than Java! But your concerms are misplaced. All programming languages (except perhaps COBOL and FORTRAN) come and go. When I left university (mid 1980's) everyone was using Pascal and C. ADA and Prolog were the forecast kings of the block and a few people were playing with Smalltalk.Then Windows came out and C++ suddenly took over. Then it was Java.Then scripting languages became poular. I don;t know what we will be using in 20 years time but it probavbly won't be Java or C++ or even Python.Get used to it, as a professional you will learn and use many languages (I know over 20 that I've used in real projects, and probavbly another dozen that I studied just for the knowledge they gave). Languages are just not that important. Stop fiocussing on languages, start to focus on the deeper fundamentals of programming. Design, architecture, state, data structures, logic coupling, cohesion, concurrency etc These things do not change. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From invincible_patriot at hotmail.com Sun Jan 31 11:03:29 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Sun, 31 Jan 2010 10:03:29 +0000 Subject: [Tutor] can any one help In-Reply-To: References: , , , , <1264893675.6587.29.camel@dedal-laptop>, <1264894841.6587.39.camel@dedal-laptop>, Message-ID: please check the questions below. 1 1.1 Write a Python program with a loop that prints out a sequence of numbers as follows:151311...31-1 1.2 Write a small Python program that generates the list of all pairs of characters c andits doubling 2  c, where c moves through all the letters of the string "foobar" and prints it out.The result will look like:[(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)]Hint: use list comprehensions. 1.3 Write a small Python program that 1. prints out the length of the string?taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu? 2. prints out how many different characters this string contains 3. replaces all the non-?t? characters in above string with dots ?.?. So, if the word were?tattoo?, it would print ?t.tt..?.Hints: (a) use a function to t-ify the string (b) there are various ways to construct the string, either using the join method or by runninga loop accumulating substrings. (c) check also out what happens if you apply the conversion list(s) to a string s. 2 2.1 Write a function count char(s, c) that takes a string s, and a character c and returnshow often the character c appears in the string.For example count_char("tattoo", "t") should return 3. 2.2 Write a Python function char_freqency(s)that returns a dictionary which, for eachcharacter of s as a key, stores as value how often this character appears.For example, char_frequency("tattoo") could return {?a?: 1, ?t?: 3, ?o?: 2} (the order ofkey:value pairs does not matter here). Hint: Consider using the function count_char defined in 2.1. 2.3 Write a program that translates a given string (of arbitrary length) of DNA bases intothe RNA strand that it will produce. For this, research which DNA bases correspond to RNA basesand create a translation table (not an if...else clause!) in the Python program. [4 marks] 3 3.1 consider the following list of base sequences:ACGTACCTTACTTACCATATCGTACCTCTTACTCATThe task consists of writing a Python program that performs a simple alignment algorithm onthese two strings and prints out this alignment in a suitable readable form. Give a brief commentexplaining the output format.Hints:1. Matching means the following: for a given sequence to be matched, your program should denotewhich bases correspond to bases in the reference sequence and which do not; in addition, markgaps where the reference sequence contains bases which are not present in the sample sequence.For a given sample sequence, your matching algorithm will attempt to match as many basesas possible to those of the reference sequence.2. This is a difficult assignment. Do not attempt it before you have solved the others.3. For this purpose, you are allowed to research and implement publicly documented versions ofthe Needleman-Wunsch algorithm or similar algorithms (however, make sure that you refer-ence them properly!). Also make sure that your program prints out the matches/mismatchesbetween the sequences. You should demonstrate at least two different alignments by usingdifferent gap penalties.Instead of following this hint, you can develop an alternative solution to the matching problem,e.g. based on the Levenshtein distance. please help me From: rabidpoobear at gmail.com Date: Sat, 30 Jan 2010 19:36:30 -0600 Subject: Re: [Tutor] can any one help To: grigor.kolev at gmail.com CC: invincible_patriot at hotmail.com; tutor at python.org On Sat, Jan 30, 2010 at 5:40 PM, Grigor Kolev wrote: Excuse me but I have question too. Why when i write this function in python shell not work says SyntaxError: invalid syntax but when I use IDLE make endless loop Your tabbing is probably messed up or something. You guys both need to be a lot more clear with your questions. If it doesn't seem like you put in the effort for a proper post then you're unlikely to get a proper reply. -Luke Sorry I also teach Python. > def fibn(n): > a,b=15,2 > while a>n: > print a, # it is same like print a, a, b = a, a+b > You can not print this. SyntaxError: invalid syntax > a,b=a,a+b > fibn(-1) -- Grigor Kolev _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. http://clk.atdmt.com/GBL/go/196390709/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sun Jan 31 13:09:54 2010 From: denis.spir at free.fr (spir) Date: Sun, 31 Jan 2010 13:09:54 +0100 Subject: [Tutor] Problem creating a search In-Reply-To: References: Message-ID: <20100131130954.14a90569@o> On Sat, 30 Jan 2010 19:45:04 -0600 Luke Paireepinart wrote: > The key here is the "for line in infile" will not keep the whole file in > memory ... provided the file is structured in lines. (Also, the searched term should not be nore hold a newline). Denis ________________________________ la vita e estrany http://spir.wikidot.com/ From beachkid at insightbb.com Sun Jan 31 16:40:37 2010 From: beachkid at insightbb.com (Ken G.) Date: Sun, 31 Jan 2010 10:40:37 -0500 Subject: [Tutor] Future Appointments... Message-ID: <4B65A475.9050402@insightbb.com> Below is a program to determine when my next appointment is. Line numbers are provided for reference only. 01 import time, datetime, sys 02 from datetime import date 03 today = date.today() 04 print 05 print "Today date is:", today 06 todaystr = str(today) 07 print 08 print "Corrected date format is:", 09 print todaystr[ 5: 7], todaystr[ 8:10], todaystr[ 0: 4] 10 print 11 future = raw_input("Next appointment is in how many days? "), 12 print 13 difference1 = datetime.timedelta(days=1) 14 datestring = str(today + difference1) 15 print "Next appointment after that is:",datestring 16 print 17 print "Corrected date format for next appointment is:", 18 print datestring[ 5: 7], datestring[ 8:10], datestring[ 0: 4] 19 sys.exit() In answering the question in line 11 as to when is my next appointment, I would answer "3" (for 2/3/2010) but how do I change "days=1" at end of line 13 to "days=3" so that datestring would read "2010-02-03" instead of "2010-02-01" as presented above? TIA, Ken From beachkid at insightbb.com Sun Jan 31 16:46:24 2010 From: beachkid at insightbb.com (Ken G.) Date: Sun, 31 Jan 2010 10:46:24 -0500 Subject: [Tutor] Complied Python program... Message-ID: <4B65A5D0.4060802@insightbb.com> In using Geany, I have the ability to complied a Python program. For example, I can complied "program.py" to program.pyc." What is the purpose of a complied Python program? Can it be transported to another computer without Python installed as run as it is? For example, use "run program.pyc" in Windows? Currently, I am using Ubuntu 9.04, a Linux OS. TIA, Ken From amonroe at columbus.rr.com Sun Jan 31 17:01:19 2010 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 31 Jan 2010 11:01:19 -0500 Subject: [Tutor] can any one help In-Reply-To: References: , , , , <1264893675.6587.29.camel@dedal-laptop>, <1264894841.6587.39.camel@dedal-laptop>, Message-ID: <4681047264.20100131110119@columbus.rr.com> > 1 1.1 Write a Python program with a loop that prints out a sequence > of numbers as follows:15 13 11...3 1 -1 Hint 1: Learn about FOR loops. Hint 2: Learn about the RANGE command. Hint 3: Show us some code you have written. Even if yours doesn't work, we can probably spot WHY it doesn't work. Alan From bermanrl at cfl.rr.com Sun Jan 31 17:15:26 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 31 Jan 2010 11:15:26 -0500 Subject: [Tutor] can any one help In-Reply-To: References: , , , , <1264893675.6587.29.camel@dedal-laptop>, <1264894841.6587.39.camel@dedal-laptop>, Message-ID: <018901caa290$99759250$cc60b6f0$@rr.com> Grigor Kolev From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor-bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of invincible patriot Sent: Sunday, January 31, 2010 5:03 AM To: rabidpoobear at gmail.com; grigor.kolev at gmail.com Cc: tutor at python.org Subject: Re: [Tutor] can any one help please check the questions below. 1 ?1.1 Write a Python program with a loop that prints out a sequence of numbers as follows: 15 13 11 ... 3 1 -1 1.2 Write a small Python program that generates the list of all pairs of characters c and its doubling 2  c, where c moves through all the letters of the string "foobar" and prints it out. The result will look like: [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)] Hint: use list comprehensions......... ................. What possible reason would you have for expecting anyone n this group to do your school work for you? If you really want help, show us the status of your current scripts and quote us the errors you are receiving. Good luck, Robert From sander.sweers at gmail.com Sun Jan 31 17:17:21 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 31 Jan 2010 17:17:21 +0100 Subject: [Tutor] Future Appointments... In-Reply-To: <4B65A475.9050402@insightbb.com> References: <4B65A475.9050402@insightbb.com> Message-ID: On 31 January 2010 16:40, Ken G. wrote: > Below is a program to determine when my next appointment is. ?Line numbers > are provided for reference only. > > 01 ?import time, datetime, sys > 02 ?from datetime import date > 03 ?today = date.today() > 04 ?print > 05 ?print "Today date is:", today > 06 ?todaystr = str(today) You should use today.strftime(), see [1] for the format. > 07 ?print > 08 ?print "Corrected date format is:", > 09 ?print todaystr[ 5: 7], todaystr[ 8:10], todaystr[ 0: 4] The above then would be. today.strftime('%Y-%m-%d'). > 10 ?print > 11 ?future = raw_input("Next appointment is in how many days? ?"), This will give a string which will need to be converted to a int. You can do this with int(future). For example d = int(future). But this might fail if future is a string like b, $ or other non number string. You can catch the error, see [2] how to do this. > 12 ?print > 13 ?difference1 = datetime.timedelta(days=1) When you converted future to an int variable d replace days=1 with days=d. > 14 ?datestring = str(today + difference1) You can use strftime() above. > 15 ?print "Next appointment after that is:",datestring > 16 ?print > 17 ?print "Corrected date format for next appointment is:", > 18 ?print datestring[ 5: 7], datestring[ 8:10], datestring[ 0: 4] Again, strftime() can be used. > 19 ?sys.exit() > > In answering the question in line 11 as to when is my next appointment, I > would answer "3" (for 2/3/2010) but how do I change "days=1" at end of line > 13 to "days=3" so that datestring would read "2010-02-03" instead of > "2010-02-01" as presented above? See comments inline also. You will need to convert your raw_input result future to a number with "int()" and store it in a new variable wich can be used in datetime.timedelta(). Greets Sander [1] http://docs.python.org/library/time.html#time.strftime [2] http://docs.python.org/tutorial/errors.html From waynejwerner at gmail.com Sun Jan 31 17:20:37 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 31 Jan 2010 10:20:37 -0600 Subject: [Tutor] Complied Python program... In-Reply-To: <4B65A5D0.4060802@insightbb.com> References: <4B65A5D0.4060802@insightbb.com> Message-ID: <333efb451001310820y617f4c13haea47e083a1ce8ea@mail.gmail.com> On Sun, Jan 31, 2010 at 9:46 AM, Ken G. wrote: > In using Geany, I have the ability to complied a Python program. For > example, I can complied "program.py" to program.pyc." > > What is the purpose of a complied Python program? Can it be transported to > another computer without Python installed as run as it is? For example, use > "run program.pyc" in Windows? Currently, I am using Ubuntu 9.04, a Linux > OS. > As far as I know - it speeds up loading time slightly, and no. When you say "import foo" it first looks for the .pyc file in the local directory, then the path. It will also look for the .py file if it can't find a .pyc. http://www.python.org/doc/1.5.1p1/tut/node43.html HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 31 17:31:13 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 31 Jan 2010 16:31:13 +0000 (GMT) Subject: [Tutor] Fw: Future of Python Programmers In-Reply-To: References: Message-ID: <535882.51420.qm@web86708.mail.ird.yahoo.com> Forwarding since I assume this was meant to go to either the list or the OP, rather than just me... Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ > >----- Forwarded Message ---- >From: Samuel de Champlain >To: Alan Gauld >Sent: Sunday, 31 January, 2010 14:40:36 >Subject: Re: [Tutor] Future of Python Programmers > >In order to get faster programs, you have to become more machine specific. If you want your program to work on several machines, you must include more code for each possible machine architecture. Python and java try to realise the old dream of coding once and running everywhere, therefore they have to be slower in execution, but with the speed of modern machines, this becomes less important. >>However, they are fantastic rad (rapid application development) languages. Time to market and therefore cost is greatly reduced and that is the main reason they are widely used. Try debugging c and you will learn to appreciate garbage collectors and the lack of pointer headaches in python. >>But that is just one person's opinion. > > >On Sun, Jan 31, 2010 at 4:26 AM, Alan Gauld wrote: > > >>>>"nikunj badjatya" wrote >> >> >>>>>I have one important question to ask to all of you, >>>>>>I am a fresher, recently completed my graduation, had started working on >>>>>>python 2 months back..!! and I just fell in love with the language. >>>>>>The only concern is there arent enough companies which work on Python. >>> >>>>How many companies do you need? >>>>One is enough if you fork for that one... >> >> >>>>>Is there any chance where the development of Python will make it as fast as >>>>>>C++ or JAVA, (or it is at its optimum level? ) . >>> >>>>No, just as there is no chance that Java will ever be as fast >>>>as C++ or C++ as fast as C or C as fast as assembler. >>>>You can construct test cases where they approach each other >>>>but raw speed is related to how close you can get to the machine. >>>>The trade off is that raw speed requires guru level skill and a lot of >>>>development time. So if you measure speed in terms of productivity >>>>Python is already faster than Java! >> >>>>But your concerms are misplaced. >>>>All programming languages (except perhaps COBOL and FORTRAN) >>>>come and go. When I left university (mid 1980's) everyone was using >>>>Pascal and C. ADA and Prolog were the forecast kings of the block >>>>and a few people were playing with Smalltalk.Then Windows came out >>>>and C++ suddenly took over. Then it was Java.Then scripting languages >>>>became poular. I don;t know what we will be using in 20 years time but >>>>it probavbly won't be Java or C++ or even Python.Get used to it, as a >>>>professional you will learn and use many languages (I know over 20 that >>>>I've used in real projects, and probavbly another dozen that I studied >>>>just for the knowledge they gave). Languages are just not that important. >> >>>>Stop fiocussing on languages, start to focus on the deeper >>>>fundamentals of programming. Design, architecture, state, data >>>>structures, logic coupling, cohesion, concurrency etc >>>>These things do not change. >> >>>>-- >>>>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 alan.gauld at btinternet.com Sun Jan 31 17:46:49 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Jan 2010 16:46:49 -0000 Subject: [Tutor] Complied Python program... References: <4B65A5D0.4060802@insightbb.com> Message-ID: "Ken G." wrote > In using Geany, I have the ability to complied a Python program. For > example, I can complied "program.py" to program.pyc." You compile (note spelling) a python script everytime you import it (if it has not already been compiled). If you compile a new(or changed) script Python first compiles the source text into an intermediate version called byte code (sometimes called p-code) that the interpreter can understand and execute. It saves the byte-code as a .pyc file so that in future it can import the compiled version directly (if there is no newer .py file). This byte-code is similar to what Java produces when you comile jave into a class file. The Jave runtime engine is basically an interpreter for Java byte-code. .Net code follows a similar approach too. > What is the purpose of a complied Python program? Can it be transported > to another computer without Python installed as run as it is? No, it needs Python to run it but it can be transported without the .py file existing - which gives a minimal amount of code hiding and a marginal startup advantage the first time you run it. Its not usually worth it IMHO. You can see the p-code if you use the dis module. The docs give this example: >>> def myfunc(alist): ... return len(alist) ...>>> dis.dis(myfunc) 2 0 LOAD_GLOBAL 0 (len) 3 LOAD_FAST 0 (alist) 6 CALL_FUNCTION 1 9 RETURN_VALUE The bytecode : 0,0,3,0,6,1,9 is more compact but much more primitive than the original source text. It is similasr in character to a machine code program but is machine independant.Thus it is said to run on a virtual machine - the Python interpreter.HTH,-- Alan GauldAuthor of the Learn to Program web sitehttp://www.alan-g.me.uk/ From samueldechamplain at gmail.com Sun Jan 31 18:03:39 2010 From: samueldechamplain at gmail.com (Samuel de Champlain) Date: Sun, 31 Jan 2010 12:03:39 -0500 Subject: [Tutor] python and sqlite Message-ID: <10cd5a2c1001310903t259967bfh5420c2331ca72291@mail.gmail.com> 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. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Jan 31 18:28:38 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 31 Jan 2010 11:28:38 -0600 Subject: [Tutor] please help me In-Reply-To: References: <1264893675.6587.29.camel@dedal-laptop> <1264894841.6587.39.camel@dedal-laptop> Message-ID: Please reply on-list unless you really need to speak to me off-list. Use "reply-all" to reply to everyone. Tutor doesn't work in that you get one of us as a tutor and we help you with every problem you have. For this mailing list you e-mail us a specific problem and everyone collaborates to guide you through it. When we say "specific problem" we mean "you have coded a solution that looks to you like it would work but it doesn't and you're stuck" and then we'll help you figure out why you're stuck and what you need to do to fix the program. (P.S. Sorry for the top-post, I'm not sure how to reply in-line to a forwarded message.) ---------- Forwarded message ---------- From: invincible patriot Date: Sun, Jan 31, 2010 at 4:05 AM Subject: RE: [Tutor] please help me To: rabidpoobear at gmail.com m sorry but i am not asking u to solve these for me rather i send all the questions to u just to let u know what i want to do n now i m looking froward for ur guidance so that i can write programme for thhem i think itz fair enough to ask what should i do, but i am not asking u to solve them for me m just looking forward for some help ------------------------------ From: rabidpoobear at gmail.com Date: Sat, 30 Jan 2010 19:39:05 -0600 Subject: Re: [Tutor] please help me To: invincible_patriot at hotmail.com CC: tutor at python.org [snip homework] please help me This is a tutor mailing list. Tutor means we will help you learn, not that we will write your homework assignments for you for free. That is the opposite of learning. Try all of the programs. Give us what you have tried and what didn't work, why you thought it would work, why you think it didn't work, and anything else helpful (eg. if you get an error message include the whole traceback, don't paraphrase it.) In other words, if you don't have code that you've tried and a specific problem you're having, you're not going to get a reply. We're busy people, make it easy for us to help you. -Luke ------------------------------ Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. Sign up now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Jan 31 19:18:48 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 31 Jan 2010 12:18:48 -0600 Subject: [Tutor] python and sqlite In-Reply-To: <10cd5a2c1001310903t259967bfh5420c2331ca72291@mail.gmail.com> References: <10cd5a2c1001310903t259967bfh5420c2331ca72291@mail.gmail.com> Message-ID: Yes, it works fine with sqlite. I've seen very large projects use it just fine. I'd recommend googling "pysqlite" or something similar. -Luke 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 cfuller084 at thinkingplanet.net Sun Jan 31 20:00:34 2010 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sun, 31 Jan 2010 13:00:34 -0600 Subject: [Tutor] python and sqlite In-Reply-To: <10cd5a2c1001310903t259967bfh5420c2331ca72291@mail.gmail.com> References: <10cd5a2c1001310903t259967bfh5420c2331ca72291@mail.gmail.com> Message-ID: <201001311300.34828.cfuller084@thinkingplanet.net> Since v2.5, SQLite is included in the Standard Library. You can get docs at the Python website, or in the handy chm that comes with the Windows distribution. Cheers On Sunday 31 January 2010, Samuel de Champlain 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. > From daverwebb at bellsouth.net Sun Jan 31 20:33:27 2010 From: daverwebb at bellsouth.net (Woodwerks) Date: Sun, 31 Jan 2010 13:33:27 -0600 Subject: [Tutor] kudos to alan Message-ID: <4B65DB07.6080904@bellsouth.net> Message: 4 Date: Sun, 31 Jan 2010 11:01:19 -0500 From: "R. Alan Monroe" To:tutor at python.org Subject: Re: [Tutor] can any one help Message-ID:<4681047264.20100131110119 at columbus.rr.com> Content-Type: text/plain; charset=us-ascii I think the way you give hints and ideas about how to accomplish something in Python is excellent. I sometimes work through these problems just to build skills. I know it would be easy for you to provide a built solution, but this exercises the brain in a much better way. Kudos, Alan. > > 1 1.1 Write a Python program with a loop that prints out a sequence > > of numbers as follows:15 13 11...3 1 -1 > Hint 1: Learn about FOR loops. Hint 2: Learn about the RANGE command. Hint 3: Show us some code you have written. Even if yours doesn't work, we can probably spot WHY it doesn't work. Alan From bermanrl at cfl.rr.com Sun Jan 31 20:34:30 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 31 Jan 2010 14:34:30 -0500 Subject: [Tutor] Future Appointments... In-Reply-To: <4B65A475.9050402@insightbb.com> References: <4B65A475.9050402@insightbb.com> Message-ID: <01ab01caa2ac$68d821f0$3a8865d0$@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: Sunday, January 31, 2010 10:41 AM To: tutor at python.org Subject: [Tutor] Future Appointments... Below is a program to determine when my next appointment is. Line numbers are provided for reference only. 01 import time, datetime, sys 02 from datetime import date 03 today = date.today() 04 print 05 print "Today date is:", today 06 todaystr = str(today) 07 print 08 print "Corrected date format is:", 09 print todaystr[ 5: 7], todaystr[ 8:10], todaystr[ 0: 4] 10 print 11 future = raw_input("Next appointment is in how many days? "), 12 print 13 difference1 = datetime.timedelta(days=1) 14 datestring = str(today + difference1) 15 print "Next appointment after that is:",datestring 16 print 17 print "Corrected date format for next appointment is:", 18 print datestring[ 5: 7], datestring[ 8:10], datestring[ 0: 4] 19 sys.exit() In answering the question in line 11 as to when is my next appointment, I would answer "3" (for 2/3/2010) but how do I change "days=1" at end of line 13 to "days=3" so that datestring would read "2010-02-03" instead of "2010-02-01" as presented above? TIA, Ken ***************************************************************** Hi Ken, I slightly altered your program. I think this is what you asked for. It will work for n number of days; for example, 1, 10, 45, 118, 412 work nicely. See code here: http://pastebin.com/m6e78d3ce Robert From dwightdhutto at yahoo.com Sun Jan 31 20:58:17 2010 From: dwightdhutto at yahoo.com (David Hutto) Date: Sun, 31 Jan 2010 11:58:17 -0800 (PST) Subject: [Tutor] kudos to alan In-Reply-To: <4B65DB07.6080904@bellsouth.net> Message-ID: <903803.75117.qm@web45304.mail.sp1.yahoo.com> --- On Sun, 1/31/10, Woodwerks wrote: From: Woodwerks Subject: [Tutor] kudos to alan To: tutor at python.org Date: Sunday, January 31, 2010, 2:33 PM Message: 4 Date: Sun, 31 Jan 2010 11:01:19 -0500 From: "R. Alan Monroe" To:tutor at python.org Subject: Re: [Tutor] can any one help Message-ID:<4681047264.20100131110119 at columbus.rr.com> Content-Type: text/plain; charset=us-ascii I think the way you give hints and ideas about how to accomplish something in Python is excellent. I sometimes work through these problems just to build skills. I know it would be easy for you to provide a built solution, but this exercises the brain in a much better way. Kudos, Alan. > >? 1 1.1 Write a Python program with a loop that prints out a sequence > >? of numbers as follows:15 13 11...3 1 -1 >? ? Hint 1: Learn about FOR loops. Hint 2: Learn about the RANGE command. Hint 3: Show us some code you have written. Even if yours doesn't work, we can probably spot WHY it doesn't work. Alan _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor I'll second the motion. -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at pythontoo.com Sun Jan 31 21:31:17 2010 From: david at pythontoo.com (David Abbott) Date: Sun, 31 Jan 2010 15:31:17 -0500 Subject: [Tutor] kudos to alan In-Reply-To: <903803.75117.qm@web45304.mail.sp1.yahoo.com> References: <903803.75117.qm@web45304.mail.sp1.yahoo.com> Message-ID: <1264969877.8709.15.camel@opteron.dwabbott.com> On Sun, 2010-01-31 at 11:58 -0800, David Hutto wrote: > > > --- On Sun, 1/31/10, Woodwerks wrote: > > > > > I think the way you give hints and ideas about how to > accomplish something in Python is excellent. I sometimes work > through these problems just to build skills. I know it would > be easy for you to provide a built solution, but this > exercises the brain in a much better way. Kudos, Alan. > > > > > I'll second the motion. > > + 3 -- David Abbott From anand.shashwat at gmail.com Sun Jan 31 21:49:06 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 1 Feb 2010 02:19:06 +0530 Subject: [Tutor] kudos to alan In-Reply-To: <1264969877.8709.15.camel@opteron.dwabbott.com> References: <903803.75117.qm@web45304.mail.sp1.yahoo.com> <1264969877.8709.15.camel@opteron.dwabbott.com> Message-ID: +1 On Mon, Feb 1, 2010 at 2:01 AM, David Abbott wrote: > On Sun, 2010-01-31 at 11:58 -0800, David Hutto wrote: > > > > > > --- On Sun, 1/31/10, Woodwerks wrote: > > > > > > > > > > I think the way you give hints and ideas about how to > > accomplish something in Python is excellent. I sometimes work > > through these problems just to build skills. I know it would > > be easy for you to provide a built solution, but this > > exercises the brain in a much better way. Kudos, Alan. > > > > > > > > > > I'll second the motion. > > > > > > + 3 > -- > David Abbott > > _______________________________________________ > 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 invincible_patriot at hotmail.com Sun Jan 31 22:21:09 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Sun, 31 Jan 2010 21:21:09 +0000 Subject: [Tutor] query In-Reply-To: References: <903803.75117.qm@web45304.mail.sp1.yahoo.com>, <1264969877.8709.15.camel@opteron.dwabbott.com>, Message-ID: 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. http://clk.atdmt.com/GBL/go/196390708/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkid at insightbb.com Sun Jan 31 22:23:13 2010 From: beachkid at insightbb.com (Ken G.) Date: Sun, 31 Jan 2010 16:23:13 -0500 Subject: [Tutor] Future Appointments... In-Reply-To: <01ab01caa2ac$68d821f0$3a8865d0$@rr.com> References: <4B65A475.9050402@insightbb.com> <01ab01caa2ac$68d821f0$3a8865d0$@rr.com> Message-ID: <4B65F4C1.9080103@insightbb.com> Sorry, I forgot to hit Reply All. > That is so cool! My first look at 'pastebin.' THANKS! > > I already finished the code up several hours ago. If I can figure out > how to post it there. > Ken 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 Ken G. > Sent: Sunday, January 31, 2010 10:41 AM > To: tutor at python.org > Subject: [Tutor] Future Appointments... > > Below is a program to determine when my next appointment is. Line > numbers are provided for reference only. > > 01 import time, datetime, sys > 02 from datetime import date > 03 today = date.today() > 04 print > 05 print "Today date is:", today > 06 todaystr = str(today) > 07 print > 08 print "Corrected date format is:", > 09 print todaystr[ 5: 7], todaystr[ 8:10], todaystr[ 0: 4] > 10 print > 11 future = raw_input("Next appointment is in how many days? "), > 12 print > 13 difference1 = datetime.timedelta(days=1) > 14 datestring = str(today + difference1) > 15 print "Next appointment after that is:",datestring > 16 print > 17 print "Corrected date format for next appointment is:", > 18 print datestring[ 5: 7], datestring[ 8:10], datestring[ 0: 4] > 19 sys.exit() > > In answering the question in line 11 as to when is my next appointment, > I would answer "3" (for 2/3/2010) but how do I change "days=1" at end of > line 13 to "days=3" so that datestring would read "2010-02-03" instead > of "2010-02-01" as presented above? > > TIA, > > Ken > ***************************************************************** > > Hi Ken, > > I slightly altered your program. I think this is what you asked for. It will > work for n number of days; for example, 1, 10, 45, 118, 412 work nicely. > > See code here: http://pastebin.com/m6e78d3ce > > Robert > > > From invincible_patriot at hotmail.com Sun Jan 31 22:27:26 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Sun, 31 Jan 2010 21:27:26 +0000 Subject: [Tutor] can any one help In-Reply-To: <4681047264.20100131110119@columbus.rr.com> References: , , , , , , , , , , , <1264893675.6587.29.camel@dedal-laptop>, , , <1264894841.6587.39.camel@dedal-laptop>, , , , <4681047264.20100131110119@columbus.rr.com> Message-ID: 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 thanks Write a small Python program that generates the list of all pairs of characters c and its doubling 2  c, where c moves through all the letters of the string "foobar" and prints it out. The result will look like: [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, ?rr?)] 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 a='foobar' b=list(a) print b ['f','o','o','b','a','r'] c=len(b) 6 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 > Date: Sun, 31 Jan 2010 11:01:19 -0500 > From: amonroe at columbus.rr.com > To: tutor at python.org > Subject: Re: [Tutor] can any one help > > > > 1 1.1 Write a Python program with a loop that prints out a sequence > > of numbers as follows:15 13 11...3 1 -1 > > Hint 1: Learn about FOR loops. > > Hint 2: Learn about the RANGE command. > > Hint 3: Show us some code you have written. Even if yours doesn't > work, we can probably spot WHY it doesn't work. > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. http://clk.atdmt.com/GBL/go/196390707/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sun Jan 31 22:33:16 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 31 Jan 2010 22:33:16 +0100 Subject: [Tutor] query In-Reply-To: References: <903803.75117.qm@web45304.mail.sp1.yahoo.com> <1264969877.8709.15.camel@opteron.dwabbott.com> Message-ID: On 31 January 2010 22:21, invincible patriot wrote: > 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 Look at http://diveintopython.org/getting_to_know_python/lists.html. Greets Sander From dwshort408 at gmail.com Sun Jan 31 22:44:34 2010 From: dwshort408 at gmail.com (Darren Short) Date: Sun, 31 Jan 2010 13:44:34 -0800 Subject: [Tutor] kudos to alan In-Reply-To: References: <903803.75117.qm@web45304.mail.sp1.yahoo.com> <1264969877.8709.15.camel@opteron.dwabbott.com> Message-ID: <8193ef041001311344oe15d6a3xf89c2db0dfd6341@mail.gmail.com> +1 Agreed. Why "do" python if you can't take the time to learn it. One must put in the work, or at least show what work has been done when not being able to reach a solution just quite yet. On Sun, Jan 31, 2010 at 12:49 PM, Shashwat Anand wrote: > +1 > > On Mon, Feb 1, 2010 at 2:01 AM, David Abbott wrote: > >> On Sun, 2010-01-31 at 11:58 -0800, David Hutto wrote: >> > >> > >> > --- On Sun, 1/31/10, Woodwerks wrote: >> > >> > >> > >> > >> > I think the way you give hints and ideas about how to >> > accomplish something in Python is excellent. I sometimes work >> > through these problems just to build skills. I know it would >> > be easy for you to provide a built solution, but this >> > exercises the brain in a much better way. Kudos, Alan. >> > >> > >> > >> > >> > I'll second the motion. >> > >> > >> >> + 3 >> -- >> David Abbott >> >> _______________________________________________ >> 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 grigor.kolev at gmail.com Sun Jan 31 22:49:58 2010 From: grigor.kolev at gmail.com (Grigor Kolev) Date: Sun, 31 Jan 2010 23:49:58 +0200 Subject: [Tutor] query In-Reply-To: References: <903803.75117.qm@web45304.mail.sp1.yahoo.com> , <1264969877.8709.15.camel@opteron.dwabbott.com> , Message-ID: <1264974598.17460.9.camel@dedal-laptop> ? 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 From invincible_patriot at hotmail.com Sun Jan 31 23:09:46 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Sun, 31 Jan 2010 22:09:46 +0000 Subject: [Tutor] query In-Reply-To: <1264974598.17460.9.camel@dedal-laptop> References: <903803.75117.qm@web45304.mail.sp1.yahoo.com>,, <1264969877.8709.15.camel@opteron.dwabbott.com>,, , , <1264974598.17460.9.camel@dedal-laptop> Message-ID: 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. http://clk.atdmt.com/GBL/go/196390708/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Jan 31 23:21:53 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 31 Jan 2010 16:21:53 -0600 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: On Sun, Jan 31, 2010 at 3:27 PM, invincible patriot < invincible_patriot at hotmail.com> 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 > > thanks > > Write a small Python program that generates the list of all pairs of > characters c and > its doubling 2 c, where c moves through all the letters of the string > "foobar" and prints it out. > The result will look like: > [(?f?, ?ff?), (?o?, ?oo?), (?o?, ?oo?), (?b?, ?bb?), (?a?, ?aa?), (?r?, > ?rr?)] > > 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 > > a='foobar' > b=list(a) > print b > > ['f','o','o','b','a','r'] > > c=len(b) > 6 > > > 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 > > See now that you have provided us with what you've tried we can help you a little more. How do you think you should do the multiplication? You mentioned a 'for loop' but you didn't actually try using one in your code. Also one hint, strings can be used directly in this situation. as an example, a = 'foobar' len(a) 6 You don't actually have to convert it to a list before iterating over it. -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: