From ramit.prasad at jpmorgan.com Thu Sep 1 00:41:04 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 31 Aug 2011 18:41:04 -0400 Subject: [Tutor] Quote of the Day version 1.0 In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F164EFC4C@EMARC112VS01.exchad.jpmchase.net> [snip] > Do not hesitate to ask questions as I added tuple unpacking and string >formatting which you might not have covered in depth yet in your >tutorial. [snip] >author, quote = random.choice(quotes) >print "%s\n\tBy %s" % (quote, author) I figured I might as well add my preferred method of string formatting. :) print 'The quote "{0}" is by {1}. I {2} {1}'.format(quote, author, 'love') # although you might hate {1} ;) Ramit P.S. Notice the mixed quote convention. Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From questions.anon at gmail.com Thu Sep 1 01:17:45 2011 From: questions.anon at gmail.com (questions anon) Date: Thu, 1 Sep 2011 09:17:45 +1000 Subject: [Tutor] reclassify values in an array Message-ID: Dear All, I have been going round in circles trying to solve something that sounds simple. I have a huge array and I would like to reclassify the values. Firstly just make them zeros and ones, for example if the values in the array are less than 100 make them 0 and if greater than 100 make them 1. And then finally sum them together. I have attempted a few methods, see code below. Any feedback will be greatly appreciated. Attempt 1: big_array=N.ma.concatenate(all_FFDI) for i in big_array: if i<100: i=0 elif i>=100: i=1 print big_array sum=big_array.sum(axis=0) print "the sum is", sum Attempt 2: big_array=N.ma.concatenate(all_FFDI) for i, value in enumerate(big_array): if value==100: big_array[i]=0 elif value>=100: big_array[i]=1 print big_array sum=big_array.sum(axis=0) print "the sum is", sum -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 1 01:23:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Sep 2011 00:23:02 +0100 Subject: [Tutor] Quote of the Day version 1.0 In-Reply-To: References: Message-ID: On 31/08/11 20:14, Cranky Frankie wrote: > This code works. Now I just have to figure out: > - how to associate .py files in Ubuntu to IDLE You probably don't want to do that. IDLE is fine for developing code but you don't want to run it in IDLE for general use you want to use the interpreter. And the shebang (#!) line at the start will do that for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 1 01:32:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Sep 2011 00:32:46 +0100 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: <201108312035.43801.lisi.reisz@gmail.com> References: <201108312035.43801.lisi.reisz@gmail.com> Message-ID: On 31/08/11 20:35, Lisi wrote: > ?? If either n or x or both were 0, and % were the same thing as *, the > statement would be true, but from the context I don't think that % does mean > the same as *, because * appears very soon after in the same fragment of > code. It's the remainder operator: IF N MOD X = 0 in BASIC It's explained in the Simple Sequences topic of my tutorial and mentioned again in the Raw Materials topic under integers. The use of % as the operator goes back to C. Many of Python's operators are just inherited directly from C. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 1 01:41:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Sep 2011 00:41:19 +0100 Subject: [Tutor] reclassify values in an array In-Reply-To: References: Message-ID: On 01/09/11 00:17, questions anon wrote: > Dear All, > I have been going round in circles trying to solve something that sounds > simple. I have a huge array and I would like to reclassify the values. > Firstly just make them zeros and ones,... > And then finally sum them together. And what has been the problem? > I have attempted a few methods, see code below. I'm not familiar with NumPy (which I assume is what you are using?) However the second approach looks more likely to succeed than the first. Assuming enumerate works with NumPy arrays. Is there any reason why you cannot use a normal list? Then it would just be: result = sum(1 for item in array if item >= 100) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Thu Sep 1 02:09:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 01 Sep 2011 10:09:47 +1000 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: References: <201108312035.43801.lisi.reisz@gmail.com> Message-ID: <4E5ECD4B.9010203@pearwood.info> Hugo Arts wrote: > n % y == 0 if n is divisible by y. This is useful in factoring prime > numbers If you find a way to factor *prime numbers*, you're doing something wrong. :) (By definition, a prime number has no factors apart from itself and one, which are trivial.) You mean, factorising numbers into the product of primes. -- Steven From bgailer at gmail.com Thu Sep 1 04:29:49 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 31 Aug 2011 22:29:49 -0400 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: References: <201108312035.43801.lisi.reisz@gmail.com> Message-ID: <4E5EEE1D.9000007@gmail.com> % is not remainder - it is modulo. Difference shows up when left agument is negative. -- Bob Gailer 919-636-4239 Chapel Hill NC From hugo.yoshi at gmail.com Thu Sep 1 04:29:32 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 1 Sep 2011 04:29:32 +0200 Subject: [Tutor] meaning of % in: if n % x == 0: In-Reply-To: <4E5ECD4B.9010203@pearwood.info> References: <201108312035.43801.lisi.reisz@gmail.com> <4E5ECD4B.9010203@pearwood.info> Message-ID: ah, my mistake. I was in a hurry writing that post, which is a really bad idea :/ On Thu, Sep 1, 2011 at 2:09 AM, Steven D'Aprano wrote: > Hugo Arts wrote: > >> ?n % y == 0 if n is divisible by y. This is useful in factoring prime >> numbers > > If you find a way to factor *prime numbers*, you're doing something wrong. > > :) > > (By definition, a prime number has no factors apart from itself and one, > which are trivial.) > > You mean, factorising numbers into the product of primes. > > > > -- > Steven > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From walksloud at gmail.com Thu Sep 1 07:02:32 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Wed, 31 Aug 2011 22:02:32 -0700 Subject: [Tutor] reclassify values in an array In-Reply-To: References: Message-ID: Hi anonymous questioner, Like Alan, I suspect you are using numpy as import numpy as N there is probably a numpy email list where this would be more appropriate (personally I don't object, but I don't want to speak for all the subscribers). the 2nd attempt is closer to the right answer. To help yourself answer the question, try > for i, value in enumerate(big_array): print i,value and see what you get. Are you allowed to compare value with 100? Then, when performing the sum, you are asking to sum over axis=0. I assume you are trying to sum all the individual elements, rather than sum the rows. asking to sum over axis=0 is telling numpy to treat each row as an object, and sum all those objects, preserving all other dimensions of your array. In your case, you have a 2 dimensional array, so summing over axis=0 is taking all the rows of your array (matrix) and summing them to produce a new row. Specifically, it will take the first entry of each row, and add them to make the first entry of the summed row, then likewise for each additional entry. In math language, you are doing r_j = sum_i big_array_{i,j} if you do big_array.sum() then it will sum all of the individual elements sum = sum_i sum_j big_array_{i,j} play around more with the interactive interpreter. If you try these things, and they fail, reproduce your code from the top to bottom, adding only one line at a time, and see what happens (at least for these simple short code snippets). That should help you improve your understanding faster - which I assume is one of your goals :) Andre On Aug 31, 2011, at 4:17 PM, questions anon wrote: > Dear All, > I have been going round in circles trying to solve something that sounds simple. I have a huge array and I would like to reclassify the values. Firstly just make them zeros and ones, for example if the values in the array are less than 100 make them 0 and if greater than 100 make them 1. And then finally sum them together. > I have attempted a few methods, see code below. Any feedback will be greatly appreciated. > > Attempt 1: > big_array=N.ma.concatenate(all_FFDI) > for i in big_array: > if i<100: > i=0 > elif i>=100: > i=1 > print big_array > sum=big_array.sum(axis=0) > print "the sum is", sum > > > Attempt 2: > big_array=N.ma.concatenate(all_FFDI) > for i, value in enumerate(big_array): > if value==100: > big_array[i]=0 > elif value>=100: > big_array[i]=1 > print big_array > sum=big_array.sum(axis=0) > print "the sum is", sum > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From sander.sweers at gmail.com Thu Sep 1 10:12:03 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 01 Sep 2011 10:12:03 +0200 Subject: [Tutor] reclassify values in an array In-Reply-To: References: Message-ID: <1314864723.5501.16.camel@Nokia-N900> On Thu,? 1 Sep 2011, 01:17:45 CEST, questions anon wrote: > Firstly just make them zeros and ones, for example if the values in the > array are less than 100 make them 0 and if greater than 100 make them 1. > And then finally sum them together. > I have attempted a few methods, see code below. Any feedback will be > greatly appreciated. *If* you do not need the array after you summed you can do something like below (untested!): big_array = N.ma.concatenate(all_FFDI) rusult = 0 for i in big_array: if i >= 100: result += 1 greets sander -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Sep 1 10:33:49 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Sep 2011 10:33:49 +0200 Subject: [Tutor] reclassify values in an array References: Message-ID: questions anon wrote: > I have been going round in circles trying to solve something that sounds > simple. I have a huge array and I would like to reclassify the values. > Firstly just make them zeros and ones, for example if the values in the > array are less than 100 make them 0 and if greater than 100 make them 1. > And then finally sum them together. > I have attempted a few methods, see code below. Any feedback will be > greatly appreciated. >>> import numpy >>> all_FFDI = numpy.arange(60).reshape((3,4,5)) >>> all_FFDI array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]], [[20, 21, 22, 23, 24], [25, 26, 27, 28, 29], [30, 31, 32, 33, 34], [35, 36, 37, 38, 39]], [[40, 41, 42, 43, 44], [45, 46, 47, 48, 49], [50, 51, 52, 53, 54], [55, 56, 57, 58, 59]]]) >>> all_FFDI >= 25 array([[[False, False, False, False, False], [False, False, False, False, False], [False, False, False, False, False], [False, False, False, False, False]], [[False, False, False, False, False], [ True, True, True, True, True], [ True, True, True, True, True], [ True, True, True, True, True]], [[ True, True, True, True, True], [ True, True, True, True, True], [ True, True, True, True, True], [ True, True, True, True, True]]], dtype=bool) >>> (all_FFDI >= 25).sum() 35 From lisi.reisz at gmail.com Thu Sep 1 16:30:26 2011 From: lisi.reisz at gmail.com (Lisi) Date: Thu, 1 Sep 2011 15:30:26 +0100 Subject: [Tutor] SOLVED and thank you was: Re: meaning of % in: if n % x == 0: In-Reply-To: <201108312035.43801.lisi.reisz@gmail.com> References: <201108312035.43801.lisi.reisz@gmail.com> Message-ID: <201109011530.27042.lisi.reisz@gmail.com> This was meant to go to the list. I did notrealise that it had not until I looked at the list just now and couln't see my reply. Sorry, "delegbede", and sorry list. On Wednesday 31 August 2011 Lisi wrote: > ?? If either n or x or both were 0, and % were the same thing as *, the > statement would be true, but from the context I don't think that % does > mean the same as *, because * appears very soon after in the same fragment > of code. On Wednesday 31 August 2011 20:59:05 delegbede at dudupay.com wrote: > % is a remainder division. I think its called modulo. Yes! Thank you. :-) I ought to have been able to guess that it was modulo - shows that I am indeed becoming slow-witted. :-( Thank you, all three of you, for such fast and helpful responses. Lisi From rdmoores at gmail.com Thu Sep 1 16:32:01 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 07:32:01 -0700 Subject: [Tutor] Is there a test for hashability? Message-ID: The glossary defines "hashable" as: hashable An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() method). Hashable objects which compare equal must have the same hash value. Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally. All of Python?s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id(). I'm trying to write a general test for hashability. How can I test if an object has both a __hash__() method and an __eq__() method? Thanks, Dick Moores From eire1130 at gmail.com Thu Sep 1 16:51:47 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 1 Sep 2011 10:51:47 -0400 Subject: [Tutor] Is there a test for hashability? In-Reply-To: References: Message-ID: On Thu, Sep 1, 2011 at 10:32 AM, Richard D. Moores wrote: > The glossary defines "hashable" as: > > hashable > An object is hashable if it has a hash value which never changes > during its lifetime (it needs a __hash__() method), and can be > compared to other objects (it needs an __eq__() method). Hashable > objects which compare equal must have the same hash value. > > Hashability makes an object usable as a dictionary key and a set > member, because these data structures use the hash value internally. > > > All of Python?s immutable built-in objects are hashable, while no > mutable containers (such as lists or dictionaries) are. Objects which > are instances of user-defined classes are hashable by default; they > all compare unequal, and their hash value is their id(). > > I'm trying to write a general test for hashability. How can I test if > an object has both a __hash__() method and an __eq__() method? > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > To test for a method within any object you can just go like this: >>> a = () >>> type(a) >>> if '__hash__' in dir(a): print True True >>> if '__eq__' in dir(a): print True True >>> But, I think the method you are approaching it from will only test for hashability. For example, you could do this: >>> a = [] >>> type(a) >>> if '__hash__' in dir(a): print True True >>> if '__eq__' in dir(a): print True True >>> and then do this: >>> b = [] >>> c = {b:1} Traceback (most recent call last): File "", line 1, in c = {b:1} TypeError: unhashable type: 'list' here is the dir for a list (not hashable): >>> dir(b) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] here is the dir for a tuple (hashable): >>> dir(()) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index'] What I would probably do though is use the built in method hash so you could do something like this: >>> a = 'a' >>> b = () >>> c = [] >>> print type(a), type(b), type(c) >>> print hash(a) -468864544 >>> print hash(b) 3527539 >>> print hash(c) Traceback (most recent call last): File "", line 1, in print hash(c) TypeError: unhashable type: 'list' >>> You can then use try, except to catch it on an as needed basis. Not sure if this answers the question you are asking though. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Thu Sep 1 17:28:26 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 08:28:26 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: References: Message-ID: Thanks, James, from your ideas I've come up with this function as a general test for hashibility of any object: def is_hashable(object): try: if hash(object): return True except TypeError: return False But is it? It returns True for ints, floats, sets, tuples, strings, functions; and False for lists Dick From hugo.yoshi at gmail.com Thu Sep 1 17:37:50 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 1 Sep 2011 17:37:50 +0200 Subject: [Tutor] Is there a test for hashability? In-Reply-To: References: Message-ID: On Thu, Sep 1, 2011 at 5:28 PM, Richard D. Moores wrote: > Thanks, James, from your ideas I've come up with this function as a > general test for hashibility of any object: > > def is_hashable(object): > ? ?try: > ? ? ? ?if hash(object): > ? ? ? ? ? ?return True > ? ?except TypeError: > ? ? ? ?return False > > But is it? ?It returns True for ints, floats, sets, tuples, strings, > functions; and False for lists > > Dick Are you sure? In my testing it returns False for sets, but True for frozensets as it should. From eire1130 at gmail.com Thu Sep 1 17:58:59 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 1 Sep 2011 11:58:59 -0400 Subject: [Tutor] Is there a test for hashability? In-Reply-To: References: Message-ID: On Thu, Sep 1, 2011 at 11:37 AM, Hugo Arts wrote: > On Thu, Sep 1, 2011 at 5:28 PM, Richard D. Moores > wrote: > > Thanks, James, from your ideas I've come up with this function as a > > general test for hashibility of any object: > > > > def is_hashable(object): > > try: > > if hash(object): > > return True > > except TypeError: > > return False > > > > But is it? It returns True for ints, floats, sets, tuples, strings, > > functions; and False for lists > > > > Dick > > Are you sure? In my testing it returns False for sets, but True for > frozensets as it should. > I agree with hugo, I just tested with all of these: a = 'a' b = [] c = 1 d = () e = set() f = frozenset() it gave the correct response for each a = 'a' - True b = [] - False c = 1 - True d = () - True e = set() - False f = frozenset() - True -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Thu Sep 1 20:30:55 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 1 Sep 2011 13:30:55 -0500 Subject: [Tutor] Is there a test for hashability? In-Reply-To: References: Message-ID: <201109011330.56342.cfuller084@thinkingplanet.net> On Thursday 01 September 2011, Richard D. Moores wrote: > Thanks, James, from your ideas I've come up with this function as a > general test for hashibility of any object: > > def is_hashable(object): > try: > if hash(object): > return True > except TypeError: > return False > > But is it? It returns True for ints, floats, sets, tuples, strings, > functions; and False for lists > > Dick > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You shouldn't be checking the truth value of the hash. If it's zero, this function will fall through and return None! def is_hashable(object): try: hash(object): return True except TypeError: return False Is what you want. Cheers From emile at fenx.com Thu Sep 1 21:47:40 2011 From: emile at fenx.com (Emile van Sebille) Date: Thu, 01 Sep 2011 12:47:40 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <201109011330.56342.cfuller084@thinkingplanet.net> References: <201109011330.56342.cfuller084@thinkingplanet.net> Message-ID: On 9/1/2011 11:30 AM Chris Fuller said... > On Thursday 01 September 2011, Richard D. Moores wrote: >> Thanks, James, from your ideas I've come up with this function as a >> general test for hashibility of any object: >> >> def is_hashable(object): >> try: >> if hash(object): >> return True >> except TypeError: >> return False >> >> But is it? It returns True for ints, floats, sets, tuples, strings, >> functions; and False for lists >> >> Dick >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > You shouldn't be checking the truth value of the hash. If it's zero, this > function will fall through and return None! > > def is_hashable(object): > try: > hash(object): > return True > except TypeError: > return False > > Is what you want. You should, of course, express it as valid python code though. :) def is_hashable(object): try: hash(object) return True except TypeError: return False From g.nius.ck at gmail.com Thu Sep 1 21:54:59 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 1 Sep 2011 15:54:59 -0400 Subject: [Tutor] Quote of the Day version 1.0 In-Reply-To: References: Message-ID: I would use a tuple of dictionaries. import random quotes = ( {'author':"Kahlil Gibran", 'quote':"A candle loses nothing of its light when lighting another."), #My favorite {'author':"Henrik Ibsen", 'quote':"The strongest man in the world is he who stands most alone."}) quote = random.choice(quotes) print "{quote}\n\tBy {author}".format(**quote) I use the dictionaries, because your not just storing a list of strings, your storing two strings of different purposes. I store the dictionaries in a tuple, because they are all quotes, but they currently never change during the course of the program. Some quotes have been omitted due to my laziness. I have not tested or debugged this code(I had to leave you something to do.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Thu Sep 1 22:06:58 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 13:06:58 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: References: <201109011330.56342.cfuller084@thinkingplanet.net> Message-ID: def is_hashable(object): try: hash(object) return True except TypeError: return False it is then. Thanks to all! Dick From g.nius.ck at gmail.com Thu Sep 1 22:10:53 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 1 Sep 2011 16:10:53 -0400 Subject: [Tutor] [Python-ideas] aliasing In-Reply-To: References: <6BA1535A-8DB5-425A-94B5-8AD3AFA96AEE@gmail.com> Message-ID: > > ------------------------ > >>> list = [3,] > >>> a = list > >>> list[0] = 6 > >>> a[0] > 3 > ------------------------- > Slight error in my code. It should be. ------------------------ >>> list = [3,] >>> a = list >>> list[0] = 6 >>> a[0] 6 ------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Thu Sep 1 21:29:15 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 1 Sep 2011 14:29:15 -0500 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <201109011330.56342.cfuller084@thinkingplanet.net> References: <201109011330.56342.cfuller084@thinkingplanet.net> Message-ID: <201109011429.16131.cfuller084@thinkingplanet.net> On Thursday 01 September 2011, Chris Fuller wrote: > On Thursday 01 September 2011, Richard D. Moores wrote: > > Thanks, James, from your ideas I've come up with this function as a > > general test for hashibility of any object: > > > > def is_hashable(object): > > try: > > if hash(object): > > return True > > > > except TypeError: > > return False > > > > But is it? It returns True for ints, floats, sets, tuples, strings, > > functions; and False for lists > > > > Dick > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > You shouldn't be checking the truth value of the hash. If it's zero, this > function will fall through and return None! > > def is_hashable(object): > try: > hash(object): > return True > except TypeError: > return False > > Is what you want. > > Cheers > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor *Ahem* def is_hashable(object): try: hash(object) except TypeError: return False return True From rdmoores at gmail.com Thu Sep 1 22:58:59 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 13:58:59 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <201109011429.16131.cfuller084@thinkingplanet.net> References: <201109011330.56342.cfuller084@thinkingplanet.net> <201109011429.16131.cfuller084@thinkingplanet.net> Message-ID: On Thu, Sep 1, 2011 at 12:29, Chris Fuller wrote: > *Ahem* > > def is_hashable(object): > ? try: > ? ? ? ?hash(object) > ? ?except TypeError: > ? ? ? ?return False > > ? ?return True Why is that preferred to def is_hashable(object): try: hash(object) return True except TypeError: return False ?? Dick From cfuller084 at thinkingplanet.net Fri Sep 2 00:42:02 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 1 Sep 2011 17:42:02 -0500 Subject: [Tutor] Is there a test for hashability? In-Reply-To: References: <201109011429.16131.cfuller084@thinkingplanet.net> Message-ID: <201109011742.02542.cfuller084@thinkingplanet.net> On Thursday 01 September 2011, Richard D. Moores wrote: > On Thu, Sep 1, 2011 at 12:29, Chris Fuller > > wrote: > > *Ahem* > > > > def is_hashable(object): > > try: > > hash(object) > > except TypeError: > > return False > > > > return True > > Why is that preferred to > > def is_hashable(object): > try: > hash(object) > return True > except TypeError: > return False > > ?? > > Dick It's a style issue, really. Either would be fine, but I don't like mixing code-flow disrupting actions when it's easily avoided. Cheers From brown.helen at yahoo.com Fri Sep 2 02:55:04 2011 From: brown.helen at yahoo.com (Helen Brown) Date: Thu, 1 Sep 2011 17:55:04 -0700 (PDT) Subject: [Tutor] openpyxl Message-ID: <1314924904.68207.YahooMailNeo@web46311.mail.sp1.yahoo.com> Will someone share with me? a link where I can download subject in order for my script to run? Any assistance will help! Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From brown.helen at yahoo.com Fri Sep 2 03:03:58 2011 From: brown.helen at yahoo.com (Helen Brown) Date: Thu, 1 Sep 2011 18:03:58 -0700 (PDT) Subject: [Tutor] openpyxl Message-ID: <1314925438.67247.YahooMailNeo@web46302.mail.sp1.yahoo.com> Will someone share if there is a link where I can download to read a script with subject file? Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Fri Sep 2 03:04:47 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 18:04:47 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <201109011742.02542.cfuller084@thinkingplanet.net> References: <201109011429.16131.cfuller084@thinkingplanet.net> <201109011742.02542.cfuller084@thinkingplanet.net> Message-ID: Ah. I'll follow you with that. Thanks, Dick On Thu, Sep 1, 2011 at 15:42, Chris Fuller wrote: > On Thursday 01 September 2011, Richard D. Moores wrote: >> On Thu, Sep 1, 2011 at 12:29, Chris Fuller >> >> wrote: >> > *Ahem* >> > >> > def is_hashable(object): >> > ? try: >> > ? ? ? ?hash(object) >> > ? ?except TypeError: >> > ? ? ? ?return False >> > >> > ? ?return True >> >> Why is that preferred to >> >> def is_hashable(object): >> ? ? try: >> ? ? ? ? hash(object) >> ? ? ? ? return True >> ? ? except TypeError: >> ? ? ? ? return False >> >> ?? >> >> Dick > > It's a style issue, really. ?Either would be fine, but I don't like mixing > code-flow disrupting actions when it's easily avoided. > > Cheers > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at pearwood.info Fri Sep 2 03:08:41 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Sep 2011 11:08:41 +1000 Subject: [Tutor] Is there a test for hashability? In-Reply-To: References: Message-ID: <4E602C99.4040309@pearwood.info> Richard D. Moores wrote: > I'm trying to write a general test for hashability. How can I test if > an object has both a __hash__() method and an __eq__() method? Just because an object has a __hash__ method doesn't mean it is guaranteed to be hashable. The method might (deliberately, or accidentally) fail and raise an exception. >>> t = (1, 2, 3) >>> t.__hash__ >>> hash(t) -378539185 But: >>> t = (1, 2, [3]) >>> t.__hash__ >>> hash(t) Traceback (most recent call last): File "", line 1, in TypeError: list objects are unhashable The only effective way to find out if an object is hashable is to try it and see. Even more effective is to avoid trying to find out whether it is hashable, and just use it, as required, and deal with the error if it isn't. This is the "Easy to get forgiveness than to ask permission" model of error handling, as opposed to "Look before you leap". For various reasons, LBYL can be risky... like in Quantum Mechanics, the very act of *looking* at an object might change its behaviour. (Methods can have side-effects.) So, even if is_hashable(obj) returns True, you can't *quite* be 100% certain that mydict[obj] will succeed until you try it. -- Steven From steve at pearwood.info Fri Sep 2 04:17:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Sep 2011 12:17:48 +1000 Subject: [Tutor] Is there a test for hashability? In-Reply-To: References: Message-ID: <4E603CCC.7090908@pearwood.info> Richard D. Moores wrote: > Thanks, James, from your ideas I've come up with this function as a > general test for hashibility of any object: > > def is_hashable(object): > try: > if hash(object): > return True > except TypeError: > return False No need for the "if hash" test, just try hash: def is_hashable(obj): try: hash(object) return True except TypeError: return False -- Steven From steve at pearwood.info Fri Sep 2 04:57:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 2 Sep 2011 12:57:16 +1000 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <4E603CCC.7090908@pearwood.info> References: <4E603CCC.7090908@pearwood.info> Message-ID: <20110902025716.GA31597@sylar> On Fri, Sep 02, 2011 at 12:17:48PM +1000, Steven D'Aprano wrote: > Richard D. Moores wrote: > >Thanks, James, from your ideas I've come up with this function as a > >general test for hashibility of any object: > > > >def is_hashable(object): > > try: > > if hash(object): > > return True > > except TypeError: > > return False > > No need for the "if hash" test, just try hash: Er, except this was already discussed :) Sorry for the noise. -- Steven From steve at pearwood.info Fri Sep 2 05:10:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 2 Sep 2011 13:10:15 +1000 Subject: [Tutor] openpyxl In-Reply-To: <1314924904.68207.YahooMailNeo@web46311.mail.sp1.yahoo.com> References: <1314924904.68207.YahooMailNeo@web46311.mail.sp1.yahoo.com> Message-ID: <20110902031015.GB31597@sylar> On Thu, Sep 01, 2011 at 05:55:04PM -0700, Helen Brown wrote: > Will someone share with me? a link where I can download subject in order for my script to run? Any assistance will help! Did you try googling for it? http://duckduckgo.com/?q=openpyxl http://www.bing.com/search?q=openpyxl http://au.search.yahoo.com/search?p=openpyxl http://www.dogpile.com/info.dogpl/search/web?q=openpyxl Even Google can find it :) http://www.google.com/search?q=openpyxl These days, I recommend using Duck Duck Go because, unlike Google, it doesn't track or bubble your searches: http://donttrack.us/ http://dontbubble.us/ -- Steven From jjhartley at gmail.com Fri Sep 2 06:48:41 2011 From: jjhartley at gmail.com (James Hartley) Date: Thu, 1 Sep 2011 21:48:41 -0700 Subject: [Tutor] use of logging module is shared by all? Message-ID: I'm just needing to verify some behavior. Functionality within the logging module is exercised by calling functions defined within the module itself. I am using SQLAlchemy for database access, but it can be configured to dump out intermediate access information & queries to the logging module -- which is great. It really helps in debugging. However, if I want to write to a log which is separate from what SQLAlchemy is doing, am I correct stating that I will not be able to do so through the logging module? Thanks for any insight which can be shared. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Fri Sep 2 06:53:00 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 1 Sep 2011 21:53:00 -0700 Subject: [Tutor] Is there a test for hashability? In-Reply-To: <4E602C99.4040309@pearwood.info> References: <4E602C99.4040309@pearwood.info> Message-ID: On Thu, Sep 1, 2011 at 18:08, Steven D'Aprano wrote: > Richard D. Moores wrote: >> >> I'm trying to write a general test for hashability. How can I test if >> an object has both a ?__hash__() method and an __eq__() method? > > > Just because an object has a __hash__ method doesn't mean it is guaranteed > to be hashable. The method might (deliberately, or accidentally) fail and > raise an exception. > >>>> t = (1, 2, 3) >>>> t.__hash__ > >>>> hash(t) > -378539185 > > But: > >>>> t = (1, 2, [3]) >>>> t.__hash__ > >>>> hash(t) > Traceback (most recent call last): > ?File "", line 1, in > TypeError: list objects are unhashable > > > The only effective way to find out if an object is hashable is to try it and > see. > > Even more effective is to avoid trying to find out whether it is hashable, > and just use it, as required, and deal with the error if it isn't. This is > the "Easy to get forgiveness than to ask permission" model of error > handling, as opposed to "Look before you leap". > > For various reasons, LBYL can be risky... like in Quantum Mechanics, the > very act of *looking* at an object might change its behaviour. (Methods can > have side-effects.) So, even if is_hashable(obj) returns True, you can't > *quite* be 100% certain that mydict[obj] will succeed until you try it. Steven, Do you have an actual example of an actual object for which "my" is_hashable(object) function would return the wrong answer? >>> def is_hashable(object): ... try: ... hash(object) ... except TypeError: ... return False ... return True ... >>> is_hashable((1, 2, [3])) False >>> Is that one? Dick From __peter__ at web.de Fri Sep 2 07:53:25 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 02 Sep 2011 07:53:25 +0200 Subject: [Tutor] use of logging module is shared by all? References: Message-ID: James Hartley wrote: > I'm just needing to verify some behavior. > > Functionality within the logging module is exercised by calling functions > defined within the module itself. I am using SQLAlchemy for database > access, but it can be configured to dump out intermediate access > information > & queries to the logging module -- which is great. It really helps in > debugging. > > However, if I want to write to a log which is separate from what > SQLAlchemy is doing, am I correct stating that I will not be able to do so > through the logging module? > > Thanks for any insight which can be shared. Loggers are typically organized in a tree; sqlalchemy will probably log to logging.getLogger("sqlalchemy").warn("whatever") or something like logging.getLogger("sqlalchemy.some.sublogger").critical("test") You can prevent the rootlogger from seeing these messages with sq = logging.getLogger("sqlalchemy") sq.propagate = False If for example you want to see messages in stdout by default, but write SQLAlchemy's messages to a file you'd do (untested) import logging import sys logging.basicConfig(stream=sys.stdout) sq = logging.getLogger("sqalchemy") sqhandler = logging.FileHandler("alchemy.log") sqformatter = logging.Formatter(logging.BASIC_FORMAT) sqhandler.setFormatter(sqformatter) sq.addHandler(sqhandler) sq.propagate = False sq.critical("alchemy") # goes to file alchemy.log logging.getLogger("mine").critical("mine") # goes to stdout From jjhartley at gmail.com Fri Sep 2 08:16:09 2011 From: jjhartley at gmail.com (James Hartley) Date: Thu, 1 Sep 2011 23:16:09 -0700 Subject: [Tutor] use of logging module is shared by all? In-Reply-To: References: Message-ID: Thanks, Peter for taking the time to respond. I need to study the reference further, & your comments pointed out some of my misconceptions. Thank you for clearing up some of my half-researched understanding. Jim On Thu, Sep 1, 2011 at 10:53 PM, Peter Otten <__peter__ at web.de> wrote: > James Hartley wrote: > > > I'm just needing to verify some behavior. > > > > Functionality within the logging module is exercised by calling functions > > defined within the module itself. I am using SQLAlchemy for database > > access, but it can be configured to dump out intermediate access > > information > > & queries to the logging module -- which is great. It really helps in > > debugging. > > > > However, if I want to write to a log which is separate from what > > SQLAlchemy is doing, am I correct stating that I will not be able to do > so > > through the logging module? > > > > Thanks for any insight which can be shared. > > Loggers are typically organized in a tree; sqlalchemy will probably log to > > logging.getLogger("sqlalchemy").warn("whatever") > > or something like > > logging.getLogger("sqlalchemy.some.sublogger").critical("test") > > You can prevent the rootlogger from seeing these messages with > > sq = logging.getLogger("sqlalchemy") > sq.propagate = False > > If for example you want to see messages in stdout by default, but write > SQLAlchemy's messages to a file you'd do (untested) > > import logging > import sys > logging.basicConfig(stream=sys.stdout) > > sq = logging.getLogger("sqalchemy") > sqhandler = logging.FileHandler("alchemy.log") > sqformatter = logging.Formatter(logging.BASIC_FORMAT) > sqhandler.setFormatter(sqformatter) > sq.addHandler(sqhandler) > sq.propagate = False > > sq.critical("alchemy") # goes to file alchemy.log > logging.getLogger("mine").critical("mine") # goes to stdout > > > _______________________________________________ > 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 g.nius.ck at gmail.com Fri Sep 2 15:18:01 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Fri, 2 Sep 2011 09:18:01 -0400 Subject: [Tutor] [Python-ideas] Terminology for "earthshattering" [was: Add from __experimental__ import bla] In-Reply-To: <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1314569103.4640.19.camel@Gutsy> <58780826-87be-436f-b777-937e41691e90@m35g2000prl.googlegroups.com> <871uw2l0vs.fsf@uwakimon.sk.tsukuba.ac.jp> <20110831111946.22bac764@resist.wooz.org> <20110831185635.744c9624@pitrou.net> <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: How about double dot, dot, and no dot releases, (for the number of decimals in it.) I do believe having terminology for this would be good and cool. *+ 0.5* -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Fri Sep 2 15:19:55 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Fri, 2 Sep 2011 09:19:55 -0400 Subject: [Tutor] [Python-ideas] Terminology for "earthshattering" [was: Add from __experimental__ import bla] In-Reply-To: <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> References: <1314569103.4640.19.camel@Gutsy> <58780826-87be-436f-b777-937e41691e90@m35g2000prl.googlegroups.com> <871uw2l0vs.fsf@uwakimon.sk.tsukuba.ac.jp> <20110831111946.22bac764@resist.wooz.org> <20110831185635.744c9624@pitrou.net> <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: What about alpha-omega release, since its the end of many old programs, the beginning of many new, and it just sounds awesome. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Fri Sep 2 16:11:26 2011 From: lisi.reisz at gmail.com (Lisi) Date: Fri, 2 Sep 2011 15:11:26 +0100 Subject: [Tutor] [Python-ideas] Terminology for "earthshattering" [was: Add from __experimental__ import bla] In-Reply-To: References: <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: <201109021511.26196.lisi.reisz@gmail.com> On Friday 02 September 2011 14:19:55 Christopher King wrote: > it just sounds awesome. ??? To me it sounds like alphabet soup! Which is, of course, what, I would argue, it is. ;-) Lisi From alan.gauld at btinternet.com Fri Sep 2 16:55:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 02 Sep 2011 15:55:57 +0100 Subject: [Tutor] [Python-ideas] Terminology for "earthshattering" [was: Add from __experimental__ import bla] In-Reply-To: References: <1314569103.4640.19.camel@Gutsy> <58780826-87be-436f-b777-937e41691e90@m35g2000prl.googlegroups.com> <871uw2l0vs.fsf@uwakimon.sk.tsukuba.ac.jp> <20110831111946.22bac764@resist.wooz.org> <20110831185635.744c9624@pitrou.net> <87mxeok5z0.fsf@uwakimon.sk.tsukuba.ac.jp> Message-ID: On 02/09/11 14:19, Christopher King wrote: > What about alpha-omega release, since its the end of many old programs, > the beginning of many new, and it just sounds awesome. Are you sure you meant to send this to the Python tutor group? It does not appear to be relevant unless I'm missing something? -- Alan G Tutor List moderator From questions.anon at gmail.com Sat Sep 3 00:27:34 2011 From: questions.anon at gmail.com (questions anon) Date: Sat, 3 Sep 2011 08:27:34 +1000 Subject: [Tutor] reclassify values in an array In-Reply-To: References: Message-ID: thank you for all of the resonses, I have attempted all of the suggestions. It is a numpy array so I can try another list if you would prefer but I thought I would show the error anyway. the error I am receiving is ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() on this code big_array=N.ma.concatenate(all_FFDI) for i, value in enumerate(big_array): if value==100: big_array[i]=0 elif value>=100: big_array[i]=1 print big_array On Thu, Sep 1, 2011 at 6:33 PM, Peter Otten <__peter__ at web.de> wrote: > questions anon wrote: > > > I have been going round in circles trying to solve something that sounds > > simple. I have a huge array and I would like to reclassify the values. > > Firstly just make them zeros and ones, for example if the values in the > > array are less than 100 make them 0 and if greater than 100 make them 1. > > And then finally sum them together. > > I have attempted a few methods, see code below. Any feedback will be > > greatly appreciated. > > >>> import numpy > >>> all_FFDI = numpy.arange(60).reshape((3,4,5)) > >>> all_FFDI > array([[[ 0, 1, 2, 3, 4], > [ 5, 6, 7, 8, 9], > [10, 11, 12, 13, 14], > [15, 16, 17, 18, 19]], > > [[20, 21, 22, 23, 24], > [25, 26, 27, 28, 29], > [30, 31, 32, 33, 34], > [35, 36, 37, 38, 39]], > > [[40, 41, 42, 43, 44], > [45, 46, 47, 48, 49], > [50, 51, 52, 53, 54], > [55, 56, 57, 58, 59]]]) > >>> all_FFDI >= 25 > array([[[False, False, False, False, False], > [False, False, False, False, False], > [False, False, False, False, False], > [False, False, False, False, False]], > > [[False, False, False, False, False], > [ True, True, True, True, True], > [ True, True, True, True, True], > [ True, True, True, True, True]], > > [[ True, True, True, True, True], > [ True, True, True, True, True], > [ True, True, True, True, True], > [ True, True, True, True, True]]], dtype=bool) > >>> (all_FFDI >= 25).sum() > 35 > > > _______________________________________________ > 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 walksloud at gmail.com Sat Sep 3 00:55:07 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Fri, 2 Sep 2011 15:55:07 -0700 Subject: [Tutor] reclassify values in an array In-Reply-To: References: Message-ID: <7962A53A-A8BF-416F-8D58-CBD71D0A5DEE@gmail.com> > thank you for all of the resonses, I have attempted all of the suggestions. It is a numpy array so I can try another list if you would prefer but I thought I would show the error anyway. > the error I am receiving is > ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() this is telling you that "value" is not a scalar element, but it has multiple dimensions. do the following: >>> big_array=N.ma.concatenate(all_FFDI) >>> print big_array.shape >>> print big_array[0].shape the first print will report the dimensionality of your big_array. The second print statement will tell you the dimensionality of the 0th element of big_array. This is the first value of "value" in your for loop. Only if the shape is given as "( )", a single (scalar) element, can you compare it to an integer or float. example >>> a = N.zeros([3]) #this builds a one-dimensional array with 3 elements and puts zeros for each value >>> a array([ 0., 0., 0.]) >>> a.shape (3,) >>> a[0].shape ( ) >>> a[0] 0. imagine you have a 2-dimensional array >>> b = N.zeros([3,3]) # a 3 by 3 array of zeros >>> b.shape (3, 3) >>> b[0] array([ 0., 0., 0.]) >>> for i,value in enumerate(b): ... print value [ 0., 0., 0.] [ 0., 0., 0.] [ 0., 0., 0.] you are trying to compare the "value" [ 0., 0., 0.], to an integer. This is why your code fails - your big_array is a multi-dimensional array. The above example is what I mean by "you should play around with the python interpreter". By doing these things (above) you will begin to learn the structure of these objects (defined in this case with numpy). Regards, Andre From questions.anon at gmail.com Mon Sep 5 06:21:31 2011 From: questions.anon at gmail.com (questions anon) Date: Mon, 5 Sep 2011 14:21:31 +1000 Subject: [Tutor] reclassify values in an array In-Reply-To: <7962A53A-A8BF-416F-8D58-CBD71D0A5DEE@gmail.com> References: <7962A53A-A8BF-416F-8D58-CBD71D0A5DEE@gmail.com> Message-ID: Thanks all, that helped me work out that I needed to try something else. If anyone else needs to know what method worked: big_array=N.ma.concatenate(all_FFDI) for x in N.nditer(big_array, op_flags=['readwrite']): if x<100: x[...]=x=0 elif x>=100: x[...]=x=1 sum=big_array.sum(axis=0) On Sat, Sep 3, 2011 at 8:55 AM, Andre' Walker-Loud wrote: > > thank you for all of the resonses, I have attempted all of the > suggestions. It is a numpy array so I can try another list if you would > prefer but I thought I would show the error anyway. > > the error I am receiving is > > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() > > this is telling you that "value" is not a scalar element, but it has > multiple dimensions. > > do the following: > > >>> big_array=N.ma.concatenate(all_FFDI) > >>> print big_array.shape > > >>> print big_array[0].shape > > > the first print will report the dimensionality of your big_array. The > second print statement will tell you the dimensionality of the 0th element > of big_array. This is the first value of "value" in your for loop. > > Only if the shape is given as "( )", a single (scalar) element, can you > compare it to an integer or float. example > > >>> a = N.zeros([3]) #this builds a one-dimensional array with 3 elements > and puts zeros for each value > >>> a > array([ 0., 0., 0.]) > >>> a.shape > (3,) > >>> a[0].shape > ( ) > >>> a[0] > 0. > > imagine you have a 2-dimensional array > > >>> b = N.zeros([3,3]) # a 3 by 3 array of zeros > >>> b.shape > (3, 3) > >>> b[0] > array([ 0., 0., 0.]) > >>> for i,value in enumerate(b): > ... print value > [ 0., 0., 0.] > [ 0., 0., 0.] > [ 0., 0., 0.] > > you are trying to compare the "value" [ 0., 0., 0.], to an integer. This > is why your code fails - your big_array is a multi-dimensional array. > > The above example is what I mean by "you should play around with the python > interpreter". By doing these things (above) you will begin to learn the > structure of these objects (defined in this case with numpy). > > > Regards, > > Andre > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Mon Sep 5 16:26:14 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 5 Sep 2011 09:26:14 -0500 Subject: [Tutor] Getting values from different functions (def's) In-Reply-To: References: Message-ID: Hello Alan!! It is exactly what I need to complete my task :D Than you so much 2011/8/31 Alan Gauld > On 31/08/11 18:17, Susana Iraiis Delgado Rodriguez wrote: > >> Hello list !! >> I'm developing a Python GUI application. I alreday developed a very >> simple window with buttons, each button will do a different task, but >> the most important button will need to get information gotten in >> previous python's functions. Let's say I have four functions but at the >> end I want to collet all the information gotten. >> > > Instead of (or as well as) printing the data you will need to store it in > variables. Then you can use those variables in the other function. > > > > from Tkinter import * >> import tkSimpleDialog >> import tkMessageBox >> import tkFileDialog >> > > # define storage variables > dir = "" > extn = "" > csv_name = "" > > def directorio(): >> > global dir # need to specify the global one > > > print 'Seleccione directorio donde empezar' >> dirname = > tkFileDialog.askdirectory(**parent=root, >> > initialdir="/", > title='Selecciona > la ruta a escanear') > >> if len(dirname ) > 0: >> print "You chose %s" % dirname >> > > dir = dirname # store the value > > def extension(): >> > global extn > > print "Escribe la extension que necesitas buscar" >> ext=tkSimpleDialog.askstring('**Extension a buscar:','') >> print 'Buscando archivos: ',ext >> > extn = ext > > def csv(): >> > global csv_name > > print "Nombre del csv a crear" >> inv=tkSimpleDialog.askstring('**Nombre de .csv:','') >> print 'Archivo de salida: ',inv >> > csv_name = inv > > > def boton4(): >> #In this button I want to make a bigger process, but I need the root >> selected and the two strings the user types. >> print csv.inv #Obviously this throws an error >> > > print dir,csv_name,extn > > But course in a GUI you would normally not use print but instead populate > the text field of a label or Text widget or some such > device. > > > -- > Alan G > 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 susana.delgado_s at utzmg.edu.mx Mon Sep 5 18:08:24 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 5 Sep 2011 11:08:24 -0500 Subject: [Tutor] 'function' object has no attribute 'writer' Message-ID: I want to write a csv file, but I need the final user to give me some values to open and update the file. My code is: from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" def directorio(): global dir print 'Seleccione directorio donde empezar' dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname ) > 0: print "You chose %s" % dirname dir = dirname def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def boton4(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ....... more code But when I run it,console shows: Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 b win32 Type "help", "copyright", "credits" or "license" for more informa >>> import win >>> Seleccione directorio donde empezar You chose C:/ Escribe la extension que necesitas buscar Buscando archivos: .shp Nombre del csv a crear Archivo de salidad: gui.csv Iniciando... Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call_ return self.func(*args) File "win.py", line 43, in boton4 writer = csv.writer(open(csv_name, 'w')) AttributeError: 'function' object has no attribute 'writer' I read a tutorial and csv has a writer function, I'm lost -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Mon Sep 5 18:21:21 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 5 Sep 2011 12:21:21 -0400 Subject: [Tutor] 'function' object has no attribute 'writer' In-Reply-To: References: Message-ID: On Mon, Sep 5, 2011 at 12:08 PM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > I want to write a csv file, but I need the final user to give me some > values to open and update the file. My code is: > from Tkinter import * #Llamo las librerias graficas de Tk > import tkSimpleDialog #Libreria de almacenamiento de dialogos > import tkMessageBox #Libreria de mensajes > import tkFileDialog > import sys, os, csv, time, socket, stat > from osgeo import ogr,gdal,osr > from osgeo.gdalconst import * > from PIL import Image > dir = "" > extn = "" > csv_name = "" > def directorio(): > global dir > print 'Seleccione directorio donde empezar' > dirname = > tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la > ruta a escanear') > if len(dirname ) > 0: > print "You chose %s" % dirname > dir = dirname > def extension(): > global extn > print "Escribe la extension que necesitas buscar" > ext=tkSimpleDialog.askstring('Extension a buscar:','') > print 'Buscando archivos: ',ext > extn = ext > def csv(): > global csv_name > print "Nombre del csv a crear" > inv=tkSimpleDialog.askstring('Nombre de .csv:','') > print 'Archivo de salidad: ',inv > csv_name = inv > def boton4(): > print 'Iniciando...' > gdal.AllRegister() > file_list = [] > folders = None > for root, folders, files in os.walk(dir): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(extn)) > f = open(csv_name, 'wb') > log = open ('log_errores.txt','w') > writer = csv.writer(f) > ....... more code > But when I run it,console shows: > Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 b > win32 > Type "help", "copyright", "credits" or "license" for more informa > >>> import win > >>> Seleccione directorio donde empezar > You chose C:/ > Escribe la extension que necesitas buscar > Buscando archivos: .shp > Nombre del csv a crear > Archivo de salidad: gui.csv > Iniciando... > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call_ > return self.func(*args) > File "win.py", line 43, in boton4 > writer = csv.writer(open(csv_name, 'w')) > AttributeError: 'function' object has no attribute 'writer' > I read a tutorial and csv has a writer function, I'm lost > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You have a function called "csv()" in your code. So when you go csv.blahbittyblob, you've overriden your imported module called "csv" with the function called "csv", python then tries to look up the attribute blahbittyblob and can't find it. it then throws an error. Change your csv function to be csvx() or _csv or something other than csv -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Sep 5 18:21:33 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 5 Sep 2011 17:21:33 +0100 Subject: [Tutor] 'function' object has no attribute 'writer' In-Reply-To: References: Message-ID: Hi Susana, On 5 September 2011 17:08, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > File "win.py", line 43, in boton4 > writer = csv.writer(open(csv_name, 'w')) > AttributeError: 'function' object has no attribute 'writer' > I read a tutorial and csv has a writer function, I'm lost > > Yes, the csv module has a writer function. But read carefully! The error message isn't saying that the csv module doesn't have a writer function -- it says **function object** has no attribute 'writer'. So... somehow Python thinks that the name 'csv' refers to a function at the point in the code where the error is thrown. So how can this be? You should be asking yourself this question -- could it be that you've (for example) defined a *function* called 'csv', thereby effectively effectively hiding the *module* csv? ;) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Mon Sep 5 18:53:12 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 5 Sep 2011 11:53:12 -0500 Subject: [Tutor] 'function' object has no attribute 'writer' In-Reply-To: References: Message-ID: Hello guys!!! Shame on me, you're rigth I missunderstood the function and the module. I change the name of my function and that part of my code worked. But now I get a differente error, this script is going to collect information from shapefiles, I asked the user where to start the search, the file extension, and the csv name. Now I get: >>> import win >>> Seleccione directorio donde empezar You chose C:/ Escribe la extension que necesitas buscar Buscando archivos: .shp Nombre del csv a crear Archivo de salidad: gui.csv Iniciando... Exception in Tkinter callback Traceback (most recent call last): File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "win.py", line 65, in boton4 shapeData = ogr.Open(filepath) File "C:\Python26\lib\site-packages\osgeo\ogr.py", line 4033, in Open return _ogr.Open(*args, **kwargs) TypeError: in method 'Open', argument 1 of type 'char const *' The other part of the code is: from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" def directorio(): global dir print 'Seleccione directorio donde empezar' dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname ) > 0: print "You chose %s" % dirname dir = dirname def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv_w(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def boton4(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' x_min = 'x_min' x_max = 'x_max' y_min = 'y_min' y_max = 'y_max' geometria = 'geometria' num_elem = 'num_elem' prj = '.prj' proyeccion = 'proyeccion' fecha = 'fecha_modificacion' creacion = 'fecha_creacion' ultimo = 'ultimo_acceso' tamanio = 'tamanio_aprox' maq = 'maquina_host' usu = 'usuario' campos = [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): directorio = os.path.dirname(filepath) filename = os.path.basename(filepath) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp log.write(shp+"\n") 2011/9/5 James Reynolds > > > On Mon, Sep 5, 2011 at 12:08 PM, Susana Iraiis Delgado Rodriguez < > susana.delgado_s at utzmg.edu.mx> wrote: > >> I want to write a csv file, but I need the final user to give me some >> values to open and update the file. My code is: >> from Tkinter import * #Llamo las librerias graficas de Tk >> import tkSimpleDialog #Libreria de almacenamiento de dialogos >> import tkMessageBox #Libreria de mensajes >> import tkFileDialog >> import sys, os, csv, time, socket, stat >> from osgeo import ogr,gdal,osr >> from osgeo.gdalconst import * >> from PIL import Image >> dir = "" >> extn = "" >> csv_name = "" >> def directorio(): >> global dir >> print 'Seleccione directorio donde empezar' >> dirname = >> tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la >> ruta a escanear') >> if len(dirname ) > 0: >> print "You chose %s" % dirname >> dir = dirname >> def extension(): >> global extn >> print "Escribe la extension que necesitas buscar" >> ext=tkSimpleDialog.askstring('Extension a buscar:','') >> print 'Buscando archivos: ',ext >> extn = ext >> def csv(): >> global csv_name >> print "Nombre del csv a crear" >> inv=tkSimpleDialog.askstring('Nombre de .csv:','') >> print 'Archivo de salidad: ',inv >> csv_name = inv >> def boton4(): >> print 'Iniciando...' >> gdal.AllRegister() >> file_list = [] >> folders = None >> for root, folders, files in os.walk(dir): >> file_list.extend(os.path.join(root,fi) for fi in files if >> fi.endswith(extn)) >> f = open(csv_name, 'wb') >> log = open ('log_errores.txt','w') >> writer = csv.writer(f) >> ....... more code >> But when I run it,console shows: >> Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 b >> win32 >> Type "help", "copyright", "credits" or "license" for more informa >> >>> import win >> >>> Seleccione directorio donde empezar >> You chose C:/ >> Escribe la extension que necesitas buscar >> Buscando archivos: .shp >> Nombre del csv a crear >> Archivo de salidad: gui.csv >> Iniciando... >> Exception in Tkinter callback >> Traceback (most recent call last): >> File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call_ >> return self.func(*args) >> File "win.py", line 43, in boton4 >> writer = csv.writer(open(csv_name, 'w')) >> AttributeError: 'function' object has no attribute 'writer' >> I read a tutorial and csv has a writer function, I'm lost >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > You have a function called "csv()" in your code. > > So when you go csv.blahbittyblob, you've overriden your imported module > called "csv" with the function called "csv", python then tries to look up > the attribute blahbittyblob and can't find it. it then throws an error. > > Change your csv function to be csvx() or _csv or something other than csv > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Sep 5 21:09:56 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 Sep 2011 21:09:56 +0200 Subject: [Tutor] 'function' object has no attribute 'writer' References: Message-ID: Susana Iraiis Delgado Rodriguez wrote: Susana, please use 4-space indents for your code samples. I've said it before, but I think it's worthwhile repeating because it makes it much easier to grasp the structure of a script at first sight. > But now I get a differente error, this script is going to collect > information from shapefiles, I asked the user where to start the search, > the file extension, and the csv name. Now I get: >>>> import win >>>> Seleccione directorio donde empezar > You chose C:/ > Escribe la extension que necesitas buscar > Buscando archivos: .shp > Nombre del csv a crear > Archivo de salidad: gui.csv > Iniciando... > Exception in Tkinter callback > Traceback (most recent call last): > File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "win.py", line 65, in boton4 > shapeData = ogr.Open(filepath) > File "C:\Python26\lib\site-packages\osgeo\ogr.py", line 4033, in Open > return _ogr.Open(*args, **kwargs) > TypeError: in method 'Open', argument 1 of type 'char const *' > > The other part of the code is: > from osgeo import ogr,gdal,osr > shapeData = ogr.Open(filepath) filepath is a unicode string, your library seems to expect byte strings. Try converting it like so: import sys filesystemencoding = sys.getfilesystemencoding() #... shapeData = ogr.Open(filepath.encode(filesystemencoding)) From clsdaniel at gmail.com Tue Sep 6 00:32:35 2011 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Mon, 5 Sep 2011 15:32:35 -0700 Subject: [Tutor] Application packaging Message-ID: Hello list, Lately I have been working on a windows desktop application for a client, using python and pyside, everything working fine, but I'm getting a bit stuck when trying to distribute the application to the client. Currently I'm using a combination of py2exe and clickonce, what are your experiences on distributing this kind of applications on a windows environment? Personally I have tried py2exe, pyinstaller, cx_freeze, only py2exe got me a working bundle but a ugly one full of unordered files, I wrapped all this on a ClickOnce installer so the user just sees an icon in their desktop. The problem with this approach is that it results in a huge bundle, updates are a pain too. Any ideas or experience with this (not precisely this combo but the packaging in general)? Regards, Carlos Ruvalcaba PD: I'm looking for the actual state of things right now as I'm sure this questing has been asked in the past. -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Tue Sep 6 17:47:49 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 6 Sep 2011 10:47:49 -0500 Subject: [Tutor] 'function' object has no attribute 'writer' In-Reply-To: References: Message-ID: Hello Petter!! Thank you for answer to my question. I apologize for the writing of my code, won't happen again. I added the lines you suggested me, and the script work fine. Than you!! Here's the code corrected and indented. from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" filesystemencoding = sys.getfilesystemencoding() def directorio(): global dir print 'Seleccione directorio donde empezar' dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname ) > 0: print "You chose %s" % dirname dir = dirname def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv_w(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def boton4(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' x_min = 'x_min' x_max = 'x_max' y_min = 'y_min' y_max = 'y_max' geometria = 'geometria' num_elem = 'num_elem' prj = '.prj' proyeccion = 'proyeccion' fecha = 'fecha_modificacion' creacion = 'fecha_creacion' ultimo = 'ultimo_acceso' tamanio = 'tamanio_aprox' maq = 'maquina_host' usu = 'usuario' campos = [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): directorio = os.path.dirname(filepath) filename = os.path.basename(filepath) shapeData = ogr.Open(filepath.encode(filesystemencoding)) shp = 'Error al abrir el archivo' +filepath ...... 2011/9/5 Peter Otten <__peter__ at web.de> > Susana Iraiis Delgado Rodriguez wrote: > > Susana, please use 4-space indents for your code samples. I've said it > before, but I think it's worthwhile repeating because it makes it much > easier to grasp the structure of a script at first sight. > > > But now I get a differente error, this script is going to collect > > information from shapefiles, I asked the user where to start the search, > > the file extension, and the csv name. Now I get: > >>>> import win > >>>> Seleccione directorio donde empezar > > You chose C:/ > > Escribe la extension que necesitas buscar > > Buscando archivos: .shp > > Nombre del csv a crear > > Archivo de salidad: gui.csv > > Iniciando... > > Exception in Tkinter callback > > Traceback (most recent call last): > > File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__ > > return self.func(*args) > > File "win.py", line 65, in boton4 > > shapeData = ogr.Open(filepath) > > File "C:\Python26\lib\site-packages\osgeo\ogr.py", line 4033, in Open > > return _ogr.Open(*args, **kwargs) > > TypeError: in method 'Open', argument 1 of type 'char const *' > > > > The other part of the code is: > > > from osgeo import ogr,gdal,osr > > > shapeData = ogr.Open(filepath) > > filepath is a unicode string, your library seems to expect byte strings. > Try converting it like so: > > import sys > filesystemencoding = sys.getfilesystemencoding() > #... > shapeData = ogr.Open(filepath.encode(filesystemencoding)) > > _______________________________________________ > 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 lina.lastname at gmail.com Wed Sep 7 06:46:37 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 12:46:37 +0800 Subject: [Tutor] how to sort the file out Message-ID: HI, I have two files, one is reference file, another is waiting for adjust one, File 1: 1 C1 2 O1 3 C2 4 C3 5 H3 6 C7 7 O2 8 H22 9 C6 10 H61 11 C5 12 H5 13 C4 14 C8 15 C9 16 C10 17 O3 18 C11 19 C12 20 O4 21 C13 22 C14 23 C15 24 C20 25 H20 26 C16 27 H16 28 C17 29 H17 30 C18 31 O6 32 H62 33 C19 34 O5 35 C21 File 2: 3 H16 4 H5 6 H61 7 H17 9 H20 12 H3 13 C1 14 O1 15 C2 16 C3 17 C4 18 C5 19 C6 20 C7 21 C8 22 C9 23 C10 24 O3 25 C11 26 C12 27 O4 28 C13 29 C14 30 C15 31 C20 32 C19 33 C18 34 C17 35 C16 36 O5 37 C21 38 O6 39 H62 40 O2 41 H22 I wish the field 2 from file 2 arranged the same sequence as the field 2 of file 1. Thanks for any suggestions, I drove my minds into nuts already, three hours passed and I still failed to achieve this. -- Best Regards, lina From wolfrage8765 at gmail.com Wed Sep 7 07:14:55 2011 From: wolfrage8765 at gmail.com (Jordan) Date: Tue, 06 Sep 2011 22:14:55 -0700 Subject: [Tutor] how to sort the file out In-Reply-To: References: Message-ID: <4E66FDCF.7090509@gmail.com> Perhaps a little more information on what is going on and what the expected outcome is. In order for the tutors to be able to better help you as I am not sure what you expect to get from these two lists. IE there is no field 2 in file 2, so what should it be? Also what should happen to the rest of the file if I make field 2 of file 2 equal "01"? -- Jordan On 09/06/2011 09:46 PM, lina wrote: > HI, I have two files, one is reference file, another is waiting for adjust one, > > File 1: > > 1 C1 > 2 O1 > 3 C2 > 4 C3 > 5 H3 > 6 C7 > 7 O2 > 8 H22 > 9 C6 > 10 H61 > 11 C5 > 12 H5 > 13 C4 > 14 C8 > 15 C9 > 16 C10 > 17 O3 > 18 C11 > 19 C12 > 20 O4 > 21 C13 > 22 C14 > 23 C15 > 24 C20 > 25 H20 > 26 C16 > 27 H16 > 28 C17 > 29 H17 > 30 C18 > 31 O6 > 32 H62 > 33 C19 > 34 O5 > 35 C21 > > File 2: > 3 H16 > 4 H5 > 6 H61 > 7 H17 > 9 H20 > 12 H3 > 13 C1 > 14 O1 > 15 C2 > 16 C3 > 17 C4 > 18 C5 > 19 C6 > 20 C7 > 21 C8 > 22 C9 > 23 C10 > 24 O3 > 25 C11 > 26 C12 > 27 O4 > 28 C13 > 29 C14 > 30 C15 > 31 C20 > 32 C19 > 33 C18 > 34 C17 > 35 C16 > 36 O5 > 37 C21 > 38 O6 > 39 H62 > 40 O2 > 41 H22 > > I wish the field 2 from file 2 arranged the same sequence as the field > 2 of file 1. > > Thanks for any suggestions, > > I drove my minds into nuts already, three hours passed and I still > failed to achieve this. > From hugo.yoshi at gmail.com Wed Sep 7 07:28:18 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 7 Sep 2011 07:28:18 +0200 Subject: [Tutor] how to sort the file out In-Reply-To: <4E66FDCF.7090509@gmail.com> References: <4E66FDCF.7090509@gmail.com> Message-ID: I was assuming that the numbers were field 1, and the letter/number combinations were field 2. If I understand him correctly, he wants the lines in file 2 to be arranged such that the order of field two is the same as it is in file 1. In that case, you can do it with one sexy sort() call (and a little preprocessing to load the files), but I don't want to get all into explain and then realize he wants something totally different. So please show us with some smaller files (5 lines is fine) what exactly you want the result to be. Hugo On Wed, Sep 7, 2011 at 7:14 AM, Jordan wrote: > Perhaps a little more information on what is going on and what the > expected outcome is. In order for the tutors to be able to better help > you as I am not sure what you expect to get from these two lists. IE > there is no field 2 in file 2, so what should it be? Also what should > happen to the rest of the file if I make field 2 of file 2 equal "01"? > -- > Jordan > > On 09/06/2011 09:46 PM, lina wrote: >> HI, I have two files, one is reference file, another is waiting for adjust one, >> >> File 1: >> >> 1 C1 >> 2 O1 >> 3 C2 >> 4 C3 >> 5 H3 >> 6 C7 >> 7 O2 >> 8 H22 >> 9 C6 >> 10 H61 >> 11 C5 >> 12 H5 >> 13 C4 >> 14 C8 >> 15 C9 >> 16 C10 >> 17 O3 >> 18 C11 >> 19 C12 >> 20 O4 >> 21 C13 >> 22 C14 >> 23 C15 >> 24 C20 >> 25 H20 >> 26 C16 >> 27 H16 >> 28 C17 >> 29 H17 >> 30 C18 >> 31 O6 >> 32 H62 >> 33 C19 >> 34 O5 >> 35 C21 >> >> File 2: >> 3 H16 >> 4 H5 >> 6 H61 >> 7 H17 >> 9 H20 >> 12 H3 >> 13 C1 >> 14 O1 >> 15 C2 >> 16 C3 >> 17 C4 >> 18 C5 >> 19 C6 >> 20 C7 >> 21 C8 >> 22 C9 >> 23 C10 >> 24 O3 >> 25 C11 >> 26 C12 >> 27 O4 >> 28 C13 >> 29 C14 >> 30 C15 >> 31 C20 >> 32 C19 >> 33 C18 >> 34 C17 >> 35 C16 >> 36 O5 >> 37 C21 >> 38 O6 >> 39 H62 >> 40 O2 >> 41 H22 >> >> I wish the field 2 from file 2 arranged the same sequence as the field >> 2 of file 1. >> >> Thanks for any suggestions, >> >> I drove my minds into nuts already, three ?hours passed and I still >> failed to achieve this. >> > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From bodsda at googlemail.com Wed Sep 7 07:52:16 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Wed, 7 Sep 2011 05:52:16 +0000 Subject: [Tutor] how to sort the file out In-Reply-To: References: Message-ID: <212055530-1315374736-cardhu_decombobulator_blackberry.rim.net-1032708278-@b28.c12.bise7.blackberry> I'm also slightly confused. Why does file one start at 1, but file 2 starts at 3. Why not just duplicate file2? Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: lina Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Wed, 7 Sep 2011 12:46:37 To: tutor Subject: [Tutor] how to sort the file out HI, I have two files, one is reference file, another is waiting for adjust one, File 1: 1 C1 2 O1 3 C2 4 C3 5 H3 6 C7 7 O2 8 H22 9 C6 10 H61 11 C5 12 H5 13 C4 14 C8 15 C9 16 C10 17 O3 18 C11 19 C12 20 O4 21 C13 22 C14 23 C15 24 C20 25 H20 26 C16 27 H16 28 C17 29 H17 30 C18 31 O6 32 H62 33 C19 34 O5 35 C21 File 2: 3 H16 4 H5 6 H61 7 H17 9 H20 12 H3 13 C1 14 O1 15 C2 16 C3 17 C4 18 C5 19 C6 20 C7 21 C8 22 C9 23 C10 24 O3 25 C11 26 C12 27 O4 28 C13 29 C14 30 C15 31 C20 32 C19 33 C18 34 C17 35 C16 36 O5 37 C21 38 O6 39 H62 40 O2 41 H22 I wish the field 2 from file 2 arranged the same sequence as the field 2 of file 1. Thanks for any suggestions, I drove my minds into nuts already, three hours passed and I still failed to achieve this. -- Best Regards, lina _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From lina.lastname at gmail.com Wed Sep 7 08:13:05 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 14:13:05 +0800 Subject: [Tutor] how to sort the file out In-Reply-To: <212055530-1315374736-cardhu_decombobulator_blackberry.rim.net-1032708278-@b28.c12.bise7.blackberry> References: <212055530-1315374736-cardhu_decombobulator_blackberry.rim.net-1032708278-@b28.c12.bise7.blackberry> Message-ID: For file 1, 1 C1 2 O1 3 C2 4 C3 5 H3 This one is much more like dictionary, ; nr atom cgnr charge mass 1 C1 1 0.062 15.0350 2 O1 1 -0.139 15.9994 3 C2 1 0.064 12.0110 4 C3 1 -0.001 12.0110 5 H3 1 0.014 1.0080 which was from field one and filed 2, namely the atom column, while for file 2: 12 H3 13 C1 14 O1 15 C2 16 C3 I want to be arranged like: 13 C1 14 O1 15 C2 16 C3 12 H3 only sort field 2 based on the dictionary, to match the sequence of C1, O1, C2, C3, H3. Thanks again, I want to arranged the field 3 according to match the dictionary (file 1) sequence. On Wed, Sep 7, 2011 at 1:52 PM, wrote: > I'm also slightly confused. Why does file one start at 1, but file 2 starts at 3. Why not just duplicate file2? > > Bodsda > Sent from my BlackBerry? wireless device > > -----Original Message----- > From: lina > Sender: tutor-bounces+bodsda=googlemail.com at python.org > Date: Wed, 7 Sep 2011 12:46:37 > To: tutor > Subject: [Tutor] how to sort the file out > > HI, I have two files, one is reference file, another is waiting for adjust one, > > File 1: > > 1 C1 > 2 O1 > 3 C2 > 4 C3 > 5 H3 > 6 C7 > 7 O2 > 8 H22 > 9 C6 > 10 H61 > 11 C5 > 12 H5 > 13 C4 > 14 C8 > 15 C9 > 16 C10 > 17 O3 > 18 C11 > 19 C12 > 20 O4 > 21 C13 > 22 C14 > 23 C15 > 24 C20 > 25 H20 > 26 C16 > 27 H16 > 28 C17 > 29 H17 > 30 C18 > 31 O6 > 32 H62 > 33 C19 > 34 O5 > 35 C21 > > File 2: > 3 H16 > 4 H5 > 6 H61 > 7 H17 > 9 H20 > 12 H3 > 13 C1 > 14 O1 > 15 C2 > 16 C3 > 17 C4 > 18 C5 > 19 C6 > 20 C7 > 21 C8 > 22 C9 > 23 C10 > 24 O3 > 25 C11 > 26 C12 > 27 O4 > 28 C13 > 29 C14 > 30 C15 > 31 C20 > 32 C19 > 33 C18 > 34 C17 > 35 C16 > 36 O5 > 37 C21 > 38 O6 > 39 H62 > 40 O2 > 41 H22 > > I wish the field 2 from file 2 arranged the same sequence as the field > 2 of file 1. > > Thanks for any suggestions, > > I drove my minds into nuts already, three ?hours passed and I still > failed to achieve this. > > -- > Best Regards, > > lina > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From hugo.yoshi at gmail.com Wed Sep 7 08:25:07 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 7 Sep 2011 08:25:07 +0200 Subject: [Tutor] Fwd: how to sort the file out In-Reply-To: References: <4E66FDCF.7090509@gmail.com> Message-ID: forgot to forward this to list, sorry. ---------- Forwarded message ---------- From: Hugo Arts Date: Wed, Sep 7, 2011 at 8:24 AM Subject: Re: [Tutor] how to sort the file out To: lina On Wed, Sep 7, 2011 at 8:16 AM, lina wrote: > On Wed, Sep 7, 2011 at 1:28 PM, Hugo Arts wrote: >> I was assuming that the numbers were field 1, and the letter/number >> combinations were field 2. If I understand him correctly, he wants the > > Yes. > >> lines in file 2 to be arranged such that the order of field two is the >> same as it is in file 1. In that case, you can do it with one sexy >> sort() call (and a little preprocessing to load the files), but I >> don't want to get all into explain and then realize he wants something >> totally different. > You understand right. > Well, it is fairly simple. You grab field2 from file1, and put all the items into a list (should be easy right? open(), readlines(), split(), grab second item). Then, you grab file2 as a list of tuples (same procedure as the first file, but you just put the results of split() right into the list. Then you sort with a key like so: list2.sort(key=lambda x: list1.index(x[1])) You see? For each item in the second list, we grab field 2, and look up what index it has in list1. Then we use that index as the sort key. That way they'll be sorted like file1 is. After that it's just a matter of writing back to the file, easy peasy. HTH, Hugo From lina.lastname at gmail.com Wed Sep 7 08:57:44 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 14:57:44 +0800 Subject: [Tutor] Fwd: how to sort the file out In-Reply-To: References: <4E66FDCF.7090509@gmail.com> Message-ID: On Wed, Sep 7, 2011 at 2:25 PM, Hugo Arts wrote: > forgot to forward this to list, sorry. > > > ---------- Forwarded message ---------- > From: Hugo Arts > Date: Wed, Sep 7, 2011 at 8:24 AM > Subject: Re: [Tutor] how to sort the file out > To: lina > > > On Wed, Sep 7, 2011 at 8:16 AM, lina wrote: >> On Wed, Sep 7, 2011 at 1:28 PM, Hugo Arts wrote: >>> I was assuming that the numbers were field 1, and the letter/number >>> combinations were field 2. If I understand him correctly, he wants the >> >> Yes. >> >>> lines in file 2 to be arranged such that the order of field two is the >>> same as it is in file 1. In that case, you can do it with one sexy >>> sort() call (and a little preprocessing to load the files), but I >>> don't want to get all into explain and then realize he wants something >>> totally different. >> You understand right. >> > > Well, it is fairly simple. You grab field2 from file1, and put all the > items into a list (should be easy right? open(), readlines(), split(), > grab second item). Then, you grab file2 as a list of tuples (same > procedure as the first file, but you just put the results of split() > right into the list. Then you sort with a key like so: > > list2.sort(key=lambda x: list1.index(x[1])) > > You see? For each item in the second list, we grab field 2, and look > up what index it has in list1. Then we use that index as the sort key. > That way they'll be sorted like file1 is. not easy to me. Sign ... I may do it by hand, cut and pasta following the orders. > > After that it's just a matter of writing back to the file, easy peasy. > > HTH, > Hugo > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From lina.lastname at gmail.com Wed Sep 7 10:50:31 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 16:50:31 +0800 Subject: [Tutor] Fwd: how to sort the file out In-Reply-To: References: <4E66FDCF.7090509@gmail.com> Message-ID: On Wed, Sep 7, 2011 at 2:57 PM, lina wrote: > On Wed, Sep 7, 2011 at 2:25 PM, Hugo Arts wrote: >> forgot to forward this to list, sorry. >> >> >> ---------- Forwarded message ---------- >> From: Hugo Arts >> Date: Wed, Sep 7, 2011 at 8:24 AM >> Subject: Re: [Tutor] how to sort the file out >> To: lina >> >> >> On Wed, Sep 7, 2011 at 8:16 AM, lina wrote: >>> On Wed, Sep 7, 2011 at 1:28 PM, Hugo Arts wrote: >>>> I was assuming that the numbers were field 1, and the letter/number >>>> combinations were field 2. If I understand him correctly, he wants the >>> >>> Yes. >>> >>>> lines in file 2 to be arranged such that the order of field two is the >>>> same as it is in file 1. In that case, you can do it with one sexy >>>> sort() call (and a little preprocessing to load the files), but I >>>> don't want to get all into explain and then realize he wants something >>>> totally different. >>> You understand right. >>> >> >> Well, it is fairly simple. You grab field2 from file1, and put all the >> items into a list (should be easy right? open(), readlines(), split(), >> grab second item). Then, you grab file2 as a list of tuples (same >> procedure as the first file, but you just put the results of split() >> right into the list. Then you sort with a key like so: >> >> list2.sort(key=lambda x: list1.index(x[1])) >> >> You see? For each item in the second list, we grab field 2, and look >> up what index it has in list1. Then we use that index as the sort key. >> That way they'll be sorted like file1 is. > > not easy to me. > > Sign ... I may do it by hand, cut and pasta following the orders. After overcoming the nearly-give-up frustration, I finally see the deadly-beautiful results. It's so BEAUTIFUL. amazing ... >> >> After that it's just a matter of writing back to the file, easy peasy. >> >> HTH, >> Hugo >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Best Regards, > > lina > -- Best Regards, lina From __peter__ at web.de Wed Sep 7 10:52:03 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 07 Sep 2011 10:52:03 +0200 Subject: [Tutor] how to sort the file out References: Message-ID: lina wrote: > HI, I have two files, one is reference file, another is waiting for adjust > one, > > File 1: > > 1 C1 > 2 O1 [...] > 33 C19 > 34 O5 > 35 C21 > > File 2: > 3 H16 > 4 H5 [...] > 39 H62 > 40 O2 > 41 H22 > > I wish the field 2 from file 2 arranged the same sequence as the field > 2 of file 1. > > Thanks for any suggestions, > > I drove my minds into nuts already, three hours passed and I still > failed to achieve this. You could have written the above after three minutes. To get the most out of this mailing list you should give some details of what you tried and how it failed. This gives us valuable information about your level of knowledge and confidence that you are trying to learn rather than get solutions on the cheap. However, I'm in the mood for some spoonfeeding: indexfile = "tmp_index.txt" datafile = "tmp_data.txt" sorteddatafile = "tmp_output.txt" def make_lookup(lines): r"""Build a dictionary that maps the second column to the line number. >>> make_lookup(["aaa bbb\n", "ccc ddd\n"]) == {'bbb': 0, 'ddd': 1} True """ position_lookup = {} for lineno, line in enumerate(lines): second_field = line.split()[1] position_lookup[second_field] = lineno return position_lookup with open(indexfile) as f: position_lookup = make_lookup(f) # With your sample data the global position_lookup dict looks like this now: # {'C1': 0, 'O1': 1, 'C2': 2,... , 'O5': 33, 'C21': 34} def get_position(line): r"""Extract the second field from the line and look up the associated line number in the global position_lookup dictionary. Example: get_position("15 C2\n") The line is split into ["15", "C2"] The second field is "C2" Its associated line number in position_lookup: 2 --> the function returns 2 """ second_field = line.split()[1] return position_lookup[second_field] with open(datafile) as f: # sort the lines in the data file using the line number in the index # file as the sort key lines = sorted(f, key=get_position) with open(sorteddatafile, "w") as f: f.writelines(lines) From lina.lastname at gmail.com Wed Sep 7 12:04:30 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 7 Sep 2011 18:04:30 +0800 Subject: [Tutor] how to sort the file out In-Reply-To: References: Message-ID: On Wed, Sep 7, 2011 at 4:52 PM, Peter Otten <__peter__ at web.de> wrote: > lina wrote: > >> HI, I have two files, one is reference file, another is waiting for adjust >> one, >> >> File 1: >> >> 1 C1 >> 2 O1 > [...] >> 33 C19 >> 34 O5 >> 35 C21 >> >> File 2: >> 3 H16 >> 4 H5 > [...] >> 39 H62 >> 40 O2 >> 41 H22 >> >> I wish the field 2 from file 2 arranged the same sequence as the field >> 2 of file 1. >> >> Thanks for any suggestions, >> >> I drove my minds into nuts already, three ?hours passed and I still >> failed to achieve this. > > You could have written the above after three minutes. To get the most out of > this mailing list you should give some details of what you tried and how it > failed. This gives us valuable information about your level of knowledge and > confidence that you are trying to learn rather than get solutions on the > cheap. > > However, I'm in the mood for some spoonfeeding: LOL ... thanks. I am very very low leavel in python, many times I just gave up due to frustration in using it. and escape back to bash, awk. > > indexfile = "tmp_index.txt" > datafile = "tmp_data.txt" > sorteddatafile = "tmp_output.txt" > > def make_lookup(lines): > ? ?r"""Build a dictionary that maps the second column to the line number. > > ? ?>>> make_lookup(["aaa bbb\n", "ccc ddd\n"]) == {'bbb': 0, 'ddd': 1} > ? ?True > ? ?""" > ? ?position_lookup = {} > ? ?for lineno, line in enumerate(lines): > ? ? ? ?second_field = line.split()[1] > ? ? ? ?position_lookup[second_field] = lineno > ? ?return position_lookup > > with open(indexfile) as f: > ? ?position_lookup = make_lookup(f) > > # With your sample data the global position_lookup dict looks like this now: > # {'C1': 0, 'O1': 1, 'C2': 2,... , 'O5': 33, 'C21': 34} > > def get_position(line): > ? ?r"""Extract the second field from the line and look up the > ? ?associated line number in the global position_lookup dictionary. > > ? ?Example: > ? ?get_position("15 C2\n") > ? ?The line is split into ["15", "C2"] > ? ?The second field is "C2" > ? ?Its associated line number in position_lookup: 2 > ? ?--> the function returns 2 > ? ?""" > ? ?second_field = line.split()[1] > ? ?return position_lookup[second_field] > > with open(datafile) as f: > ? ?# sort the lines in the data file using the line number in the index > ? ?# file as the sort key > ? ?lines = sorted(f, key=get_position) > > with open(sorteddatafile, "w") as f: > ? ?f.writelines(lines) > It's an amazing opportunity to learn. I will try it now. > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From illusiontechniques at gmail.com Thu Sep 8 05:26:34 2011 From: illusiontechniques at gmail.com (c smith) Date: Wed, 7 Sep 2011 23:26:34 -0400 Subject: [Tutor] how obsolete is 2.2? Message-ID: I found a book at the local library that covers python but it's 2.2. I already have been using 2.7 for basic stuff and would like to know if it's worth my time to read this book. Are there any glaring differences that would be easy to point out, or is it too convoluted? Also, am I correct in thinking that 3.0 will always be called 3.0 but will change over time and will always include experimental features, while 2.x will gradually increase the 'x' and the highest 'x' will indicate the most current, stable release? oh, and a question on 'pickle': can pickle deserialize things that were not serialized by python? can it convert data into a python data type regardless of it was originally a 'c array' or something else that python doesn't support? -------------- next part -------------- An HTML attachment was scrubbed... URL: From illusiontechniques at gmail.com Thu Sep 8 05:48:46 2011 From: illusiontechniques at gmail.com (c smith) Date: Wed, 7 Sep 2011 23:48:46 -0400 Subject: [Tutor] how obsolete is 2.2, and a pickle question Message-ID: I found a book at the local library that covers python but it's 2.2. I already have been using 2.7 for basic stuff and would like to know if it's worth my time to read this book. Are there any glaring differences that would be easy to point out, or is it too convoluted? Also, am I correct in thinking that 3.0 will always be called 3.0 but will change over time and will always include experimental features, while 2.x will gradually increase the 'x' and the highest 'x' will indicate the most current, stable release? oh, and a question on 'pickle': can pickle deserialize things that were not serialized by python? can it convert data into a python data type regardless of it was originally a 'c array' or something else that python doesn't support? -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Thu Sep 8 07:36:24 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 08 Sep 2011 07:36:24 +0200 Subject: [Tutor] how obsolete is 2.2? In-Reply-To: References: Message-ID: Hi, please don't repost your question before waiting at least a little for an answer. c smith, 08.09.2011 05:26: > I found a book at the local library that covers python but it's 2.2. That's way old then. It won't teach you anything about the really interesting and helpful things in Python, such as generators, itertools or the "with" statement, extended APIs and stdlib modules, and loads of other goodies and enhanced features, such as metaclasses and interpreter configuration stuff. > I already have been using 2.7 for basic stuff and would like to know if it's > worth my time to read this book. Likely not. Better read a recent tutorial or spend your time getting used to the official Python documentation. > Are there any glaring differences that would be easy to point out, or is it > too convoluted? Tons of them, too many to even get started. You might want to take a look at the "what's new" pages in the Python documentation. That will give you a pretty good idea of major advances. > Also, am I correct in thinking that 3.0 will always be called 3.0 No. It's called Python 3 (sometimes historically named Python 3k or Python 3000), with released versions being 3.0, 3.1.x and 3.2.x and the upcoming release being 3.3. > but will change over time and will always include experimental features Well, it's the place where all current development happens, be it experimental or not. > while 2.x will gradually increase the 'x' Nope. 'x' is fixed at 7, Py2.7 is the officially last release series of Python 2, although with an extended maintenance time frame of several years. > and the highest 'x' will indicate the most current, stable release? That's right, both for the Py2.x and Py3.x releases. > oh, and a question on 'pickle': Let's keep that in your other post, to let it serve a purpose. Stefan From __peter__ at web.de Thu Sep 8 10:15:19 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 10:15:19 +0200 Subject: [Tutor] how obsolete is 2.2, and a pickle question References: Message-ID: c smith wrote: > oh, and a question on 'pickle': > can pickle deserialize things that were not serialized by python? > can it convert data into a python data type regardless of it was > originally a 'c array' or something else that python doesn't support? As long as the file written by C is a valid pickle file and all classes used are available to the Python interpreter you are fine: $ cat pickledemo_struct.c #include typedef struct NAMEDPAIR { char name[10]; int x; int y; } namedpair; main() { FILE *f = fopen("tmp_struct.pickle", "wb"); int i; namedpair *p, data[] = {{"Cube", 10, 20}, {"Pyramid", 30, 40}}; fprintf(f, "(lp0\n"); for (i = 0, p = data; i != 2; i++, p++) { fprintf(f, "(S'%s'\nI%d\nI%d\ntp%d\na", p->name, p->x, p->y, i+1); } fprintf(f, "."); } $ gcc pickledemo_struct.c $ ./a.out $ python -c 'import pickle; print pickle.load(open("tmp_struct.pickle"))' [('Cube', 10, 20), ('Pyramid', 30, 40)] But remember that in C the information whether you have a 32 bit integer or four characters is in the code, not in the data; if you just dump that data to a file Python can still read it, but has no way of knowing what it's meant to be. From alan.gauld at btinternet.com Thu Sep 8 10:25:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 09:25:25 +0100 Subject: [Tutor] how obsolete is 2.2? In-Reply-To: References: Message-ID: On 08/09/11 04:26, c smith wrote: > I found a book at the local library that covers python but it's 2.2. > I already have been using 2.7 for basic stuff and would like to know if > it's worth my time to read this book. That depends on your experience level and what you are looking to get out of it. The Python 2 series is very backwards compatible so virtually everything you read in the book will still work in Python 2.7. It's just that some new whizzy features have been added since 2.2 that it won't cover. But many of those features are not things the average programmer uses every day. The vast majority of the standard library modules haven't changed that much and any information about those will probably still be accurate. Given you get to read it for free from the library I'd say yes, its very worthwhile. But if you have been using Python for a while and want to dig deeper into its power features then it probably isn't worth reading because the changes in Python recently have focused on many of the more subtle things "under the covers" and 2.2 won't cover them, > can pickle deserialize things that were not serialized by python? Not unless the thing that serialised them was deliberately copying Pythons serialisation format. > can it convert data into a python data type regardless of it was > originally a 'c array' or something else that python doesn't support? No, the nearest thing to that is the struct module. But there you have to know what you are reading and construct a format specifier to match. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From washakie at gmail.com Thu Sep 8 12:10:48 2011 From: washakie at gmail.com (John) Date: Thu, 8 Sep 2011 12:10:48 +0200 Subject: [Tutor] understanding **kwargs syntax In-Reply-To: References: Message-ID: Following up on this... Why does pylint seem to think it is a bad idea? Description Resource Path Location Type ID:W0142 plot_ts_array_split_x: Used * or ** magic tsplot.py /research.plot line 299 PyLint Problem Thanks, john On Thu, Aug 25, 2011 at 10:44 AM, Alan Gauld wrote: > On 25/08/11 09:27, John wrote: >> >> Just a quick question, >> >> is it wrong to use the *args and **kwargs ( the latter in particular) >> when DEFINING a function? > > No, in fact it's essential if you don't know in advance what arguments are > going to be passed to the function. This is very common if you are wrapping > another function that itself takes variable arguments. > >> def fest(**kwargs): >> ? ? """ a function test """ >> ? ? keys = sorted(kwargs.keys()) >> >> ? ? print("You provided {0} keywords::\n".format(len(keys))) >> ? ? for kw in keys: >> ? ? ? ? print("{0} => ?{1}".format(kw, kwargs[kw])) >> >> Are there some good examples of when this would be a good idea to >> implement? > > GUI frameworks like Tkinter often take variable numbers of configuration > values. If you want to wrap that with a > function of your own you can do something like(pseudocode): > > def myfunc(**kwargs): > ? if some interesting arg exists > ? ? ? ?do something with it > ? return wrappedFunc(kwargs) > > There are plenty other cases, try grepping the standard library code > for lines with def and **kwargs for some examples... > > -- > Alan G > 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 > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 From rdmoores at gmail.com Thu Sep 8 12:58:37 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 8 Sep 2011 03:58:37 -0700 Subject: [Tutor] need advice about a dictionary ({}) Message-ID: I've succeeded in writing a dictionary ({}) that I can use as a small personal phone book. The dictionary (very shortened and simplified) looks like this in the script; p = {} p['bp1'] = 'xxx' p['bp2'] = 'ooo' p['ch'] = 'zzz' p['me'] = 'aaa' p['mg'] = 'vvv' p['pu1'] = 'bbb' p['pu2'] = 'ccc' p['pw'] = 'kkk' I have a function that enables the user to enter 'bp', for example, and return both 'xxx' and 'ooo'. (The keys are initials; I've disguised the values, each of which of course are name, home number, mobile number, speed dial number, etc.) But I'd like to put the lines of the dictionary in a text file so that I can add key/value items to it by writing to it with another script. I think I can do that, but I need some hints about how to get the script to access the text file in a way that lets the user look up a phone number. I'm thinking that the script needs to recreate the dictionary each time it's called, but I don't know how to do that. Thanks, Dick Moores From __peter__ at web.de Thu Sep 8 13:23:30 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 13:23:30 +0200 Subject: [Tutor] understanding **kwargs syntax References: Message-ID: John wrote: > Following up on this... > > Why does pylint seem to think it is a bad idea? > > Description Resource Path Location Type > ID:W0142 plot_ts_array_split_x: Used * or ** > magic tsplot.py /research.plot line 299 PyLint Problem I would guess it's a readability concern. Consider a simple function def f(x, y=0): print x + y for a in [1], "ab", "abc": f(*a) Can you tell what will be printed immediately? For me f(1) f("a", "b") f("a", "b", "c") is much easier to predict. That said, there are valid usecases for * and ** "magic", and of course pylint cannot take the tradeoffs into account. Therefore don't take pylint's warnings as gospel. PS: the exception is intentional From cwitts at compuscan.co.za Thu Sep 8 13:36:46 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 08 Sep 2011 13:36:46 +0200 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: <4E68A8CE.6030307@compuscan.co.za> On 2011/09/08 12:58 PM, Richard D. Moores wrote: > I've succeeded in writing a dictionary ({}) that I can use as a small > personal phone book. The dictionary (very shortened and simplified) > looks like this in the script; > > p = {} > > p['bp1'] = 'xxx' > p['bp2'] = 'ooo' > p['ch'] = 'zzz' > p['me'] = 'aaa' > p['mg'] = 'vvv' > p['pu1'] = 'bbb' > p['pu2'] = 'ccc' > p['pw'] = 'kkk' > > I have a function that enables the user to enter 'bp', for example, > and return both 'xxx' and 'ooo'. > > (The keys are initials; I've disguised the values, each of which of > course are name, home number, mobile number, speed dial number, > etc.) > > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. > I think I can do that, but I need some hints about how to get the > script to access the text file in a way that lets the user look up a > phone number. I'm thinking that the script needs to recreate the > dictionary each time it's called, but I don't know how to do that. > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You could pickle your dictionary object which will give you the persistence and then when your script starts up you can unpickle the file if it exists else create a new one. Of course if you make any changes to your object you'll need to pickle it once your app finishes otherwise new changes won't be written out. With just a plain text file you can also just grep the info out $ cat test.file bp1:xxx|yyy bp2:ooo|ppp ch:zzz|asf me:agkjh|agjh $ grep -i ^bp* test.file bp1:xxx|yyy bp2:ooo|ppp $ grep -i ^BP* test.file bp1:xxx|yyy bp2:ooo|ppp -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Thu Sep 8 13:41:18 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 8 Sep 2011 04:41:18 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: <4E68A8CE.6030307@compuscan.co.za> References: <4E68A8CE.6030307@compuscan.co.za> Message-ID: On Thu, Sep 8, 2011 at 04:36, Christian Witts wrote: > On 2011/09/08 12:58 PM, Richard D. Moores wrote: > > I've succeeded in writing a dictionary ({}) that I can use as a small > personal phone book. The dictionary (very shortened and simplified) > looks like this in the script; > > p = {} > > p['bp1'] = 'xxx' > p['bp2'] = 'ooo' > p['ch'] = 'zzz' > p['me'] = 'aaa' > p['mg'] = 'vvv' > p['pu1'] = 'bbb' > p['pu2'] = 'ccc' > p['pw'] = 'kkk' > > I have a function that enables the user to enter 'bp', for example, > and return both 'xxx' and 'ooo'. > > (The keys are initials; I've disguised the values, each of which of > course are name, home number, mobile number, speed dial number, > etc.) > > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. > I think I can do that, but I need some hints about how to get the > script to access the text file in a way that lets the user look up a > phone number. I'm thinking that the script needs to recreate the > dictionary each time it's called, but I don't know how to do that. > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > You could pickle your dictionary object which will give you the persistence > and then when your script starts up you can unpickle the file if it exists > else create a new one. Of course if you make any changes to your object > you'll need to pickle it once your app finishes otherwise new changes won't > be written out. > > With just a plain text file you can also just grep the info out > $ cat test.file > bp1:xxx|yyy > bp2:ooo|ppp > ch:zzz|asf > me:agkjh|agjh > $ grep -i ^bp* test.file > bp1:xxx|yyy > bp2:ooo|ppp > $ grep -i ^BP* test.file > bp1:xxx|yyy > bp2:ooo|ppp I should have stated that I'm using Win 7, Python 3.2.1. No Unix. Dick From __peter__ at web.de Thu Sep 8 13:43:34 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 13:43:34 +0200 Subject: [Tutor] need advice about a dictionary ({}) References: Message-ID: Richard D. Moores wrote: > I've succeeded in writing a dictionary ({}) that I can use as a small > personal phone book. The dictionary (very shortened and simplified) > looks like this in the script; > > p = {} > > p['bp1'] = 'xxx' > p['bp2'] = 'ooo' > p['ch'] = 'zzz' > p['me'] = 'aaa' > p['mg'] = 'vvv' > p['pu1'] = 'bbb' > p['pu2'] = 'ccc' > p['pw'] = 'kkk' > > I have a function that enables the user to enter 'bp', for example, > and return both 'xxx' and 'ooo'. > > (The keys are initials; I've disguised the values, each of which of > course are name, home number, mobile number, speed dial number, > etc.) > > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. > I think I can do that, but I need some hints about how to get the > script to access the text file in a way that lets the user look up a > phone number. I'm thinking that the script needs to recreate the > dictionary each time it's called, but I don't know how to do that. Start with a simple file format. If you don't allow "=" in the key and "\n" in either key or value bp1=xxx bp2=ooo ... pw=kkk should do. I suppose you know how to read a file one line at a time? Before you add the line into the dictionary you have to separate key and value (str.partition() may help with that) and remove the trailing newline from the value. If you need more flexibility look into the json module. This makes reading and writing the file even easier, and while the format is a bit more complex than key=value >>> print json.dumps(p, indent=2) { "me": "aaa", "mg": "vvv", "ch": "zzz", "pw": "kkk", "bp1": "xxx", "bp2": "ooo", "pu1": "bbb", "pu2": "ccc" } it can still be edited by a human. From steve at pearwood.info Thu Sep 8 14:51:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 22:51:00 +1000 Subject: [Tutor] how obsolete is 2.2? In-Reply-To: References: Message-ID: <4E68BA34.6080800@pearwood.info> c smith wrote: > Also, am I correct in thinking that 3.0 will always be called 3.0 but will > change over time and will always include experimental features, while 2.x > will gradually increase the 'x' and the highest 'x' will indicate the most > current, stable release? No, I'm afraid you are wrong. Python 2.7 is the last version in the 2.x series. It will continue to get bug fixes and security updates for the next few years, but no new features. 2.7 and 3.2 are the most up to date versions. As I said, 2.7 is the last of the 2.x line. 3.x is the future of Python, although 2.7 will be supported for quite some time. But all new features will be going into 3.x and 2.7 will only get bug fixes. Python 3.0 is no longer supported: to be frank, it was released too early, and it has too many bugs and is painfully slow. If you are using 3.0, you should update to 3.1 or 3.2, they are much, much better. -- Steven From lina.lastname at gmail.com Thu Sep 8 14:59:21 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 20:59:21 +0800 Subject: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0> Message-ID: Hi, what does the 0x7f8221a22cb0 mean here? the computer physical address. Thanks, -- Best Regards, lina From lina.lastname at gmail.com Thu Sep 8 15:02:45 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 21:02:45 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? Message-ID: Hi, I failed to understand the "collpase" meaning in a string. can someone give me a simple example? Sorry, -- Best Regards, lina From steve at pearwood.info Thu Sep 8 15:03:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 23:03:23 +1000 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: <4E68BD1B.6070509@pearwood.info> Richard D. Moores wrote: > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. If you expect human beings (yourself, or possibly even the user) to edit the text file, then you should look at a human-writable format like these: Good ol' fashioned Windows INI files: import configparser JSON: import json PLIST: import plistlib YAML: download from http://pyyaml.org/wiki/PyYAML If the ability to edit the files isn't important, then I suggest using the pickle module instead. -- Steven From rdmoores at gmail.com Thu Sep 8 15:40:24 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 8 Sep 2011 06:40:24 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Thu, Sep 8, 2011 at 04:43, Peter Otten <__peter__ at web.de> wrote: > Richard D. Moores wrote: > >> I've succeeded in writing a dictionary ({}) that I can use as a small >> personal phone book. The dictionary (very shortened and simplified) >> looks like this in the script; >> >> p = {} >> >> p['bp1'] = 'xxx' >> p['bp2'] = 'ooo' >> p['ch'] = 'zzz' >> p['me'] = 'aaa' >> p['mg'] = 'vvv' >> p['pu1'] = 'bbb' >> p['pu2'] = 'ccc' >> p['pw'] = 'kkk' >> >> I have a function that enables the user to enter 'bp', for example, >> and return both 'xxx' and 'ooo'. >> >> (The keys are initials; I've disguised the values, each of which of >> course are ? name, home number, mobile number, speed dial number, >> etc.) >> >> But I'd like to put the lines of the dictionary in a text file so that >> I can add key/value items to it by writing to it with another script. >> I think I can do that, but I need some hints about how to get ?the >> script to access the text file in a way that lets the user look up a >> phone number. I'm thinking that the script needs to recreate the >> dictionary each time it's called, but I don't know how to do that. > > Start with a simple file format. If you don't allow "=" in the key and "\n" > in either key or value > > bp1=xxx > bp2=ooo > ... > pw=kkk > > should do. I suppose you know how to read a file one line at a time? Before > you add the line into the dictionary you have to separate key and value > (str.partition() may help with that) and remove the trailing newline from > the value. If you need more flexibility look into the json module. This > makes reading and writing the file even easier, and while the format is a > bit more complex than key=value > >>>> print json.dumps(p, indent=2) > { > ?"me": "aaa", > ?"mg": "vvv", > ?"ch": "zzz", > ?"pw": "kkk", > ?"bp1": "xxx", > ?"bp2": "ooo", > ?"pu1": "bbb", > ?"pu2": "ccc" > } > > it can still be edited by a human. Thanks Peter! You made it a lot easier than I thought it would be. Please see for the script's current incarnation. The text of the demo data file is quoted in the script, lines 6-13. It doesn't seem I need to use the json module, though I want to learn it eventually. The data file very easily edited. However, as the number of lines gets large (maybe 100?) I'll need a way to determine if the new key is already in the file. So I'll be working on a script that I can use to safely add lines to the the file, by keeping all the keys unique. Dick From alan.gauld at btinternet.com Thu Sep 8 15:53:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 14:53:19 +0100 Subject: [Tutor] understanding **kwargs syntax In-Reply-To: References: Message-ID: On 08/09/11 11:10, John wrote: > Following up on this... > > Why does pylint seem to think it is a bad idea? > > Description Resource Path Location Type > ID:W0142 plot_ts_array_split_x: Used * or ** > magic tsplot.py /research.plot line 299 PyLint Problem I assume because it is a bad idea in most cases. If you know what the arguments are going to be then specify them. Otherwise you can get all sorts of rubbish being passed in that you have to figure out how to deal with. That's never a good place to be. But occasionally you have to do things that are less than ideal. And *args/**kwargs are useful in those situations, just don't use them unless you have to. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Thu Sep 8 15:52:25 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 8 Sep 2011 06:52:25 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Thu, Sep 8, 2011 at 04:43, Peter Otten <__peter__ at web.de> wrote: > Richard D. Moores wrote: > >> I've succeeded in writing a dictionary ({}) that I can use as a small >> personal phone book. The dictionary (very shortened and simplified) >> looks like this in the script; >> >> p = {} >> >> p['bp1'] = 'xxx' >> p['bp2'] = 'ooo' >> p['ch'] = 'zzz' >> p['me'] = 'aaa' >> p['mg'] = 'vvv' >> p['pu1'] = 'bbb' >> p['pu2'] = 'ccc' >> p['pw'] = 'kkk' >> >> I have a function that enables the user to enter 'bp', for example, >> and return both 'xxx' and 'ooo'. >> >> (The keys are initials; I've disguised the values, each of which of >> course are ? name, home number, mobile number, speed dial number, >> etc.) >> >> But I'd like to put the lines of the dictionary in a text file so that >> I can add key/value items to it by writing to it with another script. >> I think I can do that, but I need some hints about how to get ?the >> script to access the text file in a way that lets the user look up a >> phone number. I'm thinking that the script needs to recreate the >> dictionary each time it's called, but I don't know how to do that. > > Start with a simple file format. If you don't allow "=" in the key and "\n" > in either key or value > > bp1=xxx > bp2=ooo > ... > pw=kkk > > should do. I suppose you know how to read a file one line at a time? Before > you add the line into the dictionary you have to separate key and value > (str.partition() may help with that) and remove the trailing newline from > the value. If you need more flexibility look into the json module. This > makes reading and writing the file even easier, and while the format is a > bit more complex than key=value > >>>> print json.dumps(p, indent=2) > { > ?"me": "aaa", > ?"mg": "vvv", > ?"ch": "zzz", > ?"pw": "kkk", > ?"bp1": "xxx", > ?"bp2": "ooo", > ?"pu1": "bbb", > ?"pu2": "ccc" > } > > it can still be edited by a human. Thanks Peter! You made it a lot easier than I thought it would be. Please see for the script's current incarnation. The text of the demo data file is quoted in the script, lines 6-13. It doesn't seem I need to use the json module, though I want to learn it eventually. The data file very easily edited. However, as the number of lines gets large (maybe 100?) I'll need a way to determine if the new key is already in the file. So I'll be working on a script that I can use to safely add lines to the the file, by keeping all the keys unique. Dick From steve at pearwood.info Thu Sep 8 15:56:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 23:56:27 +1000 Subject: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0> In-Reply-To: References: Message-ID: <4E68C98B.5010106@pearwood.info> lina wrote: > Hi, > > > > > > what does the 0x7f8221a22cb0 mean here? the computer physical address. That's the ID of the list object, converted to hexadecimal. Every object in Python gets a unique (for the life of the object) ID. In CPython, the version you are using, that ID happens to be the memory address, and can be reused. For Jython and IronPython, the ID is an auto-incrementing counter, and will never be re-used: first object created gets ID 1 second object gets ID 2 third object gets ID 3 ... etc. -- Steven From steve at pearwood.info Thu Sep 8 15:58:21 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Sep 2011 23:58:21 +1000 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: Message-ID: <4E68C9FD.6060106@pearwood.info> lina wrote: > Hi, > > I failed to understand the "collpase" meaning in a string. > > can someone give me a simple example? > > Sorry, I don't understand what you mean. Can you give context? -- Steven From alan.gauld at btinternet.com Thu Sep 8 15:59:59 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 14:59:59 +0100 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: Message-ID: On 08/09/11 14:02, lina wrote: > Hi, > > I failed to understand the "collpase" meaning in a string. > > can someone give me a simple example? Can you give us some context? Its not a method of a string object so far as I can tell? Where did you read about it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 8 15:58:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 14:58:06 +0100 Subject: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0> In-Reply-To: References: Message-ID: On 08/09/11 13:59, lina wrote: > > > what does the 0x7f8221a22cb0 mean here? the computer physical address. It's a unique identifier for the object which is implementation dependant. In practice you can consider it the memory address. But I wouldn't try using it as an address by passing it into a C function say. That's not guaranteed to work at all! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Sep 8 16:03:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Sep 2011 15:03:33 +0100 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On 08/09/11 11:58, Richard D. Moores wrote: > I've succeeded in writing a dictionary ({}) that I can use as a small > personal phone book. The dictionary (very shortened and simplified) > looks like this in the script; > > p = {} > > p['bp1'] = 'xxx' > p['bp2'] = 'ooo' > p['ch'] = 'zzz' > p['me'] = 'aaa' > p['mg'] = 'vvv' > p['pu1'] = 'bbb' > p['pu2'] = 'ccc' > p['pw'] = 'kkk' > You could have done that in one line if you preferred: > p = { 'bp1':'xxx', 'bp2':'ooo' etc/... 'pw':'kkk' } > But I'd like to put the lines of the dictionary in a text file so that > I can add key/value items to it by writing to it with another script. Consider using a shelve (See the shelve module) It is basically a file that you can treat as a dictionary... Try: >>> import shelve >>> help(shelve) For examples and info. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jjhartley at gmail.com Thu Sep 8 16:08:07 2011 From: jjhartley at gmail.com (James Hartley) Date: Thu, 8 Sep 2011 07:08:07 -0700 Subject: [Tutor] throwing exception across modules? Message-ID: This is more a design question. One lesson C++ programmers might learn is that throwing exceptions from within library code is fraught with problems because the internals of exception handling were spelled out in the C++ standard. This manifests itself as problems when the library was compiled with one vendor's compiler, but the user of the library is using another compiler. While I understand that Python doesn't suffer from this exact problem, are there other reasons that raising exceptions in a module only be caught by consumers of the module a bad idea? Any insight which can be shared would be most appreciated. Thanks. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Sep 8 16:11:37 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 22:11:37 +0800 Subject: [Tutor] a quick Q: built-in method pop of list object at 0x7f8221a22cb0> In-Reply-To: References: Message-ID: Thanks, this is very informative. open some windows for me. On Thu, Sep 8, 2011 at 9:58 PM, Alan Gauld wrote: > On 08/09/11 13:59, lina wrote: >> >> >> >> what does the 0x7f8221a22cb0 mean here? the computer physical address. > > It's a unique identifier for the object which is implementation dependant. > In practice you can consider it the memory address. > > But I wouldn't try using it as an address by passing it into a > C function say. That's not guaranteed to work at all! > > > -- > Alan G > 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 > -- Best Regards, lina From lina.lastname at gmail.com Thu Sep 8 16:16:53 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 22:16:53 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: Message-ID: On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld wrote: > On 08/09/11 14:02, lina wrote: >> >> Hi, >> >> I failed to understand the "collpase" meaning in a string. >> >> can someone give me a simple example? > > Can you give us some context? > Its not a method of a string object so far as I can tell? > Where did you read about it? >From "dive into python", http://diveintopython.org/ one example: def info(object, spacing=10, collapse=1): """Print methods and docs strings. Take modules, class, list, dictionary, or strong.""" methodList = [e for e in dir(object) if callable(getattr(object, e))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print "\n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList]) if __name__ == "__main__": print info.__doc__ I felt so hard to understand the collapse, Please don't discourage me telling me it's an old book, To me I started reading till 42 pages. let me finish it. I used to study python on and off, sometimes give a whole week, but due to not using it, so it's frustrating that when I really needed it, I barely could complete one. > > -- > Alan G > 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 > -- Best Regards, lina From steve at pearwood.info Thu Sep 8 16:34:29 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 00:34:29 +1000 Subject: [Tutor] throwing exception across modules? In-Reply-To: References: Message-ID: <4E68D275.4090205@pearwood.info> James Hartley wrote: > This is more a design question. > > One lesson C++ programmers might learn is that throwing exceptions from > within library code is fraught with problems because the internals of > exception handling were spelled out in the C++ standard. This manifests Do you mean "weren't spelled out"? > itself as problems when the library was compiled with one vendor's compiler, > but the user of the library is using another compiler. > > While I understand that Python doesn't suffer from this exact problem, are > there other reasons that raising exceptions in a module only be caught by > consumers of the module a bad idea? Not at all. Python is designed to use exceptions as the primary error mechanism. Nearly every module and function you will use in Python will use exceptions to signal errors. A few will also use exceptions to signal non-error exceptional cases, e.g. StopIteration is used by iterators when they run out of items. Exceptions in Python aren't bolted on the top, they are fundamental to the way the language works. Even things like for loops work by catching exceptions. > Any insight which can be shared would be most appreciated. The only thing which sometimes catches out beginners is that they forget to use fully-qualified names for exceptions. E.g. you may need to do this: import socket try: ... except socket.error: ... instead of just "except error". If possible, document which exceptions your code might throw. At least, document which exceptions you expect to throw under normal circumstances. An exception in the top level of your module will be treated as fatal: it will prevent the module from being imported. (When I say fatal, I mean fatal for your module, not the caller: the caller can always catch the exception and skip the import.) Think carefully about what exceptions you should use. Try to integrate with the standard Python exception hierarchy. See the docs for further details. It's a matter of opinion whether you should use built-in exceptions as-is, or whether you subclass them. Subclassing can be as simple as: class StatsError(ValueError): pass or as complicated as you want. But in general, keep exceptions simple. Try not to raise private exceptions where the caller will see them. In other words, if you define a private exception type by flagging the name with a leading single underscore: class _InternalUseOnly(TypeError): # single underscore means "private" pass then never raise it unless you also catch it. -- Steven From andreengels at gmail.com Thu Sep 8 16:36:13 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 8 Sep 2011 16:36:13 +0200 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: Message-ID: On Thu, Sep 8, 2011 at 4:16 PM, lina wrote: > On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld > wrote: > > On 08/09/11 14:02, lina wrote: > >> > >> Hi, > >> > >> I failed to understand the "collpase" meaning in a string. > >> > >> can someone give me a simple example? > > > > Can you give us some context? > > Its not a method of a string object so far as I can tell? > > Where did you read about it? > > >From "dive into python", > > http://diveintopython.org/ > > one example: > > def info(object, spacing=10, collapse=1): > """Print methods and docs strings. > > Take modules, class, list, dictionary, or strong.""" > methodList = [e for e in dir(object) if callable(getattr(object, e))] > processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: > s) > print "\n".join(["%s %s" % > (method.ljust(spacing), > processFunc(str(getattr(object, method).__doc__))) > for method in methodList]) > > if __name__ == "__main__": > print info.__doc__ > > I felt so hard to understand the collapse, > > Please don't discourage me telling me it's an old book, > To me I started reading till 42 pages. let me finish it. > > I used to study python on and off, > sometimes give a whole week, but due to not using it, > so > it's frustrating that when I really needed it, I barely could complete one. > Reading this, it seems that 'collapse' is a variable defined somewhere else in the code. -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Sep 8 16:48:07 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 8 Sep 2011 10:48:07 -0400 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: Message-ID: On Thu, Sep 8, 2011 at 10:36 AM, Andre Engels wrote: > On Thu, Sep 8, 2011 at 4:16 PM, lina wrote: > >> On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld >> wrote: >> > On 08/09/11 14:02, lina wrote: >> >> >> >> Hi, >> >> >> >> I failed to understand the "collpase" meaning in a string. >> >> >> >> can someone give me a simple example? >> > >> > Can you give us some context? >> > Its not a method of a string object so far as I can tell? >> > Where did you read about it? >> >> >From "dive into python", >> >> http://diveintopython.org/ >> >> one example: >> >> def info(object, spacing=10, collapse=1): >> """Print methods and docs strings. >> >> Take modules, class, list, dictionary, or strong.""" >> methodList = [e for e in dir(object) if callable(getattr(object, e))] >> processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda >> s: s) >> print "\n".join(["%s %s" % >> (method.ljust(spacing), >> processFunc(str(getattr(object, method).__doc__))) >> for method in methodList]) >> >> if __name__ == "__main__": >> print info.__doc__ >> >> I felt so hard to understand the collapse, >> >> Please don't discourage me telling me it's an old book, >> To me I started reading till 42 pages. let me finish it. >> >> I used to study python on and off, >> sometimes give a whole week, but due to not using it, >> so >> it's frustrating that when I really needed it, I barely could complete >> one. >> > > Reading this, it seems that 'collapse' is a variable defined somewhere else > in the code. > > -- > Andr? Engels, andreengels at gmail.com > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > collapse is a function that Mark must have described earlier in the chapter you are working on. Are you using the online version? which chapter -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Sep 8 16:50:09 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 8 Sep 2011 10:50:09 -0400 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: Message-ID: On Thu, Sep 8, 2011 at 10:48 AM, Joel Goldstick wrote: > > On Thu, Sep 8, 2011 at 10:36 AM, Andre Engels wrote: > >> On Thu, Sep 8, 2011 at 4:16 PM, lina wrote: >> >>> On Thu, Sep 8, 2011 at 9:59 PM, Alan Gauld >>> wrote: >>> > On 08/09/11 14:02, lina wrote: >>> >> >>> >> Hi, >>> >> >>> >> I failed to understand the "collpase" meaning in a string. >>> >> >>> >> can someone give me a simple example? >>> > >>> > Can you give us some context? >>> > Its not a method of a string object so far as I can tell? >>> > Where did you read about it? >>> >>> >From "dive into python", >>> >>> http://diveintopython.org/ >>> >>> one example: >>> >>> def info(object, spacing=10, collapse=1): >>> """Print methods and docs strings. >>> >>> Take modules, class, list, dictionary, or strong.""" >>> methodList = [e for e in dir(object) if callable(getattr(object, e))] >>> processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda >>> s: s) >>> print "\n".join(["%s %s" % >>> (method.ljust(spacing), >>> processFunc(str(getattr(object, method).__doc__))) >>> for method in methodList]) >>> >>> if __name__ == "__main__": >>> print info.__doc__ >>> >>> I felt so hard to understand the collapse, >>> >>> Please don't discourage me telling me it's an old book, >>> To me I started reading till 42 pages. let me finish it. >>> >>> I used to study python on and off, >>> sometimes give a whole week, but due to not using it, >>> so >>> it's frustrating that when I really needed it, I barely could complete >>> one. >>> >> >> Reading this, it seems that 'collapse' is a variable defined somewhere >> else in the code. >> >> -- >> Andr? Engels, andreengels at gmail.com >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> collapse is a function that Mark must have described earlier in the > chapter you are working on. Are you using the online version? which chapter > > I spoke too soon. collapse is a boolean variable that you set if you want > to have the code in the lamda function collapse the text. If it is False > then the statement returns false instead of whatever is going on in the > Lambda > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Sep 8 16:56:54 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 00:56:54 +1000 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: Message-ID: <4E68D7B6.1050705@pearwood.info> lina wrote: > one example: > > def info(object, spacing=10, collapse=1): > """Print methods and docs strings. > > Take modules, class, list, dictionary, or strong.""" > methodList = [e for e in dir(object) if callable(getattr(object, e))] > processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) > print "\n".join(["%s %s" % > (method.ljust(spacing), > processFunc(str(getattr(object, method).__doc__))) > for method in methodList]) In this example, "collapse" is used as the name of an argument which takes a true/false flag. If collapse is true, runs of whitespace is collapsed into a single space: "hello world" => "hello world" The above function would be much easier to understand if it was written like this: def info(object, spacing=10, collapse=1): """Print methods and docs strings. Take modules, class, list, dictionary, or string. """ method_names = [] doc_strings = [] for name in dir(object): attribute = getattr(object, name) if callable(attribute): method_names.append(name.ljust(spacing)) doc_strings.append(str(attribute.__doc__)) if collapse: doc_strings = [" ".join(doc.split()) for doc in doc_strings] parts = ["%s %s" % (n, d) for n,d in zip(method_names, doc_strings)] print "\n".join(parts) Much longer, but easier to follow for a beginner. -- Steven From lina.lastname at gmail.com Thu Sep 8 16:59:12 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 22:59:12 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: Message-ID: <... ... > >> collapse is a function that Mark must have described earlier in the >> chapter you are working on.? Are you using the online version? which chapter >> http://diveintopython.org/power_of_introspection/optional_arguments.html >> I spoke too soon.? collapse is a boolean variable that you set if you want >> to have the code in the lamda function collapse the text.? If it is False collapse the text means? destory the text? make it collapse? Thanks, >> then the statement returns false instead of whatever is going on in the >> Lambda > > > -- > Joel Goldstick > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Best Regards, lina From steve at pearwood.info Thu Sep 8 17:03:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 01:03:33 +1000 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: Message-ID: <4E68D945.9010701@pearwood.info> lina wrote: > collapse the text means? destory the text? make it collapse? Collapse runs of spaces into a single space. -- Steven From lina.lastname at gmail.com Thu Sep 8 17:08:31 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 23:08:31 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: <4E68D945.9010701@pearwood.info> References: <4E68D945.9010701@pearwood.info> Message-ID: On Thu, Sep 8, 2011 at 11:03 PM, Steven D'Aprano wrote: > lina wrote: > >> collapse the text means? destory the text? make it collapse? > > Collapse runs of spaces into a single space. That's what I want, thanks. ^_^ > > > > -- > Steven > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From marc.tompkins at gmail.com Thu Sep 8 17:17:05 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 8 Sep 2011 08:17:05 -0700 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: <4E68D945.9010701@pearwood.info> Message-ID: On Thu, Sep 8, 2011 at 8:08 AM, lina wrote: > On Thu, Sep 8, 2011 at 11:03 PM, Steven D'Aprano > wrote: > > lina wrote: > > > >> collapse the text means? destory the text? make it collapse? > > > > Collapse runs of spaces into a single space. > > That's what I want, thanks. ^_^ > Be aware that that meaning of "collapse" is not a standard Python term - it's just the word that the author chose to describe this function. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Sep 8 17:35:49 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 8 Sep 2011 23:35:49 +0800 Subject: [Tutor] a quick Q: what does the "collapse" mean? In-Reply-To: References: <4E68D945.9010701@pearwood.info> Message-ID: On Thu, Sep 8, 2011 at 11:17 PM, Marc Tompkins wrote: > On Thu, Sep 8, 2011 at 8:08 AM, lina wrote: >> >> On Thu, Sep 8, 2011 at 11:03 PM, Steven D'Aprano >> wrote: >> > lina wrote: >> > >> >> collapse the text means? destory the text? make it collapse? >> > >> > Collapse runs of spaces into a single space. >> >> That's what I want, thanks. ?^_^ > > Be aware that that meaning of "collapse" is not a standard Python term - > it's just the word that the author chose to describe this function. Thanks for reminding. Sometimes it's not so easy to realize which part I should focus to understand well. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Best Regards, lina From __peter__ at web.de Thu Sep 8 17:51:58 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 08 Sep 2011 17:51:58 +0200 Subject: [Tutor] a quick Q: what does the "collapse" mean? References: <4E68D7B6.1050705@pearwood.info> Message-ID: Steven D'Aprano wrote: > lina wrote: > >> one example: >> >> def info(object, spacing=10, collapse=1): >> """Print methods and docs strings. >> >> Take modules, class, list, dictionary, or strong.""" >> methodList = [e for e in dir(object) if callable(getattr(object, e))] >> processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda >> s: s) print "\n".join(["%s %s" % >> (method.ljust(spacing), >> processFunc(str(getattr(object, method).__doc__))) >> for method in methodList]) > > > In this example, "collapse" is used as the name of an argument which > takes a true/false flag. If collapse is true, runs of whitespace is > collapsed into a single space: > > "hello world" => "hello world" > > The above function would be much easier to understand if it was written > like this: > > def info(object, spacing=10, collapse=1): > """Print methods and docs strings. > > Take modules, class, list, dictionary, or string. > """ > method_names = [] > doc_strings = [] > for name in dir(object): > attribute = getattr(object, name) > if callable(attribute): > method_names.append(name.ljust(spacing)) > doc_strings.append(str(attribute.__doc__)) > if collapse: > doc_strings = [" ".join(doc.split()) for doc in doc_strings] > parts = ["%s %s" % (n, d) for n,d in zip(method_names, doc_strings)] > print "\n".join(parts) > > > > Much longer, but easier to follow for a beginner. Or even def info(object, spacing=10, collapse=True): for name in dir(object): attribute = getattr(object, name) if callable(attribute): doc = str(attribute.__doc__) if collapse: doc = " ".join(doc.split()) print name.ljust(spacing), doc From eire1130 at gmail.com Thu Sep 8 18:17:25 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 8 Sep 2011 12:17:25 -0400 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Thu, Sep 8, 2011 at 10:03 AM, Alan Gauld wrote: > On 08/09/11 11:58, Richard D. Moores wrote: > >> I've succeeded in writing a dictionary ({}) that I can use as a small >> personal phone book. The dictionary (very shortened and simplified) >> looks like this in the script; >> >> p = {} >> >> p['bp1'] = 'xxx' >> p['bp2'] = 'ooo' >> p['ch'] = 'zzz' >> p['me'] = 'aaa' >> p['mg'] = 'vvv' >> p['pu1'] = 'bbb' >> p['pu2'] = 'ccc' >> p['pw'] = 'kkk' >> >> > You could have done that in one line if you preferred: > > > p = { > 'bp1':'xxx', > 'bp2':'ooo' > etc/... > 'pw':'kkk' > > } > > > But I'd like to put the lines of the dictionary in a text file so that >> I can add key/value items to it by writing to it with another script. >> > > Consider using a shelve (See the shelve module) > It is basically a file that you can treat as a dictionary... > > Try: > > >>> import shelve > >>> help(shelve) > > For examples and info. > > > -- > Alan G > 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 > Another option would be for you to use XML and base it off of a schema. There's a really nifty tool called generate DS (just google it) that will turn any valid schema into a python module. I pasted an example schema that you might use here: http://pastebin.com/AVgVGpgu Once you install generateds, just cd to where it is installed and type: python generateds.py -o pn.py PhoneNumber.xsd This assumes you named the above schema as PhoneNumber.xsd That will create a file called pn.py. For some reason it generated a bad line on line 452, which I just commented out. I then made a script in just a few lines to make a phonebook: http://pastebin.com/h4JB0MkZ This outputs XML that looks like this: > > aaa > > 1231231234 > > > > bbb > > 1231231234 > > > 6789231234 > > > > ccc > > 1231231234 > > > > ddd > > 1231231234 > > > The advantage is, you can immediately grab the generated xml and create python instances using the build() method for further editing. You would of course need to create a schema that fits your needs. Mine was just a quick and dirty example of what you could do. -------------- next part -------------- An HTML attachment was scrubbed... URL: From thisisonlyatest at gmx.com Fri Sep 9 04:31:40 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Thu, 08 Sep 2011 22:31:40 -0400 Subject: [Tutor] Tkinter Entry field text Message-ID: <4E697A8C.1030106@gmx.com> How do you display text in a Entry field and have it disappear when a person clicks in it? This is what I have so far: from Tkinter import * root = Tk() root.title("Password Changer") root.geometry("300x300+600+250") label1 = Label(root, text="Enter you password: ") label1.grid(sticky=W, row=0, column=0) enter_data1 = Entry(root, bg = "pale green") enter_data1.grid(row=0, column=1) enter_data1.insert(0, "password") root.mainloop() To get text into this box the person must first delete what is already in there. Python 2.6.6 From ryan.strunk at gmail.com Fri Sep 9 04:39:47 2011 From: ryan.strunk at gmail.com (Ryan Strunk) Date: Thu, 8 Sep 2011 21:39:47 -0500 Subject: [Tutor] Flat is better than Nested Message-ID: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> Hello everyone, I am still learning to program by writing this boxing game. I'm running into a problem with how to organize data. My current setup looks something like this: """This feels incredibly disgusting to me.""" self.behaviors = { 'offensive_combos': { 'combo1': { 1: { #time in seconds 'punch': { 'speed': 2, 'strength': 4, 'side': 'left'} } 1.5: { #time in seconds 'punch': { 'speed': 4, 'strength': 8, 'side': 'right'} } } } } By the time I write this all into a file, the end user will never even know this crazy hierarchy exists, but I will, and I don't like it. Do I just need to get over it and realize that sometimes nested is necessary, or is there a better way I might consider? Thanks for any help you can provide. Best, Ryan From steve at pearwood.info Fri Sep 9 06:28:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 14:28:46 +1000 Subject: [Tutor] Flat is better than Nested In-Reply-To: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> References: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> Message-ID: <4E6995FE.1010009@pearwood.info> Ryan Strunk wrote: > Hello everyone, > I am still learning to program by writing this boxing game. I'm running into > a problem with how to organize data. My current setup looks something like > this: > """This feels incredibly disgusting to me.""" You might find it a little less disgusting with the application of some helper classes and a slightly different data format. Combos probably should be treated as a sequence of moves. For simplicity, I'm going to assume each move takes the same time, and once a combo is entered, the opponent can't interrupt it. You may want to make it more complicated/realistic. The hard part is deciding what fields you need. Here's my guess: class Move: def __init__(self, speed, strength, side, purpose, kind, foul=False): self.speed = speed self.strength = strength self.side = side self.purpose = purpose self.kind = kind self.foul = foul CENTRE = NEUTRAL = '' LEFT, RIGHT = 'left right'.split() ATTACK, DEFENSE = 'attack defense'.split() right_cross = Move(2, 3, RIGHT, ATTACK, 'punch') left_lead = Move(3, 4, LEFT, ATTACK, 'punch') left_jab = Move(1, 1, LEFT, ATTACK, 'punch') headbutt = Move(1, 3, CENTRE, ATTACK, 'headbutt', True) step_in = Move(2, 0, NEUTRAL, NEUTRAL, 'footwork') weave = Move(1, 0, NEUTRAL, DEFENSE, 'footwork') rabbit_punch = Move(1, 2, CENTRE, ATTACK, 'punch', True) class Combo: def __init__(self, *moves): self.moves = moves old_one_two = Combo(left_lead, right_cross) liverpool_kiss = Combo(step_in, headbutt) combos = { 1: old_one_two, 2: liverpool_kiss, 3: Combo(weave, weave, step_in, rabbit_punch), 4: Combo(left_jab, left_jab, left_jab, step_in, uppercut), } Does that help? -- Steven From quasipedia at gmail.com Fri Sep 9 09:08:23 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 9 Sep 2011 09:08:23 +0200 Subject: [Tutor] Flat is better than Nested In-Reply-To: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> References: <001f01cc6e99$be38b1e0$3aaa15a0$@gmail.com> Message-ID: <20110909090823.5ebb7a16@jabbar> On Thu, 8 Sep 2011 21:39:47 -0500 "Ryan Strunk" wrote: > By the time I write this all into a file, the end user will never > even know this crazy hierarchy exists, but I will, and I don't like > it. Do I just need to get over it and realize that sometimes nested > is necessary, or is there a better way I might consider? There are two different problem you should consider here. The first is the MODEL STRUCTURE of your player. A model is a representation of something, so you really can't change the model structure that much from reality, as what you want is truly the opposite: you want to have the model as close as possible to the "something" you are representing. The other element to consider is the way you MANIPULATE your model, and this is the level at which you can operate to make your life easier. An example might clarify: suppose you are writing a very detailed simulation of the universe, and in it you have to model a neutron in your right big toe: your model could be something huge in terms of nested levels: Universe --> Milky way --> Aplha quadrant --> Solar system --> Planet Earth --> Continent --> Country --> County --> City --> District --> Building --> Floor --> Flat --> Room --> Person --> Limb --> Toe --> Cell --> Molecule --> Atom --> Nucleus --> Neutron. Now, if your simulation needs to know about stellar systems, continents, and all the rest, you really WANT to maintain all the levels of the hierarchy, because putting neutrons "flat" together with galaxies would make truly hard to write sane code. What you have to ask yourself is how you are going to manipulate your data. For example: when you are considering your neutron collisions with nearby subatomic particles do you really need to know about what galaxy your neutron is in? Probably not: all you need to know is about the nucleus of your atom. And when you are calculating the time a planet takes to go around it's star, do you really need to know about people living on it? Again: probably not. The trick for you would be to break down your hierarchy in sensible chunks, attaching to each bit of it the parts of code that are relevant at that resolution. So you could have a class "Nucleus", that knows about its parent molecule and its children particles and have methods like "get_atomic_number()", "decay()" or "bond_with()". And another class called "StellarSystem" knowing about its galaxy quadrant, its star(s) and its planet(s), having methods like "calculate_revolution()", "collapse()", etc... This is really what OOP is all about: you creating semi-independent objects which include only the information and methods needed at the level you are using them. Incidentally this won't only make things EASIER, it will also make them more FLEXIBLE/EASY-TO-MAINTAIN. Still working with the universe example: say that at some point (after you already wrote the code for planet Earth) you realise that other planets indeed are not organised in countries/counties/cities... If whenever you referred to an element in your simulation you included its entire hierarchy, you will be in trouble: you will have to modify your code everywhere you referred to something smaller than a planet. If you contrarily broke down your hierarchy and discover that on Alpha Prime they don't have administrative regions but just cities, all you will have to to is creating a new sister class "PlanetNoBorders" for the one ("PlanetWithRegions") that you used for the Earth, then you will be able to attach to it instantiations of the same City() class that you already used for planet Earth. In OOP this is called "programming to an interface", meaning that your code should ignore the real STRUCTURE of your data (the MODEL) and contrarily only know on how to MANIPULATE that data. Still using the universe example: if you need to access the list of cities on planets, you should make sure a "list_cities()" method is available both in "PlanetOriginal()" and "PlanetNoAdminBorders()" classes, and that they return data in the same format. You can then safely ignore if that specifc planet has or doesn't have countries on it. HTH, /mac From 132zed at gmail.com Fri Sep 9 12:10:59 2011 From: 132zed at gmail.com (Stu Rocksan) Date: Fri, 9 Sep 2011 05:10:59 -0500 Subject: [Tutor] _init_() arguments Message-ID: I have a very basic question that I am sure has a simple answer. I would be very appreciative of anyone that would set me straight. Python 2.7.2 I am simply trying to pass arguments. Based on the documentation that I've read so far _init_() is called upon instance creation and the arguments are those passed to the class constructor expression. That all makes sense to me but the problem is when I try to actually pass the argument. I get an TypeError that states "This constructor takes no arguments." Even using code direct from the tutorials included in the documentation gives me the same error. I doubt that there would be bad code coming direct from the official website...right? So the problem must be me. Example: class Complex: def _init_(self, realpart, imagpart) self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) x.r, x.i # theoretical output (3.0, -4.5) This is taken direct from the tutorial included in the documentation dated September 8, 2011. If you try to run this you will get a TypeError: this constructor takes no arguments. It even says in the explanation before this code: Of course, the __init__() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__(). I've tried similar code from other beginner Python books and I get the exact same result. I am sure that I am missing something simple. Thanks in advance From cwitts at compuscan.co.za Fri Sep 9 12:26:30 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 09 Sep 2011 12:26:30 +0200 Subject: [Tutor] _init_() arguments In-Reply-To: References: Message-ID: <4E69E9D6.7050509@compuscan.co.za> On 2011/09/09 12:10 PM, Stu Rocksan wrote: > I have a very basic question that I am sure has a simple answer. I > would be very appreciative of anyone that would set me straight. > > Python 2.7.2 > > I am simply trying to pass arguments. Based on the documentation that > I've read so far _init_() is called upon instance creation and the > arguments are those passed to the class constructor expression. That > all makes sense to me but the problem is when I try to actually pass > the argument. I get an TypeError that states "This constructor takes > no arguments." > > Even using code direct from the tutorials included in the > documentation gives me the same error. I doubt that there would be > bad code coming direct from the official website...right? So the > problem must be me. > > Example: > > class Complex: > def _init_(self, realpart, imagpart) > self.r = realpart > self.i = imagpart > > x = Complex(3.0, -4.5) > x.r, x.i > # theoretical output > (3.0, -4.5) > > This is taken direct from the tutorial included in the documentation > dated September 8, 2011. If you try to run this you will get a > TypeError: this constructor takes no arguments. > > It even says in the explanation before this code: > Of course, the __init__() method may have arguments for greater > flexibility. In that case, arguments given to the class instantiation > operator are passed on to __init__(). > > I've tried similar code from other beginner Python books and I get the > exact same result. > > I am sure that I am missing something simple. Thanks in advance > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > __init__() has 2 underscores pre- and post-fixed. Your example will break because of that, and also you're missing a colon at the end of your `def` line. Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5) >>> class Complex2: ... def _init_(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x= Complex2(3.0, -4.5) Traceback (most recent call last): File "", line 1, in TypeError: this constructor takes no arguments -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From kitty.a1000 at gmail.com Fri Sep 9 12:44:10 2011 From: kitty.a1000 at gmail.com (kitty) Date: Fri, 9 Sep 2011 11:44:10 +0100 Subject: [Tutor] Get a single random sample Message-ID: Hi, I'm new to python and I have read through the tutorial on: http://docs.python.org/tutorial/index.html which was really good, but I have been an R user for 7 years and and am finding it difficult to do even basic things in python, for example I want to import my data (a tab-delimited .txt file) so that I can index and select a random sample of one column based on another column. my data has 2 columns named 'area' and 'change.dens'. In R I would just data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) #header =T gives colums their headings so that I can call each individually names(data) attach(data) Then to Index I would simply: subset<-change.dens[area<2000&area>700] # so return change.dens values that have corresponding 'area's of between 700 and 2000 then to randomly sample a value from that I just need to random<-sample(subset,1) My question is how do I get python to do this??? Sorry I know it is very basic but I just cant seem to get going, Thank you K. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Sep 9 14:19:35 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 22:19:35 +1000 Subject: [Tutor] _init_() arguments In-Reply-To: References: Message-ID: <4E6A0457.4060805@pearwood.info> Stu Rocksan wrote: > class Complex: > def _init_(self, realpart, imagpart) Special methods in Python have TWO underscores at the beginning and end. You need to call it __init__ rather than _init_. Also, are you aware that Python already includes a built-in complex type? >>> complex(1, 2) (1+2j) -- Steven From d at davea.name Fri Sep 9 14:24:01 2011 From: d at davea.name (Dave Angel) Date: Fri, 09 Sep 2011 08:24:01 -0400 Subject: [Tutor] Get a single random sample In-Reply-To: References: Message-ID: <4E6A0561.2090600@davea.name> On 09/09/2011 06:44 AM, kitty wrote: > Hi, > > I'm new to python and I have read through the tutorial on: > http://docs.python.org/tutorial/index.html > which was really good, but I have been an R user for 7 years and and am > finding it difficult to do even basic things in python, for example I want > to import my data (a tab-delimited .txt file) so that I can index and select > a random sample of one column based on another column. my data has > 2 columns named 'area' and 'change.dens'. > > In R I would just > > data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) > #header =T gives colums their headings so that I can call each individually > names(data) > attach(data) > > Then to Index I would simply: > subset<-change.dens[area<2000&area>700] # so return change.dens values that > have corresponding 'area's of between 700 and 2000 > > then to randomly sample a value from that I just need to > random<-sample(subset,1) > > > My question is how do I get python to do this??? > > Sorry I know it is very basic but I just cant seem to get going, > > Thank you > K. No, it's not basic. If that R fragment is self-contained, apparently R makes lots of assumptions about its enviroment. Python can handle all of this, but not so succinctly and not without libraries (modules). In particular, your problem would be addressed with the csv module and the random one. The following (untested) code might get you started. import csv, sys, os infilename = "path to file/Road.density.municipio.all.txt" infile = open(infilename, "r") incsv = csv.DictReader(infile, delimiter="\t") # \t is the tab character print incsv.fieldnames for index, item in enumerate(incsv): do-something-with-item item will be a dict representing one line of the file, each time through the loop. You can choose some of those with an if statement, and build a list of the dicts that are useful. You can combine some of these steps using things like list comprehensions, but it's easier to take it a step at a time and see what you've got. -- DaveA From steve at pearwood.info Fri Sep 9 14:44:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 22:44:43 +1000 Subject: [Tutor] Get a single random sample In-Reply-To: References: Message-ID: <4E6A0A3B.6080203@pearwood.info> kitty wrote: > I'm new to python and I have read through the tutorial on: > http://docs.python.org/tutorial/index.html > which was really good, but I have been an R user for 7 years and and am > finding it difficult to do even basic things in python, for example I want > to import my data (a tab-delimited .txt file) so that I can index and select > a random sample of one column based on another column. my data has > 2 columns named 'area' and 'change.dens'. > > In R I would just > > data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) > #header =T gives colums their headings so that I can call each individually > names(data) > attach(data) > > Then to Index I would simply: > subset<-change.dens[area<2000&area>700] # so return change.dens values that > have corresponding 'area's of between 700 and 2000 > > then to randomly sample a value from that I just need to > random<-sample(subset,1) > > > My question is how do I get python to do this??? Good question! This does look like something where R is easier to use than Python, especially with the table() function doing most of the work for you. Here's one way to do it in Python. # Open the file and read two tab-delimited columns. # Note that there is minimal error checking here. f = open('Road.density.municipio.all.txt') data = [] for row in f: if not row.strip(): # Skip blank lines. continue area, dens = row.split('\t') # Split into two columns at tab pair = (float(area), float(dens)) data.append(pair) f.close() # Close the file when done. # Select items with specified areas. subset = [pair for pair in data if 700 < pair[0] < 2000] # Get a single random sample. import random sample = random.choice(subset) # Get ten random samples, sampling with replacement. samples = [random.choice(subset) for i in range(10)] # Get ten random samples, without replacement. copy = subset[:] random.shuffle(copy) samples = copy[:10] -- Steven From __peter__ at web.de Fri Sep 9 14:49:09 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Sep 2011 14:49:09 +0200 Subject: [Tutor] Get a single random sample References: Message-ID: kitty wrote: > Hi, > > I'm new to python and I have read through the tutorial on: > http://docs.python.org/tutorial/index.html > which was really good, but I have been an R user for 7 years and and am > finding it difficult to do even basic things in python, for example I want > to import my data (a tab-delimited .txt file) so that I can index and > select a random sample of one column based on another column. my data has > 2 columns named 'area' and 'change.dens'. > > In R I would just > > data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) > #header =T gives colums their headings so that I can call each > #individually > names(data) > attach(data) > > Then to Index I would simply: > subset<-change.dens[area<2000&area>700] # so return change.dens values > that have corresponding 'area's of between 700 and 2000 > > then to randomly sample a value from that I just need to > random<-sample(subset,1) > > > My question is how do I get python to do this??? I don't know R, but I believe the following does what you want: import csv import random import sys from collections import namedtuple filename = "FILE PATH\\Road.density.municipio.all.txt" with open(filename, "rb") as f: rows = csv.reader(f, delimiter="\t") headers = next(rows) rowtype = namedtuple("RT", [h.replace(".", "_") for h in headers]) data = [rowtype(*map(float, row)) for row in rows] print data subset = [row for row in data if 700 < row.area < 2000] print random.choice(subset).area As you can see Python with just the standard library requires a lot more legwork than R. You might have a look at scipy/numpy, perhaps they offer functions that simplify your task. Finally, there's also http://rpy.sourceforge.net/ , but I've never tried that. From __peter__ at web.de Fri Sep 9 14:54:03 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Sep 2011 14:54:03 +0200 Subject: [Tutor] Get a single random sample References: <4E6A0A3B.6080203@pearwood.info> Message-ID: Steven D'Aprano wrote: > # Get ten random samples, sampling with replacement. > samples = [random.choice(subset) for i in range(10)] That may include subset items more than once. Use the aptly named random.sample(subset, 10) to avoid that. From __peter__ at web.de Fri Sep 9 15:03:02 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 09 Sep 2011 15:03:02 +0200 Subject: [Tutor] Get a single random sample References: <4E6A0A3B.6080203@pearwood.info> Message-ID: Peter Otten wrote: > Steven D'Aprano wrote: > >> # Get ten random samples, sampling with replacement. I can quote. But not read ;( >> samples = [random.choice(subset) for i in range(10)] Sorry for the noise. From steve at pearwood.info Fri Sep 9 15:06:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Sep 2011 23:06:33 +1000 Subject: [Tutor] Get a single random sample In-Reply-To: References: <4E6A0A3B.6080203@pearwood.info> Message-ID: <4E6A0F59.80500@pearwood.info> Peter Otten wrote: > Steven D'Aprano wrote: > >> # Get ten random samples, sampling with replacement. >> samples = [random.choice(subset) for i in range(10)] > > That may include subset items more than once. Hence the "sampling with replacement" comment. > Use the aptly named > > random.sample(subset, 10) > > to avoid that. Ah, I didn't know that one! Nice. -- Steven From alan.gauld at btinternet.com Fri Sep 9 20:04:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Sep 2011 19:04:04 +0100 Subject: [Tutor] Get a single random sample In-Reply-To: References: Message-ID: On 09/09/11 11:44, kitty wrote: > ...I have been an R user for 7 years and and am > finding it difficult to do even basic things in python, If you are trying to do the kinds of things that R is good at in Python you will find it involves a lot more work. That's because Python is a general purpose programming language and R is a special purpose one, optimised to its task. You can do most things in Python but it can never compete with a specialised language in that language's area. On the other hand if you try writing networking applications or GUIs in R you will likely find that's harder than using Python. Choosing the right tool for the job is always a choice between a specialist tool or a general purpose one. If you do a specialised job a specialised tool is probably a better choice. > In R I would just > > data<-read.table("FILE PATH\\Road.density.municipio.all.txt", header=T) > names(data) > attach(data) > subset<-change.dens[area<2000&area>700] > random<-sample(subset,1) > > > My question is how do I get python to do this??? > > Sorry I know it is very basic but I just cant seem to get going, And there's the rub, it may be very basic in R but its quite a challenge in Python, you need to get into a lot more detail. But the good news is that there is an interface between Python and R - called RPy - that you can use to get the best of both worlds. Use Python for the general stuff and use RPy for the analytical work... You can get RPy here: http://rpy.sourceforge.net/rpy2.html And there is a simple introduction and comparison of R and Python benefits here: http://www.bytemining.com/2010/10/accessing-r-from-python-using-rpy2/ HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Sat Sep 10 16:16:20 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 10 Sep 2011 09:16:20 -0500 Subject: [Tutor] Tkinter Entry field text In-Reply-To: <4E697A8C.1030106@gmx.com> References: <4E697A8C.1030106@gmx.com> Message-ID: On Thu, Sep 8, 2011 at 9:31 PM, brandon w wrote: > How do you display text in a Entry field and have it disappear when a > person clicks in it? > To get text into this box the person must first delete > what is already in there. > > Python 2.6.6 > Think about the process. You're already mostly there: you're displaying data already, and you know what you want to do. You'll want to take a look at binding events, and if you Google for "tkinter events" (http://www.google.com/search?q=tkinter+events) then your first result takes you here: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm To point you in the right direction, you want to take a look at the event. If you're not familiar with what a callback is, you should also read this page: http://effbot.org/zone/tkinter-callbacks.htm If you still have problems after that, show us what else you've tried and we'll be happy to give you more pointers in the right direction. Of course, while this answers your questions, I would be remiss if I didn't suggest a few more things about your program in general. > label1 = Label(root, text="Enter you password: ") label1 isn't a terribly descriptive name. That's fine if you don't intend to actually do anything with the label. However, you can make this even more explicit by chaining the commands together. Since Label() returns a label, you can add a dot to the end and treat it just like you would the variable: Label(root, text="Enter you password: ").grid(sticky=W, row=0, column=0) That will create your label and stick it in the grid in one step, and makes it clear to anyone reading your code (including yourself down the road!) that you don't care to do anything with that label. Next: > enter_data1 = Entry(root, bg = "pale green") enter_data1 also suffers from the same naming problem. It doesn't describe what the variable is or does very well, aside from entering data. You could change it to something like "password_entry" - which tells anyone reading your program that the variable should contain something that lets you do some password entry. Just naming it password would also be better than enter_data1. One other issue that you should consider - with the options you have set, anyone could see what you typed in as your password. If you're just using this as a testing program to play around with, that's probably OK, but what's even better is to change what's shown in the box. You can do this by setting the "show" option, either in the constructor or somewhere later: from Tkinter import * root = Tk() entry = Entry(root) entry.pack() entry.insert(0, "My Cool Password") entry.config(show="*") root.mainloop() The nice thing about the config() method is that it allows you to change config attributes later. You can combine this knowledge with some of what I mentioned earlier to show 'password' until they navigate to the field, and then just show asterisks. For bonus points, if they leave the password field without typing a password, can you make it show 'password' again? HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Sat Sep 10 20:08:18 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 11:08:18 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: So I've done quite a bit more work. With phone_book.py the user can not only access phone numbers by the person's initials, but can add items to the data file. I've also solved the problem of adding a person who's initials have already been used in a key. I've pasted phone_book_for_pasting.py at . I'd appreciate any comments, instructive criticism, etc. Some have suggested using the shelve module. I looked at it but couldn't see in detail how to use it. If someone could write a short demo script, or send me to one that pretty much does what my phone_book.py does, that would be terrific. Dick Moores From walksloud at gmail.com Sat Sep 10 21:39:15 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sat, 10 Sep 2011 12:39:15 -0700 Subject: [Tutor] databases Message-ID: Hi All, I am completely new to databases as well as using python to access/create databases. I started googling about it and found so much info, I wasn't sure where to begin to answer my first question. So I thought I would query this group by asking a question I am sure has been asked before - but you all are so friendly, I thought I would give it a try. I have databases (many of them) which I want to manipulate, averaging data, merging databases, etc. Do I need to install separate modules to access the databases? Do I need to know the specific style the databases were created in to open manipulate them with python (2.7)? I ask this because with xml files, I was able to just use from xml.dom import minidom and then by trial and error in an interactive session, I could figure out how to walk through the xml file to find what I wanted. I am wondering if I can do something similar with a database, or if there are more pre-defined formats. I do not actually know what format my databases are in (someone else wrote the c-code to create them). While waiting for suggestions, I have started to read Alan Gauld's tutorial on the subject http://www.alan-g.me.uk/tutor/index.htm Thanks, Andre From jacktradespublic at gmail.com Sat Sep 10 21:42:04 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Sat, 10 Sep 2011 14:42:04 -0500 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 1:08 PM, Richard D. Moores wrote: > So I've done quite a bit more work. With phone_book.py the user can > not only access phone numbers by the person's initials, but can add > items to the data file. I've also solved the problem of adding a > person who's initials have already been used in a key. > > I've pasted phone_book_for_pasting.py at . > > I'd appreciate any comments, instructive criticism, etc. > > It looks pretty good overall, though I didn't examine it too closely. IMHO there are some awkward bits which I think come from your representation of the data. I would probably make the phonebook itself a list, with each entry being a dict. Something like: book = [ {'name':'Mark Sanders', 'cell':'422-318-2346', ' email':'msanders at stanfordalumni.org'}, {'name':'AAA', 'phone':'575-3992', 'phone2':'1-800-472-4630', 'notes':'Membership #422 260 0131863 00 8'}, #... ] Then you can easily search your phone book by name, email, type of contact, relation, etc. A search by name would look like this: def find_by_name(name): for entry in book: if entry['name'] == name: return entry find_by_name('Mark Sanders') #==> {'name':'Mark Sanders', 'cell':'422-318-2346', ' email':'msanders at stanfordalumni.org} or a more general procedure for doing searches on your book could be: def find(criteria, term): for entry in book: if entry[criteria] == term: return entry find('name', 'Mark Sanders') #==> {'name':'Mark Sanders', 'cell':'422-318-2346', ' email':'msanders at stanfordalumni.org} Similarly you could search for initials by providing a to_initials procedure: def to_initials(name): return ''.join([i[0] for i in name.split(' ')]) def find_by_initials(initials): for entry in book: if to_initials(entry['name']) == initials: return entry find_by_initials('MS') #==> {'cell': '422-318-2346', 'name': 'Mark Sanders', 'email': ' msanders at stanfordalumni.org'} Adding a new entry would then be as simple as: def add_new_entry(entry, book): book.append(entry) For storing data I would probably use Pickle, which would look something like this: from cPickle import load, dump f = open('book.pk', 'w') dump(book, f) f.close() and loading your book is similar f = open('book.pk', 'r') book = load(f) f.close() If you want a human readable storage format I would look into json, but pickle has served me well for most purposes. Surely you can store your phonebook as plain text and parse it the way you have, but it's not necessary to do that with all the tools that exist for that purpose. -- Nick Zarczynski Pointless Programming Blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Sat Sep 10 21:42:26 2011 From: eire1130 at gmail.com (James Reynolds) Date: Sat, 10 Sep 2011 15:42:26 -0400 Subject: [Tutor] databases In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 3:39 PM, Andre' Walker-Loud wrote: > Hi All, > > I am completely new to databases as well as using python to access/create > databases. I started googling about it and found so much info, I wasn't > sure where to begin to answer my first question. So I thought I would query > this group by asking a question I am sure has been asked before - but you > all are so friendly, I thought I would give it a try. > > I have databases (many of them) which I want to manipulate, averaging data, > merging databases, etc. > > Do I need to install separate modules to access the databases? > > Do I need to know the specific style the databases were created in to open > manipulate them with python (2.7)? I ask this because with xml files, I was > able to just use > > from xml.dom import minidom > > and then by trial and error in an interactive session, I could figure out > how to walk through the xml file to find what I wanted. I am wondering if I > can do something similar with a database, or if there are more pre-defined > formats. I do not actually know what format my databases are in (someone > else wrote the c-code to create them). > > > While waiting for suggestions, I have started to read Alan Gauld's tutorial > on the subject > > http://www.alan-g.me.uk/tutor/index.htm > > > > Thanks, > > Andre > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > What type of databases? sql server, mysql, sqllite? -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Sat Sep 10 21:44:14 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sat, 10 Sep 2011 12:44:14 -0700 Subject: [Tutor] databases In-Reply-To: References: Message-ID: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> > > What type of databases? sql server, mysql, sqllite? Hi James, well this already helps. I don't even know. Do I have to know ahead of time? Or is there a general database package that can open a databases without knowing there format? Thanks, Andre From rdmoores at gmail.com Sat Sep 10 23:36:07 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 14:36:07 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: Thanks so much, Jack. You've given me much to chew on. I began phone_book.py without much need for it -- I already had an RTF file with 786 lines that I "grepped" using a script I wrote with Tutor help long ago. I used an RTF file instead of a text file so that any URLs in it would be live. But I wanted to refresh what little I used to know about dicts and see where I could go with it. It turns out to be something I'll actually use for quickly looking up phone numbers of people (friends, relatives, doctors, etc.) and some businesses, and the occasional address. For adding key=value items to the data file, values can be copied as is from the RTF file. It'll probably have fewer than 100 entries. Your idea doesn't seem efficient for me -- lots of typing and editing. But very interesting! I'll probably have fewer than 100 entries. Your pickle examples give me a start on using the cPickle module. Dick From rdmoores at gmail.com Sat Sep 10 23:40:11 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 14:40:11 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: Thanks so much, Jack. You've given me much to chew on. I began phone_book.py without much need for it -- I already had an RTF file with 786 lines that I "grepped" using a script I wrote with Tutor help long ago. I used an RTF file instead of a text file so that any URLs in it would be live. But I wanted to refresh what little I used to know about dicts and see where I could go with it. It turns out to be something I'll actually use for quickly looking up phone numbers of people (friends, relatives, doctors, etc.) and some businesses, and the occasional address. For adding key=value items to the data file, values can be copied as is from the RTF file. It'll probably have fewer than 100 entries. Your idea doesn't seem efficient for me -- lots of typing and editing. But very interesting! I'll probably have fewer than 100 entries. Your pickle examples give me a start on using the cPickle module. Dick From rdmoores at gmail.com Sat Sep 10 23:58:40 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 14:58:40 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: Jack Trades (actually Nick Zarczynski) just sent me this link to a "Simple phone book app", and has agreed to let me post it to this thread: Dick From rafadurancastaneda at gmail.com Sun Sep 11 00:12:13 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Sun, 11 Sep 2011 00:12:13 +0200 Subject: [Tutor] databases In-Reply-To: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> References: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> Message-ID: <4E6BE0BD.9040803@gmail.com> On 10/09/11 21:44, Andre' Walker-Loud wrote: >> What type of databases? sql server, mysql, sqllite? > Hi James, > > well this already helps. I don't even know. Do I have to know ahead of time? Or is there a general database package that can open a databases without knowing there format? > > > Thanks, > > Andre > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You might look at http://www.sqlalchemy.org/, since it works with most databases. However if you are new on databases, I think you should start learning databases basics, choose a database management system (DBMS) that fit your needs and learn as much as you can about that specific DBMS. Then you can use SQLAlchemy or specific packagas (MySQL-Python, PyGreSQL,...) to acces to that DBMS. In addition if you are going to use frameworks, most of them already have their own tools for DB manipulation. From jacktradespublic at gmail.com Sun Sep 11 00:15:20 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Sat, 10 Sep 2011 17:15:20 -0500 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 4:36 PM, Richard D. Moores wrote: > Your idea doesn't seem efficient for me -- > lots of typing and editing. > Not sure what you mean by that? I've updated the gist with a quick 5min implementation of a GUI using Tkinter and the approach I outlined. I think using a GUI is best way to minimize "typing and editing" in an app like this. You can find it here: https://gist.github.com/1208786#file_book.py If you're talking about re-entering all your data from your file, you would write a script to do that. This program assumes that you are starting from scratch with a blank phone book. If you would like help converting your existing file, I'm sure I or others can help, but I'd need to see the original file. -- Nick Zarczynski Pointless Programming Blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Sep 11 00:24:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Sep 2011 23:24:54 +0100 Subject: [Tutor] databases In-Reply-To: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> References: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> Message-ID: On 10/09/11 20:44, Andre' Walker-Loud wrote: >> What type of databases? sql server, mysql, sqllite? > well this already helps. I don't even know. > Do I have to know ahead of time? Or is there a general database > package that can open a databases without knowing there format? The Python DB API is pretty good at covering all the common databases but sadly everyone has some slight variances so you do need to know which product you will be using. As an example the SQLite package that comes in the standard library - and is a good starter - doesn't require login credentials but Oracle, MySQL etc do. Also Sqllite is stored in a single file accessed via a code library whereas most other SQL databases use multiple files and a server frontend. (That's why there's a connect() function - to connect to the server... in SQLite connect just opens the file!) If you are a database noob I'd keep it simple and stick with SQLite, it's powerful enough for most beginner type projects and misses out some of the more complex features of the other packages. Provided you aren't expecting to scale up to 10's of millions of records it will do just fine. Once you understand SQLite moving to MySQL or Firebird or whatever will be an easy next step. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From achompas at gmail.com Sun Sep 11 00:28:34 2011 From: achompas at gmail.com (Alejandro Companioni) Date: Sat, 10 Sep 2011 18:28:34 -0400 Subject: [Tutor] databases In-Reply-To: References: Message-ID: On Sep 10, 2011, at 6:15 PM, tutor-request at python.org wrote: > You might look at http://www.sqlalchemy.org/, since it works with most > databases. However if you are new on databases, I think you should start > learning databases basics, choose a database management system (DBMS) > that fit your needs and learn as much as you can about that specific > DBMS. Then you can use SQLAlchemy or specific packagas (MySQL-Python, > PyGreSQL,...) to acces to that DBMS. In addition if you are going to use > frameworks, most of them already have their own tools for DB manipulation. > Just wanted to chime in, because I wish someone had told me this sooner, but if you're using a Mac, try to steer clear of mysql-python. Setting it up on a Mac is absolutely infuriating. If your databases are MySQL-based and you're using a Mac, I'd recommend setting up a Linux VM to access them with Python (or not using Python at all). Good luck! -Alejandro -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Sep 11 00:32:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Sep 2011 23:32:11 +0100 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On 10/09/11 19:08, Richard D. Moores wrote: > Some have suggested using the shelve module. I looked at it but > couldn't see in detail how to use it. Did you read the help page? It says: import shelve d = shelve.open(filename) # open, with (g)dbm filename -- no suffix d[key] = data # store data at key data = d[key] # retrieve a COPY of the data at key del d[key] # delete data stored at key flag = d.has_key(key) # true if the key exists list = d.keys() # a list of all existing keys (slow!) d.close() # close it So you open the file and from that point on treat it exactly like a dictionary. Then close the file at the end. Now which part don't you understand? The ony bit that migt confuse is the mention of gdbm filename which just means give it a filename without any suffix...just ignore the gdbm reference. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Sun Sep 11 01:18:18 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 16:18:18 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 15:32, Alan Gauld wrote: > On 10/09/11 19:08, Richard D. Moores wrote: > >> Some have suggested using the shelve module. I looked at it but >> couldn't see in detail how to use it. > > Did you read the help page? I did. I can see it would be a useful reference once I learned from elsewhere how to use shelve. > It says: > > import shelve > d = shelve.open(filename) # open, with (g)dbm filename -- no suffix > > d[key] = data ? # store data at key > data = d[key] ? # retrieve a COPY of the data at key > del d[key] ? ? ?# delete data stored at key > flag = d.has_key(key) ? # true if the key exists > list = d.keys() # a list of all existing keys (slow!) > d.close() ? ? ? # close it > > > So you open the file and from that point on treat it exactly like a > dictionary. I'm still a bit shaky about dictionaries. > Then close the file at the end. > > Now which part don't you understand? Much of what comes after that is beyond me. > The ony bit that migt confuse is the mention of gdbm filename which just > means give it a filename without any suffix...just ignore the gdbm > reference. Thanks for your encouragement Alan, but I'm still looking among my Python books for a good exposition of shelve. Dick From walksloud at gmail.com Sun Sep 11 02:24:56 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sat, 10 Sep 2011 17:24:56 -0700 Subject: [Tutor] databases In-Reply-To: References: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> Message-ID: <4D6D29B3-701F-4B2F-B079-DBB0052BEA2B@gmail.com> > > package that can open a databases without knowing there format? > > The Python DB API is pretty good at covering all the common databases but sadly everyone has some slight variances so you do need to know which product you will be using. > > As an example the SQLite package that comes in the standard library - and is a good starter - doesn't require login credentials but Oracle, MySQL etc do. Also Sqllite is stored in a single file accessed via a code library whereas most other SQL databases use multiple files and a server frontend. (That's why there's a connect() function - to connect to the server... in SQLite connect just opens the file!) > > If you are a database noob I'd keep it simple and stick with SQLite, it's powerful enough for most beginner type projects and misses out some of the more complex features of the other packages. Provided you aren't expecting to scale up to 10's of millions of records it will do just fine. Once you understand SQLite moving to MySQL or Firebird or whatever will be an easy next step. So, in case I wasn't clear, the databases are already made by someone else, and the format is beyond my control. I need/want to learn to manipulate them. Most likely they are similar to the Berkeley database (but I don't know what this means yet). Thanks for the help, Andre From walksloud at gmail.com Sun Sep 11 02:26:48 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sat, 10 Sep 2011 17:26:48 -0700 Subject: [Tutor] databases In-Reply-To: References: Message-ID: >> You might look at http://www.sqlalchemy.org/, since it works with most >> databases. However if you are new on databases, I think you should start >> learning databases basics, choose a database management system (DBMS) >> that fit your needs and learn as much as you can about that specific >> DBMS. Then you can use SQLAlchemy or specific packagas (MySQL-Python, >> PyGreSQL,...) to acces to that DBMS. In addition if you are going to use >> frameworks, most of them already have their own tools for DB manipulation. >> > > Just wanted to chime in, because I wish someone had told me this sooner, but if you're using a Mac, try to steer clear of mysql-python. Setting it up on a Mac is absolutely infuriating. > > If your databases are MySQL-based and you're using a Mac, I'd recommend setting up a Linux VM to access them with Python (or not using Python at all). Good luck! Thanks for the warning Alejandro. Turns out, they live on a linux cluster - but I log in via a Mac, and likely will copy locally to play around with. I figured I could either hack the c++ code built already to manipulate them, or use this as an excuse to learn about databases via python. Andre From alan.gauld at btinternet.com Sun Sep 11 02:34:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Sep 2011 01:34:18 +0100 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On 11/09/11 00:18, Richard D. Moores wrote: >> So you open the file and from that point on treat it exactly like a >> dictionary. > > I'm still a bit shaky about dictionaries. But you started the post with using a dictionary. Shelve is just a dictionary that lives in a file instead of memory. If you can put data into or read it out of a dictionary then you can do the same with shelve. The only complexity is you have to open the file before sing it and close it when your done. > Much of what comes after that is beyond me. > Thanks for your encouragement Alan, but I'm still looking among my > Python books for a good exposition of shelve. You probably won't find much in books because shelve has such a specific purpose. As a result there isn't much to say about it if you've already covered dictionaries. It's a file based dictionary. So read up on dictionaries. Then just use it. There are a few limitations with shelve but for most normal cases you can ignore that and just use it like any normal dictionary. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Sun Sep 11 02:34:26 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 10 Sep 2011 17:34:26 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 4:18 PM, Richard D. Moores wrote: > On Sat, Sep 10, 2011 at 15:32, Alan Gauld > wrote: > > So you open the file and from that point on treat it exactly like a > > dictionary. > > I'm still a bit shaky about dictionaries. > > That right there is the salient bit. Using shelve is just like using a dictionary; probably that's why you're finding the documentation sparse: dictionaries are core Python, so they assume you know how to use them. ("First, catch your rabbit...") I was about to write an introduction to dictionaries, but I realized it's been done, and done better than I could. I really recommend that you learn them; I think that once you do, you'll find that they're a better fit in all sorts of places where you've been using lists. (Speaking from personal experience...) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Sep 11 02:41:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Sep 2011 01:41:35 +0100 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On 11/09/11 00:18, Richard D. Moores wrote: >> Now which part don't you understand? > > Much of what comes after that is beyond me. I meant to add, you can pretty much ignore all the stuff at the end of the Help page about class definitions. You only need that if you intend to create your own specialised Shelf object. All you need to know is in the pseudocode bit that I posted. open() the file use the shelf like a dictionary close() the file And there are two main caveats given: 1) Don't try to edit mutable data objects (lists) in place. Extract them, modify them and replace them 2) Don't use the writeback=True setting when you open large data sets. That's it. Alan G. From alan.gauld at btinternet.com Sun Sep 11 02:46:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Sep 2011 01:46:30 +0100 Subject: [Tutor] databases In-Reply-To: References: Message-ID: On 10/09/11 23:28, Alejandro Companioni wrote: > Just wanted to chime in, because I wish someone had told me this sooner, > but if you're using a Mac, try to steer clear of mysql-python. Setting > it up on a Mac is absolutely infuriating. I've never used MySql on a Mac but I'm curious why it should be so difficult. MacOS is just BSD Unix under the GUI so why would be any different to any other Unix type system? What were the problems that you encountered? > If your databases are MySQL-based and you're using a Mac, I'd recommend > setting up a Linux VM to access them with Python (or not using Python at > all). Good luck! Now that sounds like it should be much more difficult. You'd effectively be running a client server setup to a foreign OS on your own computer but sharing the physical resources... There must be something really weird about the MacOS setup to make that easier! I'm intrigued. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Sep 11 02:49:44 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 11 Sep 2011 01:49:44 +0100 (BST) Subject: [Tutor] databases In-Reply-To: <4D6D29B3-701F-4B2F-B079-DBB0052BEA2B@gmail.com> References: <896D17E8-298D-41C4-9C3E-E0F7AFB603F1@gmail.com> <4D6D29B3-701F-4B2F-B079-DBB0052BEA2B@gmail.com> Message-ID: <1315702184.64895.YahooMailRC@web86702.mail.ird.yahoo.com> > > package that can open a databases without knowing there format? > So, in case I wasn't clear, the databases are already made by someone else, > and the format is beyond my control. I need/want to learn to manipulate them. > OK, That wasn't clear. And it makes a difference. You need to know the format. > Most likely they are similar to the Berkeley database And that makes a much bigger difference because most folks assume by 'database' you mean a SQL database. Berkeley databases are flat file based and there is a module to read them in the Python library, but they don't use SQL. They are more like a random access file mechanism than a relational database. If that's what you are dealing with then it's a whole lot of different references you need. I'd start with wikipedia and the [g]dbm module documentation. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Sun Sep 11 03:28:40 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 18:28:40 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 17:34, Marc Tompkins wrote: > On Sat, Sep 10, 2011 at 4:18 PM, Richard D. Moores > wrote: >> >> On Sat, Sep 10, 2011 at 15:32, Alan Gauld >> wrote: >> >> > So you open the file and from that point on treat it exactly like a >> > dictionary. >> >> I'm still a bit shaky about dictionaries. >> > That right there is the salient bit.? Using shelve is just like using a > dictionary; probably that's why you're finding the documentation sparse: > dictionaries are core Python, so they assume you know how to use them. > ("First, catch your rabbit...") > > I was about to write an introduction to dictionaries, but I realized it's > been done, and done better than I could.? I really recommend that you learn > them; I think that once you do, you'll find that they're a better fit in all > sorts of places where you've been using lists.? (Speaking from personal > experience...) Well, I wrote "a BIT shaky". I sure learned a lot writing my phone_book.py, with important input from you . And am still pretty happy with it. And dictionaries seem to be well-covered in some of the Python books I have. Dick From rdmoores at gmail.com Sun Sep 11 03:32:15 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 18:32:15 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 17:34, Alan Gauld wrote: > On 11/09/11 00:18, Richard D. Moores wrote: > >>> So you open the file and from that point on treat it exactly like a >>> dictionary. >> >> I'm still a bit shaky about dictionaries. > > But you started the post with using a dictionary. > > Shelve is just a dictionary that lives in a file instead of memory. > If you can put data into or read it out of a dictionary then you can do the > same with shelve. > > The only complexity is you have to open the file before sing it and close it > when your done. > >> Much of what comes after that is beyond me. > > >> Thanks for your encouragement Alan, but I'm still looking among my >> Python books for a good exposition of shelve. > > You probably won't find much in books because shelve has such a specific > purpose. As a result there isn't much to say about it > if you've already covered dictionaries. > > It's a file based dictionary. So read up on dictionaries. > Then just use it. > > There are a few limitations with shelve but for most normal > cases you can ignore that and just use it like any normal > dictionary. OK, Alan, I really will give shelve a try. Dick From rdmoores at gmail.com Sun Sep 11 03:35:33 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 10 Sep 2011 18:35:33 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: On Sat, Sep 10, 2011 at 15:15, Jack Trades wrote: > On Sat, Sep 10, 2011 at 4:36 PM, Richard D. Moores > wrote: >> >> Your idea doesn't seem efficient for me -- >> lots of typing and editing. > > Not sure what you mean by that?? I've updated the gist with a quick 5min > implementation of a GUI using Tkinter and the approach I outlined.? I think > using a GUI is best way to minimize "typing and editing" in an app like > this.? You can find it here: > > https://gist.github.com/1208786#file_book.py Using Python 2.7 for it, it seems to work fine, except that I can't see how the GUI helps. It opens only when I use the g option to find an entry already made. Useful for editing an entry, though. As for the non-GUI script, I get this error no matter which choice I make. I'm too dumb, and have forgotten too much of Python 2.x to debug: ============================== What's next: (q) Quit (a) Add new Entry (v) View all Entries (s) General Search (si) Search by Initials (sn) Search by Name > q Traceback (most recent call last): File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line 171, in main_loop() File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line 94, in main_loop > """) File "", line 1, in NameError: name 'q' is not defined Process terminated with an exit code of 1 ============================ > > If you're talking about re-entering all your data from your file, you would > write a script to do that. Ha! I would? >? This program assumes that you are starting from > scratch with a blank phone book.? If you would like help converting your > existing file, I'm sure I or others can help, but I'd need to see the > original file. I'll take you up on that. I'll have to edit it some first. What I have now with "grepping" that 786-line RTF file is maximum flexibility. A line in the file always begins with a name, with at least one phone number, then if a company, the hours they are reachable by phone, possibly their web address, maybe an email address, my contact there plus maybe her secretary. If a physician, there might very well be his specialty, his nurse's name, mention of who recommended him to me, etc. It seems that the format of info for your way is set rigidly in advance, or am I wrong? Dick > > -- > Nick Zarczynski > Pointless Programming Blog > > From jacktradespublic at gmail.com Sun Sep 11 04:13:32 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Sat, 10 Sep 2011 21:13:32 -0500 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: > > Using Python 2.7 for it, it seems to work fine, except that I can't > see how the GUI helps. It opens only when I use the g option to find > an entry already made. Useful for editing an entry, though. > Well the idea would be to build the app as a full-blown GUI. The GUI search and edit functionality was just a proof-of-concept to show how that may work. I was just having some fun and seeing what I could do in less than an hour. Turning this into a full blown app is not what I had in mind, though if you want to build on it to learn I would be willing to help. > > As for the non-GUI script, I get this error no matter which choice I > make. I'm too dumb, and have forgotten too much of Python 2.x to > debug: > > ============================== > What's next: > (q) Quit > (a) Add new Entry > (v) View all Entries > (s) General Search > (si) Search by Initials > (sn) Search by Name > > > q > Traceback (most recent call last): > File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line > 171, in > main_loop() > File "c:\P32Working\Pickles\nicks_simple_phone_book_app.py", line > 94, in main_loop > > """) > File "", line 1, in > NameError: name 'q' is not defined > Process terminated with an exit code of 1 > ============================ > My guess is that this has something to do with Python 3.x not having raw_input. Try changing the raw_input calls to input. I don't get that error with 2.7. > > > If you're talking about re-entering all your data from your file, you > would > > write a script to do that. > > Ha! I would? > > Well, yeah. A line in the file always begins with a name, with at > least one phone number, then if a company, the hours they are > reachable by phone, possibly their web address, maybe an email > address, my contact there plus maybe her secretary. If a physician, > there might very well be his specialty, his nurse's name, mention of > who recommended him to me, etc. Like I said, I'd have to see the file to comment more, but it sounds like it may be too irregular to make writing a script an easy process. Though I can't be sure without seeing it. You could always enter these things by hand... I should probably ask; what is your goal for this app? Is it to learn some Python while making a usable app? Or are you looking for a robust address book for quick lookups of information? If it's the latter, I'd recommend you look around for something that's already made. It will save you a lot of trouble in the long run. If you're looking for a good learning experience this kind of app is a great starting place. However expect to run into problems along the way, up to and possibly beyond possibly hosing all the data you have entered into the app. Make regular backups of the data and keep your original around. > It seems that the format of info for > your way is set rigidly in advance, or am I wrong? > > Not really. Key/value pairs can be entered in arbitrary order. I used = to seperate key/values because that's what you used in your app and | to seperate k/v pairs to allow spaces without quoting strings. You could easily replace these tokens (= or |) with whatever you want. If you have another format that differs by more than those characters you would need to write a different parser. However there does have to be some consistency to the format of your data to make parsing easier. The less rigid your data the more work you will have to do to parse it. Since you said earlier that you will probably have less than 100 entries in your phone book, you may want to think about restructuring your data by hand to make it easier to parse before writing your parser. -- Nick Zarczynski Pointless Programming Blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From achompas at gmail.com Sun Sep 11 07:19:02 2011 From: achompas at gmail.com (Alejandro Companioni) Date: Sun, 11 Sep 2011 01:19:02 -0400 Subject: [Tutor] databases In-Reply-To: References: Message-ID: <1901FF48-1741-42AA-B37A-588FD449CC83@gmail.com> On Sep 10, 2011, at 9:29 PM, tutor-request at python.org wrote: > I've never used MySql on a Mac but I'm curious why it should be so > difficult. > > MacOS is just BSD Unix under the GUI so why would be any different > to any other Unix type system? What were the problems that you encountered? Hey Alan, I had the same thoughts at first: OS X is just BSD! This can't be too different from a Linux installation, right? There are a number of problems with mysql-python--chiefly its poor maintenance. I'll link to a nine (!) step guide on installing mysql-python on Mac as an example: http://friendlybit.com/tutorial/install-mysql-python-on-mac-os-x-leopard/ At Step 9 the author suggests using setuptools even though it will fail, and you'd actually have to patch a (old, well-documented) bug yourself. I wish I had found that website sooner, as installing mysql-python on my Mac took about 5-6 hours of constant frustration. Not a good start for a new Python coder, but if at least one novice skips my experience after reading this email then I'll be happy. -Alejandro -------------- next part -------------- An HTML attachment was scrubbed... URL: From thisisonlyatest at gmx.com Sun Sep 11 08:15:26 2011 From: thisisonlyatest at gmx.com (brandon w) Date: Sun, 11 Sep 2011 02:15:26 -0400 Subject: [Tutor] Tkinter Entry field text In-Reply-To: References: <4E697A8C.1030106@gmx.com> Message-ID: <4E6C51FE.6010906@gmx.com> On 09/10/2011 10:16 AM, Wayne Werner wrote: > On Thu, Sep 8, 2011 at 9:31 PM, brandon w > wrote: > > How do you display text in a Entry field and have it disappear > when a person clicks in it? > To get text into this box the person must first > delete what is already in there. > > Python 2.6.6 > > > Think about the process. You're already mostly there: you're > displaying data already, and you know what you want to do. > > You'll want to take a look at binding events, and if you Google for > "tkinter events" (http://www.google.com/search?q=tkinter+events) then > your first result takes you here: > http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm > > To point you in the right direction, you want to take a look at the > event. If you're not familiar with what a callback is, you > should also read this page: http://effbot.org/zone/tkinter-callbacks.htm > > If you still have problems after that, show us what else you've tried > and we'll be happy to give you more pointers in the right direction. > > > > Of course, while this answers your questions, I would be remiss if I > didn't suggest a few more things about your program in general. > > > label1 = Label(root, text="Enter you password: ") > > label1 isn't a terribly descriptive name. That's fine if you don't > intend to actually do anything with the label. However, you can make > this even more explicit by chaining the commands together. Since > Label() returns a label, you can add a dot to the end and treat it > just like you would the variable: > > Label(root, text="Enter you password: ").grid(sticky=W, row=0, column=0) > > That will create your label and stick it in the grid in one step, and > makes it clear to anyone reading your code (including yourself down > the road!) that you don't care to do anything with that label. > > Next: > > > enter_data1 = Entry(root, bg = "pale green") > > enter_data1 also suffers from the same naming problem. It doesn't > describe what the variable is or does very well, aside from entering > data. You could change it to something like "password_entry" - which > tells anyone reading your program that the variable should contain > something that lets you do some password entry. Just naming it > password would also be better than enter_data1. > > One other issue that you should consider - with the options you have > set, anyone could see what you typed in as your password. If you're > just using this as a testing program to play around with, that's > probably OK, but what's even better is to change what's shown in the > box. You can do this by setting the "show" option, either in the > constructor or somewhere later: > > from Tkinter import * > > root = Tk() > entry = Entry(root) > entry.pack() > entry.insert(0, "My Cool Password") > entry.config(show="*") > root.mainloop() > > The nice thing about the config() method is that it allows you to > change config attributes later. You can combine this knowledge with > some of what I mentioned earlier to show 'password' until they > navigate to the field, and then just show asterisks. > > For bonus points, if they leave the password field without typing a > password, can you make it show 'password' again? > > HTH, > Wayne Wayne, Your advice was extremely helpful. I pointed me into the right direction. I got the code to work after some time. I know how to make it show the "password" again. I would have to do this: from Tkinter import * root = Tk() root.title("Show me your Password") root.geometry("375x100+600+250") root.grid() def callback(event): passwd_entry.delete(0, END) # It would come back because there is no .insert() function. return [....snip...] #========================= Here is the final working code: #!/usr/bin/python from Tkinter import * root = Tk() root.title("Show me your Password") root.geometry("375x100+600+250") root.grid() def callback(event): field0 = varText1.get() passwd_entry.delete(0, END) passwd_entry.insert(0, field0) return def showPasswd(): field1 = varText.get() passwd_display.delete(0, END) passwd_display.insert(0, field1) return Label(root, text="Type your password in this box: ").grid(sticky=W, row=0, column=0) Label(root, text="Your password is:").grid(sticky=W, row=2, column=0) varText = StringVar() varText.set("Enter password") passwd_entry = Entry(root, textvariable=varText, bg = "pale green") passwd_entry.bind("", callback) passwd_entry.config(show="*") passwd_entry.grid(row=0, column=1) varText1 = StringVar(None) passwd_display = Entry(root, textvariable=varText1, bg = "pale green") passwd_display.grid(row=2, column=1) Button(root, text="Show Password", width=10, command=showPasswd).grid(sticky=W, row=1, column=0) root.mainloop() Thanks a lot for your help!!!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Sep 11 10:34:38 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Sep 2011 09:34:38 +0100 Subject: [Tutor] databases In-Reply-To: <1901FF48-1741-42AA-B37A-588FD449CC83@gmail.com> References: <1901FF48-1741-42AA-B37A-588FD449CC83@gmail.com> Message-ID: On 11/09/11 06:19, Alejandro Companioni wrote: > I had the same thoughts at first: OS X is just BSD! This can't be too > different from a Linux installation, right? > > There are a number of problems with mysql-python--chiefly its poor > maintenance. I'll link to a nine (!) step guide on installing > mysql-python on Mac as an example: > > http://friendlybit.com/tutorial/install-mysql-python-on-mac-os-x-leopard/ > Hmm, That's not really that difficult, about the same as on any standard Unix system. I guess its much harder than the usual MacOS install though, so for a Mac user would seem pretty bad. > At Step 9 the author suggests using setuptools even though it will fail, > and you'd actually have to patch a (old, well-documented) bug yourself. Yeah, but he could have shortened it slightly by telling you about the types.h bug at step 7 rather than wait till it failed!... But its a pity they MySQL folks haven't fixed that yet. Then it would only have been a 7 step process. Also I suspect you don't really need to download the full Developers Tools(XCode) you could probably just use the gcc compiler which is much smaller from Macports or Fink. OTOH IF you are using Python on a Mac then using XCode as your IDE is a good idea! Especially if you want to write Mac GUIs. And if you already had XCode installed then the process would go dowen to 5 steps... And as one commentator said the Developer tools are on the MacOS DVD, you don't need to download them and register on the site (although that's a good idea too) > ....Not a good start for a new Python coder, I can see it might be intimidating to a Mac user trying to get into programming. But OTOH wouldn't setting up a Linux VM be even more steps? But sadly as a programmer that kind of installation routine is fairly normal(*). Developers are expected to be fairly savvy about how their computer works so slick installation tools are rarely a high priority... And in fact some developers don't like fancy installers that do all the setup for them because they have set up their machines "just so" for their own ends and want complete control. You can't please everyone... (*)I once worked on a project that required Oracle 6 to be installed on our Sun server and after two days I got it working. I then documented the process for the rest of the team. It was 22 steps and even after doing it a half dozen times it still took several hours to complete. Thankfully Oracle have improved their installers nowadays! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Mon Sep 12 05:02:56 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 11 Sep 2011 20:02:56 -0700 Subject: [Tutor] About installing 3.2.2 In-Reply-To: References: Message-ID: Win 7, Python 3.2.1 I had downloaded python-3.2.2.amd64.msi and started the installation when I saw the attached. Does it mean that I would lose everything in the site-packages folder? Is this something even the Python newbie is supposed to know? Thanks, Dick Moores -------------- next part -------------- A non-text attachment was scrubbed... Name: Python3.2.2Setup3.jpg Type: image/jpeg Size: 19863 bytes Desc: not available URL: From rdmoores at gmail.com Mon Sep 12 07:29:30 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 11 Sep 2011 22:29:30 -0700 Subject: [Tutor] Can't edit a file I've opened with open(), then closed with close() Message-ID: Win 7, Python 3.2.1 I'm trying to improve my skills with opening text files, reading from them, and writing to them. But while I'm doing this sometimes I want to manually modify the text file I'm using, C:\t\text.txt . Say I've done this: >>> f = open(r"C:\t\test.txt", 'r+') >>> f.read() '0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19Now is the time for all goo men\nto come to the aid\nof their party.\n' >>> f.close() >>> and I decide to manually delete all those integers, and also correct "goo". So I open test.txt and do that. But when I try to save, I get "The process cannot access the file because it is being used by another process." I'm using IDLE, so I close it. But still no save. Why? And what can I do about it? I check with the task manager and see 22 pythonw.exe processes.. Thanks, Dick Moores -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Sep 12 13:51:51 2011 From: d at davea.name (Dave Angel) Date: Mon, 12 Sep 2011 07:51:51 -0400 Subject: [Tutor] Can't edit a file I've opened with open(), then closed with close() In-Reply-To: References: Message-ID: <4E6DF257.6060801@davea.name> On 09/12/2011 01:29 AM, Richard D. Moores wrote: > Win 7, Python 3.2.1 > > I'm trying to improve my skills with opening text files, reading from them, > and writing to them. > > But while I'm doing this sometimes I want to manually modify the text file > I'm using, C:\t\text.txt . Say I've done this: > >>>> f = open(r"C:\t\test.txt", 'r+') >>>> f.read() > '0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19Now is > the time for all goo men\nto come to the aid\nof their party.\n' >>>> f.close() >>>> > and I decide to manually delete all those integers, and also correct "goo". > So I open test.txt and do that. But when I try to save, I get "The process > cannot access the file because it is being used by another process." I'm > using IDLE, so I close it. But still no save. Why? And what can I do about > it? I check with the task manager and see 22 pythonw.exe processes.. > > Thanks, > > Dick Moores > Nothing wrong with the program as you show it. Once it you've entered the close(), it should release the file so a text editor can work on it. However, I notice you're doing this interactively. So probably in one of the many sessions you DIDN'T close it. Or you used the wrong variable to try to close it. Until that shell is closed, it'll prevent anyone else from writing to the file. Each of those pythonw processes is a potential problem. One of them is presumably holding onto the file. Sysinternals has a number of utilities to help track down problems like that. However, in this case, you probably don' t care which process it is, just close them all from the task manager. If you did, the utility 'handle' would probably identify which process it was. Sysinternals, hosted here: http://technet.microsoft.com/en-us/sysinternals/default.aspx handle is here: http://technet.microsoft.com/en-us/sysinternals/bb795533Sy -- DaveA From ramit.prasad at jpmorgan.com Mon Sep 12 15:43:50 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 12 Sep 2011 09:43:50 -0400 Subject: [Tutor] databases In-Reply-To: References: <1901FF48-1741-42AA-B37A-588FD449CC83@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A197FB@EMARC112VS01.exchad.jpmchase.net> > Also I suspect you don't really need to download the full Developers >Tools(XCode) you could probably just use the gcc compiler which >is much smaller from Macports or Fink. The last I checked, Macports required XCode compiler to build/install itself (and requires XCode to be updated on OS upgrade). This might have changed. I have never used Fink, so not sure if that is different. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Mon Sep 12 15:48:44 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 12 Sep 2011 09:48:44 -0400 Subject: [Tutor] About installing 3.2.2 In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A19816@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Richard D. Moores Sent: Sunday, September 11, 2011 10:03 PM To: Tutor List Subject: [Tutor] About installing 3.2.2 Win 7, Python 3.2.1 I had downloaded python-3.2.2.amd64.msi and started the installation when I saw the attached. Does it mean that I would lose everything in the site-packages folder? Is this something even the Python newbie is supposed to know? Thanks, Dick Moores ============================= I would think not. The message leads me to think it will update an existing Python install but not in a delete-replace manner. You could always test it by copying the directory or creating a zip of it, update, and see if the site-packages folder has been modified. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From susana.delgado_s at utzmg.edu.mx Mon Sep 12 16:49:25 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 12 Sep 2011 09:49:25 -0500 Subject: [Tutor] Unusual pathfile Message-ID: Hi! I developed a python gui module to make a walk through a directory. This time I want the user to select the parameters I need from the python gui. The results will be written in a csv file, the problem I found is the pathfile shows this way: C:/\Archivos de programa\FWTools2.4.7\bin\mapnik-0.7.1\demo\data I'm workin with Python 2.6.6 and Windows XP, the code is: from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" def directorio(): global dir print 'Seleccione directorio donde empezar' dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname ) > 0: print "You chose %s" % dirname dir = dirname def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv_w(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def boton4(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' x_min = 'x_min' x_max = 'x_max' y_min = 'y_min' y_max = 'y_max' geometria = 'geometria' num_elem = 'num_elem' prj = '.prj' proyeccion = 'proyeccion' fecha = 'fecha_modificacion' creacion = 'fecha_creacion' ultimo = 'ultimo_acceso' tamanio = 'tamanio_aprox' maq = 'maquina_host' usu = 'usuario' campos = [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): directorio = os.path.dirname(filepath) filename = os.path.basename(filepath) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp log.write(shp+"\n") I don't want to get filepath order -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Sep 12 21:05:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Sep 2011 20:05:27 +0100 Subject: [Tutor] Unusual pathfile In-Reply-To: References: Message-ID: On 12/09/11 15:49, Susana Iraiis Delgado Rodriguez wrote: > Hi! > I developed a python gui module to make a walk through a directory. This > time I want the user to select the parameters I need from the python > gui. The results will be written in a csv file, the problem I found is > the pathfile shows this way: > C:/\Archivos de programa\FWTools2.4.7\bin\mapnik-0.7.1\demo\data What exactly do you feel is wrong with that? Is it the fact that the first slash after the colon is forward facing? Or is there something else? > I'm workin with Python 2.6.6 and Windows XP, the code is: Could you please use a few more spaces. Both to indent the code (2 spaces ids really the minimum and 3 or 4 is normal. But one is useless) and to separate the functions vertically. (ie a blank line before the def statements) It is really very hard work wading through this stuff! I don't know how you can read it but I'm struggling to see the structure. > from Tkinter import * #Llamo las librerias graficas de Tk > import tkSimpleDialog #Libreria de almacenamiento de dialogos > import tkMessageBox #Libreria de mensajes > import tkFileDialog > import sys, os, csv, time, socket, stat > from osgeo import ogr,gdal,osr > from osgeo.gdalconst import * > from PIL import Image > dir = "" > extn = "" > csv_name = "" > def directorio(): > global dir > print 'Seleccione directorio donde empezar' > dirname = > tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona > la ruta a escanear') > if len(dirname ) > 0: > print "You chose %s" % dirname > dir = dirname > def extension(): > global extn > print "Escribe la extension que necesitas buscar" > ext=tkSimpleDialog.askstring('Extension a buscar:','') > print 'Buscando archivos: ',ext > extn = ext > def csv_w(): > global csv_name > print "Nombre del csv a crear" > inv=tkSimpleDialog.askstring('Nombre de .csv:','') > print 'Archivo de salidad: ',inv > csv_name = inv > def boton4(): > print 'Iniciando...' > gdal.AllRegister() > file_list = [] > folders = None > for root, folders, files in os.walk(dir): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(extn)) > f = open(csv_name, 'wb') > log = open ('log_errores.txt','w') > writer = csv.writer(f) > ruta = 'Ruta' > archivo = 'archivo' > x_min = 'x_min' > x_max = 'x_max' > y_min = 'y_min' > y_max = 'y_max' > geometria = 'geometria' > num_elem = 'num_elem' > prj = '.prj' > proyeccion = 'proyeccion' > fecha = 'fecha_modificacion' > creacion = 'fecha_creacion' > ultimo = 'ultimo_acceso' > tamanio = 'tamanio_aprox' > maq = 'maquina_host' > usu = 'usuario' > campos = > [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] > writer.writerow(campos) > for row, filepath in enumerate(file_list, start=1): > directorio = os.path.dirname(filepath) > filename = os.path.basename(filepath) > shapeData = ogr.Open(filepath) > shp = 'Error al abrir el archivo' +filepath > if shapeData is None: > print shp > log.write(shp+"\n") > I don't want to get filepath order I don't understand what that means? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From nitinchandra1 at gmail.com Mon Sep 12 21:15:22 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Tue, 13 Sep 2011 00:45:22 +0530 Subject: [Tutor] Calendar Message-ID: Hi All, I need to create a calendar with python & CSS for the web page, in the following format Dec , 2011 ------------------------------------------------------------------------------------------------- sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun -------|-----------|----------|---------------------------------------------------------------------- 1 | 2 | 3 | 4 5 6 7 8 9 10 11 12 13 14 15 -------|-----------|----------|----------------------------------------------------------------------- img1 | img2 | img3 | .... Jan , 2012 ------------------------------------------------------------------------------------------------- sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun -------|-----------|----------|---------------------------------------------------------------------- 1 | 2 | 3 | 4 5 6 7 8 9 10 11 12 13 14 15 -------|-----------|----------|----------------------------------------------------------------------- img1 | img2 | img3 | .... Feb , 2012 ------------------------------------------------------------------------------------------------- sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun -------|-----------|----------|---------------------------------------------------------------------- 1 | 2 | 3 | 4 5 6 7 8 9 10 11 12 13 14 15 -------|-----------|----------|----------------------------------------------------------------------- img1 | img2 | img3 | .... Can some one please show me how to do the above ? Thanks Nitin From spawgi at gmail.com Mon Sep 12 21:33:09 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Tue, 13 Sep 2011 01:03:09 +0530 Subject: [Tutor] Calendar In-Reply-To: References: Message-ID: If you want to create a calendar for a webpage, I think you can use many ready made JS packages for this. May be jquery also has something. Is using Python mandatory for this task? And why? On Tue, Sep 13, 2011 at 12:45 AM, nitin chandra wrote: > Hi All, > > I need to create a calendar with python & CSS for the web page, in the > following format > > Dec , 2011 > > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat > sun > > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > Jan , 2012 > > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat > sun > > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > Feb , 2012 > > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat > sun > > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > > Can some one please show me how to do the above ? > > Thanks > > Nitin > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Mon Sep 12 23:21:34 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 12 Sep 2011 23:21:34 +0200 Subject: [Tutor] Calendar In-Reply-To: References: Message-ID: <4E6E77DE.3040602@gmail.com> On 12/09/11 21:15, nitin chandra wrote: > I need to create a calendar with python& CSS for the web page, in the > following format > > Dec , 2011 > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > Jan , 2012 > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > Feb , 2012 > ------------------------------------------------------------------------------------------------- > sun | mon | tue | wed thu fri sat sun mon tue wed thu fri sat sun > -------|-----------|----------|---------------------------------------------------------------------- > 1 | 2 | 3 | 4 5 6 7 8 9 10 11 > 12 13 14 15 > -------|-----------|----------|----------------------------------------------------------------------- > img1 | img2 | img3 | .... > > > Can some one please show me how to do the above ? Have a look at the calendar module. A quick google search I also found [1] which does all the bits you just need to adapt it for your needs. Greets Sander From nitinchandra1 at gmail.com Tue Sep 13 07:02:34 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Tue, 13 Sep 2011 10:32:34 +0530 Subject: [Tutor] Calendar In-Reply-To: <4E6E77DE.3040602@gmail.com> References: <4E6E77DE.3040602@gmail.com> Message-ID: I tried it in the following way, but beyond that i am not able to go. #!/usr/bin/env python import os, re, sys, calendar from datetime import datetime myCal = calendar.monthcalendar(2011,9) html += str(myCal) mycal = myCal[:1] cal1 = myCal[1:2] cal2 = myCal[2:3] cal3 = myCal[3:4] cal4 = myCal[4:5] html += str(mycal)+'
' html += str(cal1)+'
' html += str(cal2)+'
' html += str(cal3)+'
' html += str(cal4)+'
' html += "
" This is the following output ? which I need in the above format: [[0, 0, 0, 1, 2, 3, 4]] [[5, 6, 7, 8, 9, 10, 11]] [[12, 13, 14, 15, 16, 17, 18]] [[19, 20, 21, 22, 23, 24, 25]] [[26, 27, 28, 29, 30, 0, 0]] How do I proceed, or is there another way? Thanks From rdmoores at gmail.com Tue Sep 13 08:43:34 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 12 Sep 2011 23:43:34 -0700 Subject: [Tutor] need advice about a dictionary ({}) In-Reply-To: References: Message-ID: I'm the OP. Nick Zarr, alias Jack Trades, has done something really marvelous. He's made a thorough critique and refactoring of my phone_book.py, in its last incarnation as . See . He'll be making that part of his blog (), and may turn it into an article. Dick From rdmoores at gmail.com Tue Sep 13 08:49:31 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 12 Sep 2011 23:49:31 -0700 Subject: [Tutor] About installing 3.2.2 In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A19816@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A19816@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Mon, Sep 12, 2011 at 06:48, Prasad, Ramit wrote: > -----Original Message----- > From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Richard D. Moores > Sent: Sunday, September 11, 2011 10:03 PM > To: Tutor List > Subject: [Tutor] About installing 3.2.2 > > Win 7, Python 3.2.1 > > I had downloaded python-3.2.2.amd64.msi and started the installation when I saw the attached. Does it mean that I would lose everything in the site-packages folder? Is this something even the Python newbie is supposed to know? > > Thanks, > > Dick Moores > ============================= > > > I would think not. The message leads me to think it will update an existing Python install but not in a delete-replace manner. You could always test it by copying the directory or creating a zip of it, update, and see if the site-packages folder has been modified. > > > Ramit Thanks, Ramit. I didn't see your reply until just now. I'll follow your advice. Dick From rdmoores at gmail.com Tue Sep 13 09:21:15 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 13 Sep 2011 00:21:15 -0700 Subject: [Tutor] About installing 3.2.2 In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16A19816@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Mon, Sep 12, 2011 at 23:49, Richard D. Moores wrote: > On Mon, Sep 12, 2011 at 06:48, Prasad, Ramit wrote: >> -----Original Message----- >> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Richard D. Moores >> Sent: Sunday, September 11, 2011 10:03 PM >> To: Tutor List >> Subject: [Tutor] About installing 3.2.2 >> >> Win 7, Python 3.2.1 >> >> I had downloaded python-3.2.2.amd64.msi and started the installation when I saw the attached. Does it mean that I would lose everything in the site-packages folder? Is this something even the Python newbie is supposed to know? >> >> Thanks, >> >> Dick Moores >> ============================= >> >> >> I would think not. The message leads me to think it will update an existing Python install but not in a delete-replace manner. You could always test it by copying the directory or creating a zip of it, update, and see if the site-packages folder has been modified. >> >> >> Ramit > > Thanks, Ramit. I didn't see your reply until just now. I'll follow your advice. The installation didn't NOT disturb anything in the site-packages folder, exactly as Ramit surmised. Dick From susana.delgado_s at utzmg.edu.mx Tue Sep 13 17:41:26 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 13 Sep 2011 10:41:26 -0500 Subject: [Tutor] Unusual pathfile In-Reply-To: References: Message-ID: Hi! I just want to look the pathfile like this: C:\Python26 instead of C:/\Python26, I feel the loop repeats its walking with this pathfile structure. About the indention for the code, I tried my best to make it clear ande neat. But the mi e-mail editor it's mixing-up spaces. Here's again: from Tkinter import * #Llamo las librerias graficas de Tk import tkSimpleDialog #Libreria de almacenamiento de dialogos import tkMessageBox #Libreria de mensajes import tkFileDialog import sys, os, csv, time, socket, stat from osgeo import ogr,gdal,osr from osgeo.gdalconst import * from PIL import Image dir = "" extn = "" csv_name = "" filesystemencoding = sys.getfilesystemencoding() def directorio(): global dir print 'Seleccione directorio donde empezar' dirname1 = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la ruta a escanear') if len(dirname1 ) > 0: print "You chose %s" % dirname1 dir = dirname1 def extension(): global extn print "Escribe la extension que necesitas buscar" ext=tkSimpleDialog.askstring('Extension a buscar:','') print 'Buscando archivos: ',ext extn = ext def csv_w(): global csv_name print "Nombre del csv a crear" inv=tkSimpleDialog.askstring('Nombre de .csv:','') print 'Archivo de salidad: ',inv csv_name = inv def buscar(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) f = open(csv_name, 'wb') log = open ('log_errores.txt','w') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' x_min = 'x_min' x_max = 'x_max' y_min = 'y_min' y_max = 'y_max' geometria = 'geometria' num_elem = 'num_elem' prj = '.prj' proyeccion = 'proyeccion' fecha = 'fecha_modificacion' creacion = 'fecha_creacion' ultimo = 'ultimo_acceso' tamanio = 'tamanio_aprox' maq = 'maquina_host' usu = 'usuario' campos = [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): directorio = os.path.dirname(filepath) filename = os.path.basename(filepath) #shapeData = ogr.Open(filepath) shapeData = ogr.Open(filepath.encode(filesystemencoding)) if shapeData is None: shp = 'Error al abrir el archivo ' + filepath.encode(filesystemencoding) print shp log.write(shp+"\n") else: print 'Trabajando en: ' +filepath layer = shapeData.GetLayer() feature = layer.GetNextFeature() x_y = layer.GetExtent() #x_min x1 = x_y[0] #x_max x2 = x_y[1] #y_min y1 = x_y[2] #y_max y2 = x_y[3] #Escribir el tipo de geometria del shp. 1=Point, 2=LineString, 3=Polygon defn = layer.GetLayerDefn() geo = defn.GetGeomType() #Comenzar el featurecount() cuenta = layer.GetFeatureCount() proy = layer.GetSpatialRef() prjtext = ''+str(proy)+'' ### n = os.path.splitext(filepath) p = n[0]+'.prj' shx = n[0]+'.shx' #shx_msj = 'Error al abrir el archivo' +shx dbf = n[0]+'.dbf' #dbf_msj = 'Error al abrir el archivo' +dbf filepath = ''+filepath+'' filename = ''+filename+'' t = time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(filepath))) modificacion = ''+t+'' crdt = time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getctime(filepath))) crea = ''+crdt+'' lt_acc = time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getatime(filepath))) acceso = ''+lt_acc+'' s = os.path.getsize(filepath) def sizeof_fmt(num): for x in ['bytes','KB','MB','GB','TB']: if num < 1024.0: return "%3.1f%s" % (num, x) num /= 1024.0 #Obtener usuario usuario = os.environ.get("USERNAME") user = ''+usuario+'' host = socket.gethostname() maquina = ''+host+'' if os.path.exists(shx): print '.' shx1 = os.path.getsize(shx) #kb2 = sizeof_fmt(shx1) else: log.write('No existe el archivo ' +shx+"\n") if os.path.exists(dbf): print '.' else: log.write('No existe el archivo ' +dbf+"\n") if os.path.exists(p): #Si existe, asignar 1 p1 = os.path.getsize(p) total = sizeof_fmt(s+shx1+p1) aRow= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 1, prjtext, crea, modificacion, acceso, total, maquina, user] writer.writerow(aRow) else: #Sino asignar 0 #no_prj = 'Sin prj, no se puede determinar la proyeccion' total = sizeof_fmt(s+shx1) aRow1= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 0, prjtext, crea, modificacion, acceso, total, maquina, user] writer.writerow(aRow1) log.close() f.close() print "El archivo esta listo" root = Tk() top = Toplevel() #Llamo una nueva ventana #Dimensiones de la ventana root.minsize(400,200) #Barra de herramientas toolbar = Frame(root) #Botones b = Button(toolbar, text="Selecciona ruta", width=15, command=directorio) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Escriba extension", width=15, command=extension) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Nombre de csv", width=15, command=csv_w) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Aceptar", width=6, command=buscar) b.pack(side=LEFT, padx=2, pady=2) toolbar.pack(side=TOP, fill=X) root.mainloop() 2011/9/12 Alan Gauld > On 12/09/11 15:49, Susana Iraiis Delgado Rodriguez wrote: > >> Hi! >> I developed a python gui module to make a walk through a directory. This >> time I want the user to select the parameters I need from the python >> gui. The results will be written in a csv file, the problem I found is >> the pathfile shows this way: >> C:/\Archivos de programa\FWTools2.4.7\bin\**mapnik-0.7.1\demo\data >> > > What exactly do you feel is wrong with that? > Is it the fact that the first slash after the colon is forward facing? > Or is there something else? > > > I'm workin with Python 2.6.6 and Windows XP, the code is: >> > > Could you please use a few more spaces. Both to indent the code (2 spaces > ids really the minimum and 3 or 4 is normal. But one is > useless) and to separate the functions vertically. (ie a blank line before > the def statements) > > It is really very hard work wading through this stuff! I don't know how you > can read it but I'm struggling to see the structure. > > > > from Tkinter import * #Llamo las librerias graficas de Tk >> import tkSimpleDialog #Libreria de almacenamiento de dialogos >> import tkMessageBox #Libreria de mensajes >> import tkFileDialog >> import sys, os, csv, time, socket, stat >> from osgeo import ogr,gdal,osr >> from osgeo.gdalconst import * >> from PIL import Image >> dir = "" >> extn = "" >> csv_name = "" >> > > def directorio(): >> global dir >> print 'Seleccione directorio donde empezar' >> dirname = >> tkFileDialog.askdirectory(**parent=root,initialdir="/",** >> title='Selecciona >> la ruta a escanear') >> if len(dirname ) > 0: >> print "You chose %s" % dirname >> dir = dirname >> > > def extension(): >> global extn >> print "Escribe la extension que necesitas buscar" >> ext=tkSimpleDialog.askstring('**Extension a buscar:','') >> print 'Buscando archivos: ',ext >> extn = ext >> > > def csv_w(): >> global csv_name >> print "Nombre del csv a crear" >> inv=tkSimpleDialog.askstring('**Nombre de .csv:','') >> print 'Archivo de salidad: ',inv >> csv_name = inv >> > > def boton4(): >> print 'Iniciando...' >> gdal.AllRegister() >> file_list = [] >> folders = None >> for root, folders, files in os.walk(dir): >> file_list.extend(os.path.join(**root,fi) for fi in files if >> fi.endswith(extn)) >> f = open(csv_name, 'wb') >> log = open ('log_errores.txt','w') >> writer = csv.writer(f) >> ruta = 'Ruta' >> archivo = 'archivo' >> x_min = 'x_min' >> x_max = 'x_max' >> y_min = 'y_min' >> y_max = 'y_max' >> geometria = 'geometria' >> num_elem = 'num_elem' >> prj = '.prj' >> proyeccion = 'proyeccion' >> fecha = 'fecha_modificacion' >> creacion = 'fecha_creacion' >> ultimo = 'ultimo_acceso' >> tamanio = 'tamanio_aprox' >> maq = 'maquina_host' >> usu = 'usuario' >> campos = >> [ruta,archivo,x_min,x_max,y_**min,y_max,geometria,num_elem,** >> prj,proyeccion,creacion,fecha,**ultimo,tamanio,maq,usu] >> writer.writerow(campos) >> for row, filepath in enumerate(file_list, start=1): >> directorio = os.path.dirname(filepath) >> filename = os.path.basename(filepath) >> shapeData = ogr.Open(filepath) >> shp = 'Error al abrir el archivo' +filepath >> if shapeData is None: >> print shp >> log.write(shp+"\n") >> > > > > I don't want to get filepath order >> > > I don't understand what that means? > > -- > Alan G > 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 d at davea.name Tue Sep 13 18:55:04 2011 From: d at davea.name (Dave Angel) Date: Tue, 13 Sep 2011 12:55:04 -0400 Subject: [Tutor] Unusual pathfile In-Reply-To: References: Message-ID: <4E6F8AE8.70300@davea.name> 1. Don't top-post. Put your response after whatever parts of a previous message you're quoting. And delete the parts that are no longer relevant. 2. If you used tabs in your code, convert to spaces before pasting into some email editors. Apparently your email editor is converting the tabs to single spaces. On 09/13/2011 11:41 AM, Susana Iraiis Delgado Rodriguez wrote: > Hi! > I just want to look the pathfile like this: C:\Python26 instead of > C:/\Python26, I feel the loop repeats its walking with this pathfile > structure. > > Try using mypath = os.path.abspath(mypath) No clue what you mean by "repeats its walking" -- DaveA From steve at pearwood.info Tue Sep 13 19:00:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 14 Sep 2011 03:00:50 +1000 Subject: [Tutor] Unusual pathfile In-Reply-To: References: Message-ID: <4E6F8C42.4070709@pearwood.info> Susana Iraiis Delgado Rodriguez wrote: > Hi! > I just want to look the pathfile like this: C:\Python26 instead of > C:/\Python26, I feel the loop repeats its walking with this pathfile > structure. About the indention for the code, I tried my best to make it > clear ande neat. But the mi e-mail editor it's mixing-up spaces. > Here's again: Susana, you are showing too much code that is unrelated to your problem. Your problem is that your code gives the wrong result for the file name: you want C:\Python26 but get C:/\Python26. You should isolate the part of your code that produces the path names. We don't need the part that creates buttons, or writes CSV files, or prints messages to the user. As it stands now, I can't even tell which part of the code generates "C:/\Python26", let alone how to fix it. You should have a small function, no more than ten or twenty lines, that handles the path names, and nothing else. -- Steven From susana.delgado_s at utzmg.edu.mx Tue Sep 13 19:12:08 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 13 Sep 2011 12:12:08 -0500 Subject: [Tutor] Unusual pathfile In-Reply-To: <4E6F8C42.4070709@pearwood.info> References: <4E6F8C42.4070709@pearwood.info> Message-ID: I think I've received many complains for my questions and messages, I know you're great programmers and this is for helping beginners or any level of Python users. I tried to correct the code I sent the best I could, than you for your time, I'll try to manage it myself. 2011/9/13 Steven D'Aprano > Susana Iraiis Delgado Rodriguez wrote: > >> Hi! >> >> I just want to look the pathfile like this: C:\Python26 instead of >> C:/\Python26, I feel the loop repeats its walking with this pathfile >> structure. About the indention for the code, I tried my best to make it >> clear ande neat. But the mi e-mail editor it's mixing-up spaces. >> Here's again: >> > > Susana, you are showing too much code that is unrelated to your problem. > Your problem is that your code gives the wrong result for the file name: you > want C:\Python26 but get C:/\Python26. > > You should isolate the part of your code that produces the path names. We > don't need the part that creates buttons, or writes CSV files, or prints > messages to the user. As it stands now, I can't even tell which part of the > code generates "C:/\Python26", let alone how to fix it. > > You should have a small function, no more than ten or twenty lines, that > handles the path names, and nothing else. > > > > -- > Steven > > ______________________________**_________________ > 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 marc.tompkins at gmail.com Tue Sep 13 19:37:58 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 13 Sep 2011 10:37:58 -0700 Subject: [Tutor] Unusual pathfile In-Reply-To: References: <4E6F8C42.4070709@pearwood.info> Message-ID: On Tue, Sep 13, 2011 at 10:12 AM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > I think I've received many complains for my questions and messages, I know > you're great programmers and this is for helping beginners or any level of > Python users. I tried to correct the code I sent the best I could, than you > for your time, I'll try to manage it myself. > Susana - I think I speak for everyone when I say: don't go away! Nobody's complaining about your question; that's what the list is for. However, we're all human beings, and all doing this voluntarily. So it's in your best interest to make your questions easy for us to read. So many lines all run together, with only one space of indentation, makes my head hurt when I try to read it; I'm ashamed to admit that I simply skipped over your question when you first posted it. Others put more effort into it, and have told you why it was hard for them. Don't be offended! At least they took the trouble, which is more than I did. Two things you can do to make this better: - Set your text editor to convert tabs to spaces, preferably four spaces. This is a Good Thing To Do anyway, because some of the hardest bugs to find - for you as well as for us - happen when Python gets confused about levels of indentation. If you're not sure how to change that setting, just tell us which editor you use and someone can help with that. - When you ask a question - and we WANT you to ask questions! - try to narrow down your program to just the part that's giving you trouble. It makes it MUCH easier for us to help you, and quite often it helps you to find the problem yourself. As Steven said above, at the moment I can't even see which part of your code is generating "C:\/Python26", let alone help you to correct it. Just remember: we all want to help; speaking for myself, I started out asking questions on this list and have stuck around to answer them. But we're all human too - and speaking for myself, sometimes we're a little lazy. -------------- next part -------------- An HTML attachment was scrubbed... URL: From di.marvellous at gmail.com Tue Sep 13 19:57:46 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Tue, 13 Sep 2011 21:57:46 +0400 Subject: [Tutor] cmd window Message-ID: Hello, Excuse me for my stupid question, but I'm an absolute beginner in programming. I just would like to know what should I do in such case: when I run my program by clicking on the file itself, rather than from IDLE, the cmd window disappears just immediately after the output printing, so that I can't even see it. The solution must be very simple, but I can't find it in tutorials... Thank you! -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Sep 13 20:20:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 14 Sep 2011 04:20:40 +1000 Subject: [Tutor] Unusual pathfile In-Reply-To: References: <4E6F8C42.4070709@pearwood.info> Message-ID: <4E6F9EF8.8060202@pearwood.info> Susana Iraiis Delgado Rodriguez wrote: > I think I've received many complains for my questions and messages Please don't be upset! We're not angry at your, and we are trying to help you. In English, we have a saying: "Give a man a fish, and you feed him for one day. Teach a man how to catch fish, and you feed him forever." We are happy to help solve your problems, but just as important is to teach you how to solve your problems without our help. Also, sometimes your questions are too hard for us to answer without spending many hours of work. We are volunteers who do this for free. We are not being paid for this. We do this as a way to pay back to the community that helped us when we were beginners. But help has to go both ways: you help us by asking good questions, and we help you by teaching you the answers. Lastly, remember that some of us use Apple Macs, or Linux, and do not have Windows. If this problem is specific to Windows pathnames, it might be impossible for us to help except by guessing. So have patience that we can't solve everything easily. Let us start with a simple part: you have this function: from Tkinter import * root = Tk() import tkFileDialog dir = "" def directorio(): global dir print 'Seleccione directorio donde empezar' dirname1 = tkFileDialog.askdirectory( parent=root, initialdir="/", title='Selecciona la ruta a escanear' ) if len(dirname1 ) > 0: print "You chose %s" % dirname1 dir = dirname1 If I run this function, I get this: >>> directorio() Seleccione directorio donde empezar You chose /usr/bin (I am using Linux, so I have no C: drive.) What do you get if you run it? -- Steven From waynejwerner at gmail.com Tue Sep 13 20:25:05 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 13 Sep 2011 13:25:05 -0500 Subject: [Tutor] cmd window In-Reply-To: References: Message-ID: On Tue, Sep 13, 2011 at 12:57 PM, Dinara Vakhitova wrote: > Hello, > > Excuse me for my stupid question, but I'm an absolute beginner in > programming. > I just would like to know what should I do in such case: when I run my > program by clicking on the file itself, rather than from IDLE, the cmd > window disappears just immediately after the output printing, so that I > can't even see it. The solution must be very simple, but I can't find it in > tutorials... > This is mainly because in later versions of Windows (XP onward, I believe) they changed a setting so that the command window would close after a program has executed. There are probably some more complicated settings to fix it on a global basis, but you'll find that most people add this line to the end of their programs: raw_input("Press to continue") # Use input() with Python 3.x HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From di.marvellous at gmail.com Tue Sep 13 20:55:29 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Tue, 13 Sep 2011 22:55:29 +0400 Subject: [Tutor] cmd window In-Reply-To: References: Message-ID: Thank you a lot, it helped! 2011/9/13 Wayne Werner > On Tue, Sep 13, 2011 at 12:57 PM, Dinara Vakhitova < > di.marvellous at gmail.com> wrote: > >> Hello, >> >> Excuse me for my stupid question, but I'm an absolute beginner in >> programming. >> I just would like to know what should I do in such case: when I run my >> program by clicking on the file itself, rather than from IDLE, the cmd >> window disappears just immediately after the output printing, so that I >> can't even see it. The solution must be very simple, but I can't find it in >> tutorials... >> > > This is mainly because in later versions of Windows (XP onward, I believe) > they changed a setting so that the command window would close after a > program has executed. There are probably some more complicated settings to > fix it on a global basis, but you'll find that most people add this line to > the end of their programs: > > raw_input("Press to continue") # Use input() with Python 3.x > > HTH, > Wayne > -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Sep 13 21:01:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Sep 2011 20:01:56 +0100 Subject: [Tutor] Unusual pathfile In-Reply-To: References: Message-ID: On 13/09/11 16:41, Susana Iraiis Delgado Rodriguez wrote: > Hi! > I just want to look the pathfile like this: C:\Python26 instead of > C:/\Python26, OK, Let's see how you might debug that. > I feel the loop repeats its walking with this pathfile I'm not sure what you mean by that but I do have some comments below that might be relevant... > structure. About the indention for the code, I tried my best to make it > clear ande neat. But the mi e-mail editor it's mixing-up spaces. OK, That's unfortunate. Which editor/email tool are you using? We may be able to suggest alternate settings. > dir = "" > extn = "" > csv_name = "" > filesystemencoding = sys.getfilesystemencoding() > > def directorio(): > global dir > print 'Seleccione directorio donde empezar' > dirname1 = > tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona > la ruta a escanear') Does changing the '/' here have any affect on your final result? Is this why you get the /\ maybe? > if len(dirname1 ) > 0: > print "You chose %s" % dirname1 > dir = dirname1 What gets printed here? Does it have the same /\ structure? > def extension():... I don't think the above function is relevant so we can ignore the code for now. > def csv_w():.... Same here, it just gets a filename - we could substitute a dummy one while testing... But this next function is way too big! Try breaking it into chunks each in their own function. It will make it easier to read and thus to understand and to debug. > def buscar(): > print 'Iniciando...' > gdal.AllRegister() > file_list = [] > folders = None > for root, folders, files in os.walk(dir): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(extn)) This could be put in a function to build the file list. Also you don't need the assignment to folders since os.walk will do that for you and you don't use it anywhere anyway. > f = open(csv_name, 'wb') > log = open ('log_errores.txt','w') > writer = csv.writer(f) > ruta = 'Ruta' > archivo = 'archivo' > x_min = 'x_min' > x_max = 'x_max' > y_min = 'y_min' > y_max = 'y_max' > geometria = 'geometria' > num_elem = 'num_elem' > prj = '.prj' > proyeccion = 'proyeccion' > fecha = 'fecha_modificacion' > creacion = 'fecha_creacion' > ultimo = 'ultimo_acceso' > tamanio = 'tamanio_aprox' > maq = 'maquina_host' > usu = 'usuario' Frankly there is no real advantage putting these strings in variables. You only use them in one place so just use the literal strings in the code there. It will make the code much shorter and therefore easier to read! > campos = > [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu] > writer.writerow(campos) > for row, filepath in enumerate(file_list, start=1): Since you don't seem to use row anywhere you could just make this: for filepath in file_list: > directorio = os.path.dirname(filepath) > filename = os.path.basename(filepath) > shapeData = ogr.Open(filepath.encode(filesystemencoding)) > if shapeData is None: > shp = 'Error al abrir el archivo ' + filepath.encode(filesystemencoding) Since the rest of this is irrelevant to your problem we can delete it for now... > def sizeof_fmt(num): > for x in ['bytes','KB','MB','GB','TB']: > if num < 1024.0: > return "%3.1f%s" % (num, x) > num /= 1024.0 > #Obtener usuario It's generally better to define all functions outside of other functions unless you plan on returning them as function objects. And if you are going to define a function inside another one please do it at the top and not in the middle of the function code. > usuario = os.environ.get("USERNAME") > user = ''+usuario+'' > host = socket.gethostname() > maquina = ''+host+'' I don't understand what this is trying to do? It adds an empty string to the user and host names? You might also want to check that you get valid values for these variables before using them... > if os.path.exists(shx): > print '.' > shx1 = os.path.getsize(shx) > #kb2 = sizeof_fmt(shx1) > else: > log.write('No existe el archivo ' +shx+"\n") > if os.path.exists(dbf): > print '.' > else: > log.write('No existe el archivo ' +dbf+"\n") I'm not sure what this is for? The paths don't exist so you log the error but then continue with the function anyway? > if os.path.exists(p): > #Si existe, asignar 1 > p1 = os.path.getsize(p) > total = sizeof_fmt(s+shx1+p1) If shx didn't exist shx1 will not exist and the code will fail here I think. > aRow= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 1, > prjtext, crea, modificacion, acceso, total, maquina, user] > writer.writerow(aRow) Could you simplify what you write to get rid of the extra data and see if the fault remains? > else: > #Sino asignar 0 > #no_prj = 'Sin prj, no se puede determinar la > proyeccion' > total = sizeof_fmt(s+shx1) > aRow1= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 0, > prjtext, crea, modificacion, acceso, total, maquina, user] > writer.writerow(aRow1) > log.close() > f.close() > print "El archivo esta listo" I doubt the rest of the code contributes to the error so I didn't read it... > root = Tk() > top = Toplevel() #Llamo una nueva ventana #Dimensiones de la ventana > root.minsize(400,200) #Barra de herramientas > toolbar = Frame(root) #Botones > b = Button(toolbar, text="Selecciona ruta", width=15, command=directorio) > b.pack(side=LEFT, padx=2, pady=2) > b = Button(toolbar, text="Escriba extension", width=15, command=extension) > b.pack(side=LEFT, padx=2, pady=2) > b = Button(toolbar, text="Nombre de csv", width=15, command=csv_w) > b.pack(side=LEFT, padx=2, pady=2) > b = Button(toolbar, text="Aceptar", width=6, command=buscar) > b.pack(side=LEFT, padx=2, pady=2) > toolbar.pack(side=TOP, fill=X) > root.mainloop() HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sander.sweers at gmail.com Tue Sep 13 21:05:53 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 13 Sep 2011 21:05:53 +0200 Subject: [Tutor] Unusual pathfile In-Reply-To: References: Message-ID: <1315940753.1480.11.camel@Nokia-N900> On Tue, 13 Sep 2011, 21:01:56 CEST, Alan Gauld wrote: > On 13/09/11 16:41, Susana Iraiis Delgado Rodriguez wrote: > > structure. About the indention for the code, I tried my best to make it > > clear ande neat. But the mi e-mail editor it's mixing-up spaces. > > OK, That's unfortunate. Which editor/email tool are you using? > We may be able to suggest alternate settings. Then use a pastebin like pastebin.com. It also can do proper python syntax highlighting which make reviewing much easier. Greets sander -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Sep 13 21:15:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Sep 2011 20:15:15 +0100 Subject: [Tutor] cmd window In-Reply-To: References: Message-ID: On 13/09/11 18:57, Dinara Vakhitova wrote: > Hello, > > Excuse me for my stupid question, but I'm an absolute beginner in > programming. Its not stupid and many have asked it before you :-) > can't even see it. The solution must be very simple, but I can't find it > in tutorials... You're obviously reading the wrong tutorials :-) It's covered in the "Add a Little style" topic in my tutorial. Its near the bottom of the page, in the box "Note for Windows Users"... It offers several different ways to deal with it depending on what you want to do. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Tue Sep 13 21:09:02 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 15:09:02 -0400 Subject: [Tutor] cmd window In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB4213@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Dinara Vakhitova Sent: Tuesday, September 13, 2011 1:55 PM To: Wayne Werner Cc: tutor at python.org Subject: Re: [Tutor] cmd window Thank you a lot, it helped! 2011/9/13 Wayne Werner > On Tue, Sep 13, 2011 at 12:57 PM, Dinara Vakhitova > wrote: Hello, Excuse me for my stupid question, but I'm an absolute beginner in programming. I just would like to know what should I do in such case: when I run my program by clicking on the file itself, rather than from IDLE, the cmd window disappears just immediately after the output printing, so that I can't even see it. The solution must be very simple, but I can't find it in tutorials... This is mainly because in later versions of Windows (XP onward, I believe) they changed a setting so that the command window would close after a program has executed. There are probably some more complicated settings to fix it on a global basis, but you'll find that most people add this line to the end of their programs: raw_input("Press to continue") # Use input() with Python 3.x HTH, Wayne -- Yours faithfully, Dinara Vakhitova You can also run from command line. Start->run-> type "cmd" ->hit enter -> navigate to directory "cd c:\directory\with\python\filename.py" (substitute the path you need) -> run script "python filename.py" Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Sep 13 21:01:09 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Sep 2011 15:01:09 -0400 Subject: [Tutor] Unusual pathfile In-Reply-To: References: <4E6F8C42.4070709@pearwood.info> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16BB41D4@EMARC112VS01.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Marc Tompkins Sent: Tuesday, September 13, 2011 12:38 PM To: tutor at python.org Subject: Re: [Tutor] Unusual pathfile Susana - I think I speak for everyone when I say: don't go away! Nobody's complaining about your question; that's what the list is for. However, we're all human beings, and all doing this voluntarily. So it's in your best interest to make your questions easy for us to read. So many lines all run together, with only one space of indentation, makes my head hurt when I try to read it; I'm ashamed to admit that I simply skipped over your question when you first posted it. Others put more effort into it, and have told you why it was hard for them. Don't be offended! At least they took the trouble, which is more than I did. Two things you can do to make this better: - Set your text editor to convert tabs to spaces, preferably four spaces. This is a Good Thing To Do anyway, because some of the hardest bugs to find - for you as well as for us - happen when Python gets confused about levels of indentation. If you're not sure how to change that setting, just tell us which editor you use and someone can help with that. - When you ask a question - and we WANT you to ask questions! - try to narrow down your program to just the part that's giving you trouble. It makes it MUCH easier for us to help you, and quite often it helps you to find the problem yourself. As Steven said above, at the moment I can't even see which part of your code is generating "C:\/Python26", let alone help you to correct it. Just remember: we all want to help; speaking for myself, I started out asking questions on this list and have stuck around to answer them. But we're all human too - and speaking for myself, sometimes we're a little lazy. ======================================================================================= Not to mention, all of us have different levels of understanding for languages. I understand English, but little else. :) I think I can narrow down the problem section. (And this is my third try. As I was indenting, I saw that I could continue narrowing down the section). def buscar(): print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(dir): ### Add print statement here ## file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extn)) I am not very familiar with the os module, but I would suggesting adding a print/debug statement in the loop to print root, folders, files so that you can see if something incorrect is happening. This will also give you a much better "stack trace" to see the progress of your application. Small sample of what I got: c:\tmp\m2\localrepo\saxpath ['saxpath'] [] c:\tmp\m2\localrepo\saxpath\saxpath ['1.0-FCS'] [] c:\tmp\m2\localrepo\saxpath\saxpath\1.0-FCS [] ['saxpath-1.0-FCS.jar', 'saxpath-1.0-FCS.jar.sha1', 'saxpath-1.0-FCS.pom', 'saxpath-1.0-FCS.pom.sha1', '_maven.repositories'] This does not show the behavior you are suggesting. Is there somewhere else that you were referring to? Is it possible you are changing directory or something in the middle of the os.walk command and that is causing it to re-execute the walk? (Python 2.6 / Win7) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From di.marvellous at gmail.com Tue Sep 13 21:30:31 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Tue, 13 Sep 2011 23:30:31 +0400 Subject: [Tutor] cmd window In-Reply-To: References: Message-ID: Thank you, Ramit and thank you, Alan! I have so many tutorials around me that I'm a little bit lost in the materials! Now I'll be focusing on "Learning to Program" by Alan Gauld. :) 2011/9/13 Alan Gauld > On 13/09/11 18:57, Dinara Vakhitova wrote: > >> Hello, >> >> Excuse me for my stupid question, but I'm an absolute beginner in >> programming. >> > > Its not stupid and many have asked it before you :-) > > > can't even see it. The solution must be very simple, but I can't find it >> in tutorials... >> > > You're obviously reading the wrong tutorials :-) > > It's covered in the "Add a Little style" topic in my tutorial. > Its near the bottom of the page, in the box "Note for Windows Users"... > > It offers several different ways to deal with it depending > on what you want to do. > > HTH, > > -- > Alan G > 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 > -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjhartley at gmail.com Wed Sep 14 21:44:06 2011 From: jjhartley at gmail.com (James Hartley) Date: Wed, 14 Sep 2011 12:44:06 -0700 Subject: [Tutor] telnetlib's read_very_eager() method? Message-ID: I'm trying to programmatically create a telnet session. Within the interactive environment, this appears to work very well as server messages can be saved as strings: $ python Python 2.7.1 (r271:86832, Sep 3 2011, 01:32:33) [GCC 4.2.1 20070719 ] on openbsd5 Type "help", "copyright", "credits" or "license" for more information. >>> import telnetlib >>> tn = telnetlib.Telnet('gmail-smtp-in.l.google.com', 25) >>> s = tn.read_very_eager() >>> print s 220 mx.google.com ESMTP r70si1582241yhm.54 >>> tn.write("helo\n") >>> s = tn.read_very_eager() >>> print s 250 mx.google.com at your service >>> tn.write("quit\n") >>> s = tn.read_very_eager() >>> print s 221 2.0.0 closing connection r70si1582241yhm.54 >>> $ These server response can then be parsed to determine what commands need to be provided next. Yet when I execute the same methods in a script, I am getting nothing in response: $ cat script.py #!/usr/bin/env python import telnetlib if __name__ == '__main__': print 'begin' tn = telnetlib.Telnet('gmail-smtp-in.l.google.com', 25) s = tn.read_very_eager() print s tn.write("helo\n") s = tn.read_very_eager() print s tn.write("quit\n") s = tn.read_very_eager() print s print 'end' $ python script.py begin end $ What do I need to do to emulate the IDE environment? If I am needing to capture stdout, it isn't readily apparent. Any insight you can share would be greatly appreciated. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Sep 14 21:54:17 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 14 Sep 2011 20:54:17 +0100 Subject: [Tutor] telnetlib's read_very_eager() method? In-Reply-To: References: Message-ID: On 14 September 2011 20:44, James Hartley wrote: > #!/usr/bin/env python > > import telnetlib > > if __name__ == '__main__': > print 'begin' > tn = telnetlib.Telnet('gmail-smtp-in.l.google.com', 25) > s = tn.read_very_eager() > print s > tn.write("helo\n") > s = tn.read_very_eager() > print s > tn.write("quit\n") > s = tn.read_very_eager() > print s > print 'end' > $ python script.py > begin > > > > end > $ > > What do I need to do to emulate the IDE environment? If I am needing to > capture stdout, it isn't readily apparent. > Make it go slower or force it to read *some* data at least. Interactively there's plenty of time for data to arrive for read_very_eager() to read. When run as a batch your computer tries to read and continue before any data's been returned from google. Hence, try using read_some() instead of read_very_eager(). Aside: If you want to interact with a mail server there's probably better modules to be using than the telnet module. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjhartley at gmail.com Wed Sep 14 22:03:30 2011 From: jjhartley at gmail.com (James Hartley) Date: Wed, 14 Sep 2011 13:03:30 -0700 Subject: [Tutor] telnetlib's read_very_eager() method? In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 12:54 PM, Walter Prins wrote: > Hence, try using read_some() instead of read_very_eager(). > read_some() captures what I was hoping to catch. Thanks! > > Aside: If you want to interact with a mail server there's probably better > modules to be using than the telnet module. > > Do you have any suggestions? Thank you again for your quick reply. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Sep 14 22:13:38 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 14 Sep 2011 21:13:38 +0100 Subject: [Tutor] telnetlib's read_very_eager() method? In-Reply-To: References: Message-ID: On 14 September 2011 21:03, James Hartley wrote: > On Wed, Sep 14, 2011 at 12:54 PM, Walter Prins wrote: > >> Hence, try using read_some() instead of read_very_eager(). >> > > read_some() captures what I was hoping to catch. Thanks! > > >> >> Aside: If you want to interact with a mail server there's probably better >> modules to be using than the telnet module. >> >> > Do you have any suggestions? > The smtplib module: http://docs.python.org/library/smtplib.html Cheers, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjhartley at gmail.com Wed Sep 14 22:40:18 2011 From: jjhartley at gmail.com (James Hartley) Date: Wed, 14 Sep 2011 13:40:18 -0700 Subject: [Tutor] telnetlib's read_very_eager() method? In-Reply-To: References: Message-ID: On Wed, Sep 14, 2011 at 1:13 PM, Walter Prins wrote: > On 14 September 2011 21:03, James Hartley wrote: > >> On Wed, Sep 14, 2011 at 12:54 PM, Walter Prins wrote: >> > Aside: If you want to interact with a mail server there's probably better >> modules to be using than the telnet module. >> >>> >>> >> Do you have any suggestions? >> > > The smtplib module: http://docs.python.org/library/smtplib.html > Wow, I wasn't aware this existed. It appears to have what I was looking for, too. My goal was to validate email addresses in bulk, so this reduces the code I need to write. I also see that VRFY is disabled on some MX servers, so I may have to resort to telnetlib's read_some() yet. :-) Thanks, again for your comments. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From illusiontechniques at gmail.com Thu Sep 15 04:01:16 2011 From: illusiontechniques at gmail.com (c smith) Date: Wed, 14 Sep 2011 22:01:16 -0400 Subject: [Tutor] making lists of prime numbers Message-ID: hi list, i am trying the MIT opencourseware assignments. one was to find the 1000th prime. since this isn't actually my homework, I modified the solution as I would like to collect lists of primes and non-primes up to N, also some log() ratio to one comparison. here is what I came up with on paper: #!/usr/bin/env python import sys, os, math def main(a): notprime = [] primelist = [2,3] nprime = sys.argv[1] numcheck = 4 while len(primelist) < nprime: for i in range(2,numcheck-1): if numcheck % i == 0: print numcheck,'is not prime' notprime.append(numcheck) numcheck += 1 break if i == numcheck and numcheck % i !=0: print numcheck, 'is prime' primelist.append(numcheck) numcheck += 1 break TwotoN = 0 for j in primelist: TwotoN += log(j) print 'sum of logs of primes from 2 to', nprime,'is',TwotoN print 'the ratio of this sum to 1 is' %f % (float(TwotoN)/nprime) if __name__=='__main__': main(sys.argv[1]) my questions would be: am I passing arguments from the command line correctly? this seems to count by twos (going through both 'if statements' maybe?) I thought the 'break' would send control back to the 'while' basically, is there an obvious problem here or is it just completely wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Sep 15 04:35:24 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 15 Sep 2011 04:35:24 +0200 Subject: [Tutor] making lists of prime numbers In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 4:01 AM, c smith wrote: > hi list, i am trying the MIT opencourseware assignments. > one was to find the 1000th prime. > since this isn't actually my homework, I modified the solution as I would > like to collect lists of primes and non-primes up to N, also some log() > ratio to one comparison. > here is what I came up with on paper: > #!/usr/bin/env python > import sys, os, math > > def main(a): > notprime = [] > primelist = [2,3] > nprime = sys.argv[1] > numcheck = 4 > while len(primelist) < nprime: > for i in range(2,numcheck-1): > if numcheck % i == 0: > print numcheck,'is not prime' > notprime.append(numcheck) > numcheck += 1 > break > if i == numcheck and numcheck % i !=0: > print numcheck, 'is prime' > primelist.append(numcheck) > numcheck += 1 > break > TwotoN = 0 > for j in primelist: > TwotoN += log(j) > print 'sum of logs of primes from 2 to', nprime,'is',TwotoN > print 'the ratio of this sum to 1 is' %f % (float(TwotoN)/nprime) > if __name__=='__main__': > main(sys.argv[1]) > > my questions would be: > am I passing arguments from the command line correctly? > this seems to count by twos (going through both 'if statements' maybe?) > I thought the 'break' would send control back to the 'while' > basically, is there an obvious problem here or is it just completely wrong? > I'd say the obvious problem is your second if statement. Its guard will never be true. i goes through range(2,numcheck-1). The highest number in that range in numcheck-2, so i==numcheck will never be true. Even if you'd get i to equal numcheck somehow, numcheck % i would then ber equal to numcheck % numcheck, which equals 0, so numcheck % i != 0 would not be true. The obvious thing to do seems to be to get this code out of the for loop, without and if statement guarding it. Another thing that goes wrong is: nprime = sys.argv[1] You use nprime as an integer, but sys.argv[1] is a string. You should thus change this into nprime = int(sys.argv[1]) However, for the sake of reusability, it's better to have a function that gets the first n primes for n decided by the caller than to have a function that gets the first n primes for n always being the first argument, thus I would change it to: nprime = int(a) -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Sep 15 10:36:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Sep 2011 09:36:11 +0100 Subject: [Tutor] making lists of prime numbers In-Reply-To: References: Message-ID: On 15/09/11 03:01, c smith wrote: > am I passing arguments from the command line correctly? Yes, although not converting to an int. > this seems to count by twos (going through both 'if statements' maybe?) > I thought the 'break' would send control back to the 'while' > basically, is there an obvious problem here or is it just completely wrong? It might work once you iron out the bugs but it's horribly inefficient. It will take a very long time to run for large numbers. Did you try searching for prime number algorithms? There are several that will be much faster than this. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Sep 15 14:20:25 2011 From: d at davea.name (Dave Angel) Date: Thu, 15 Sep 2011 08:20:25 -0400 Subject: [Tutor] making lists of prime numbers In-Reply-To: References: Message-ID: <4E71ED89.6090807@davea.name> On 09/14/2011 10:35 PM, Andre Engels wrote: > On Thu, Sep 15, 2011 at 4:01 AM, c smithwrote: > >> hi list, i am trying the MIT opencourseware assignments. >> one was to find the 1000th prime. >> since this isn't actually my homework, I modified the solution as I would >> like to collect lists of primes and non-primes up to N, also some log() >> ratio to one comparison. >> here is what I came up with on paper: >> #!/usr/bin/env python >> import sys, os, math >> >> def main(a): >> notprime = [] >> primelist = [2,3] >> nprime = sys.argv[1] >> numcheck = 4 >> while len(primelist)< nprime: >> for i in range(2,numcheck-1): >> if numcheck % i == 0: >> print numcheck,'is not prime' >> notprime.append(numcheck) >> numcheck += 1 >> break >> if i == numcheck and numcheck % i !=0: >> print numcheck, 'is prime' >> primelist.append(numcheck) >> numcheck += 1 >> break >> TwotoN = 0 >> for j in primelist: >> TwotoN += log(j) >> print 'sum of logs of primes from 2 to', nprime,'is',TwotoN >> print 'the ratio of this sum to 1 is' %f % (float(TwotoN)/nprime) >> if __name__=='__main__': >> main(sys.argv[1]) >> >> my questions would be: >> am I passing arguments from the command line correctly? >> this seems to count by twos (going through both 'if statements' maybe?) >> I thought the 'break' would send control back to the 'while' >> basically, is there an obvious problem here or is it just completely wrong? >> > I'd say the obvious problem is your second if statement. Its guard will > never be true. i goes through range(2,numcheck-1). The highest number in > that range in numcheck-2, so i==numcheck will never be true. Even if you'd > get i to equal numcheck somehow, numcheck % i would then ber equal to > numcheck % numcheck, which equals 0, so numcheck % i != 0 would not be true. > > The obvious thing to do seems to be to get this code out of the for loop, > without and if statement guarding it. > > Another thing that goes wrong is: > > nprime = sys.argv[1] > > You use nprime as an integer, but sys.argv[1] is a string. You should thus > change this into > > nprime = int(sys.argv[1]) > > However, for the sake of reusability, it's better to have a function that > gets the first n primes for n decided by the caller than to have a function > that gets the first n primes for n always being the first argument, thus I > would change it to: > > nprime = int(a) > As Andre and Alan have said, there are some problems with your code. However, the basic concept is reasonable. I wouldn't worry much about efficiency, yet. Get it to work reliably, then figure how to tune it. And if you have a source control system (like git, svn, mercurial), check in each version that works, so you can always compare to what you currently have. Your specific questions: 1) you're passing the (one) argument from the command line reasonably, though I'd convert it to int before passing it, and I'd change the formal parameter name of it in your function to nprime. Then you don't need any additional assignment in the function. 2) it seems to count by twos because of the problems with your second if, as Andre has said. Start by fixing the second if statement. There are two ways to fix it. a) change the condition so it detects the end of the loop, which in your case is numcheck-2. Catch to that is that when you realize you can optimize the loop, you'll have to remember to change the if to match. b) move the code outside of the loop. However, you'd also have to make sure it *didn't* get executed if the first if statement did. That could be a real pain, except that Python has a nice "else" clause you can attach to a loop, that only gets executed if the loop completes normally. That else is exactly what you want, so it makes it straightforward. Once you see it generating the correct primes, you may notice that it sails right past the nprimes value. That'll get fixed when you add the int() function when calling main(). Comparing int to string usually doesn't do what you'd want. next problem you'll have is the log function, which is defined in math. So you want to call math.log() next problem is the misplaced quotes on the last print statement. You'll get an error when you hit that one. Finally, the wording of those two prints is all wrong, so you might want to fix it so it matches what the code does. HTH -- DaveA From rdmoores at gmail.com Thu Sep 15 20:19:11 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 15 Sep 2011 11:19:11 -0700 Subject: [Tutor] What's the keyword for the Python creed? Message-ID: You know, at the interactive prompt you enter some Monty Python word that I can't remember, and you get a small list of pithy pythonic advice such as "explicit is better than implicit", etc. Thanks, Dick Moores From sirgnip at gmail.com Thu Sep 15 20:24:57 2011 From: sirgnip at gmail.com (Scott Nelson) Date: Thu, 15 Sep 2011 13:24:57 -0500 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: References: Message-ID: On Thu, Sep 15, 2011 at 1:19 PM, Richard D. Moores wrote: > You know, at the interactive prompt you enter some Monty Python word > that I can't remember, and you get a small list of pithy pythonic > advice such as "explicit is better than implicit", etc. > import this You can also do... import antigravity ...for another Pythonic easter egg... Though I think this one requires Python 3? 2.7? Can't remember. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfrage8765 at gmail.com Thu Sep 15 20:25:33 2011 From: wolfrage8765 at gmail.com (Jordan) Date: Thu, 15 Sep 2011 11:25:33 -0700 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: References: Message-ID: <4E72431D.90902@gmail.com> I think you mean the Zen of Python: http://www.python.org/dev/peps/pep-0020/ The command is >>> import this -- Jordan On 09/15/2011 11:19 AM, Richard D. Moores wrote: > You know, at the interactive prompt you enter some Monty Python word > that I can't remember, and you get a small list of pithy pythonic > advice such as "explicit is better than implicit", etc. > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From ramit.prasad at jpmorgan.com Thu Sep 15 20:30:09 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Sep 2011 14:30:09 -0400 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16CEFC98@EMARC112VS01.exchad.jpmchase.net> >import antigravity >...for another Pythonic easter egg... ?Though I think this one requires Python 3? ?2.7? ?Can't remember. Works in 2.7 but not 2.6.4 Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rdmoores at gmail.com Thu Sep 15 20:57:36 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 15 Sep 2011 11:57:36 -0700 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: <61310E38B60C8F4AB59757E88A3C967723F3020CD5@UMDAC-CCR2.ad.umu.se> References: <61310E38B60C8F4AB59757E88A3C967723F3020CD5@UMDAC-CCR2.ad.umu.se> Message-ID: Thanks, all. Good to have that at hand. antigravity: any more? Dick From emekamicro at gmail.com Fri Sep 16 01:50:31 2011 From: emekamicro at gmail.com (Emeka) Date: Fri, 16 Sep 2011 01:50:31 +0200 Subject: [Tutor] Please review my code Message-ID: Hello All, While trying to learn Python I developed a small game, Text Text. It has rough edges and may not meet your class. However, by reviewing it you'll be helping me to advance. It was only tested on a Windows Box, but I see no reason why it would not work on Unix family. https://github.com/janus/Text-Twist I need you comments. -- *Regards, Emeka * -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjreynol13 at aol.com Fri Sep 16 04:22:09 2011 From: cjreynol13 at aol.com (Chad Reynolds) Date: Thu, 15 Sep 2011 22:22:09 -0400 Subject: [Tutor] help importing pygame Message-ID: For starters, I am a newish python programmer, far enough along to have my feet wet. Running Mac OSX Lion (10.7), and python 2.7.2. I am trying to expand my knowledge and use some packages outside of the base python library. Games are interesting so I decided I'd try pygame after reading many good things about it. Now I have been to the site and downloaded the install package for OSX Lion, and run it successfully. But when I try to run the example on the site (line by line chimp example) I get this error message: Traceback (most recent call last): File "/private/var/folders/j4/10dtxgh14hl6vdvzzhbbqzdc0000gn/T/Cleanup At Startup/untitled text 4-337832000.071", line 11, in import os, pygame File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in from pygame.base import * ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, 2): no suitable image found. Did find: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: no matching architecture in universal wrapper The program hasn't even made it anywhere else in the code, and I really don't understand what the problem is. Help would be much appreciated, thank you all From swiftone at swiftone.org Fri Sep 16 04:35:37 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Thu, 15 Sep 2011 22:35:37 -0400 Subject: [Tutor] Strange zip syntax Message-ID: I ran into this article ( http://blog.adku.com/2011/09/hodgepodge-of-python.html ) and found myself temporarily stymied by one line it in: zip(*[iter(a)]*2) Used like this: >>> a = ['a','1','b','2','c','3'] >>> zip(*[iter(a)]*2) [('a', '1'), ('b', '2'), ('c', '3')] While I'm unlikely to use such a construct (if I can't easily follow it now, I or my successor likely won't follow it should it need to be debugged sometime in the future), I found the education I got in deciphering it was worth the effort. I'm sharing it here so others can benefit from my puzzlement. iter(a) returns a list iterator for a. See help(iter) for more. [iter(a)] is a list containing one element, an iterator. This is created only so we can do the below: [iter(a)]*2 is a list containing two elements, each the SAME list iterator. For simplicity, let's break this out for further analysis: >>> b = iter(a) >>> c = [b,b] *[iter(a)]*2 flattens the list when passed into a function call. Using our more verbose but simple syntax: *c. This only works when passed to a function. zip() creates tuples each holding the Nth elements from a number of sequences. See help(zip) for more. Thus, zip(a) or zip(a,a) would return: >>> zip(a) [('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] >>> zip(a,a) [('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] What happens when we pass an iterator to zip? That's not mentioned in the docstring blurb. >>> zip(iter(a)) [('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] Answer: It works as intended. Now we come to the magic of this little snippet. zip(iter(a),iter(a)) wouldn't work, because each call to iter(a) returns a DIFFERENT iterator. >>> zip(iter(a), iter(a)) [('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] But by creating the list of two elements each of which is the SAME iterator, as each is asked to iterate it advances the common element indicator: >>> zip(*c) [('a', '1'), ('b', '2'), ('c', '3')] Notice that the flattening is required, because zip needs to get multiple arguments: >>> b = iter(a) #our original iterator is spent, so we're assigning a new one >>> c = [b,b] >>> zip(c) #Not flattened, is just a single list, like a. [(,), (,)] >>> zip(b,b) # here it is two iterators sent to zip() (though they happen to be the SAME iterator) [('a', '1'), ('b', '2'), ('c', '3')] I hope some of you enjoy playing with this, and hopefully someone learned something useful! While I'm not likely to use the listed form, I can very well see myself saying: >>> a = ['a','1','b','2','c','3'] #well, I can see myself using this with meaningful variable names >>> b = iter(a) >>> zip(b,b) # Group in sets of 2 elements -- Brett Ritter / SwiftOne swiftone at swiftone.org From cwitts at compuscan.co.za Fri Sep 16 08:47:05 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 16 Sep 2011 08:47:05 +0200 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: References: <61310E38B60C8F4AB59757E88A3C967723F3020CD5@UMDAC-CCR2.ad.umu.se> Message-ID: <4E72F0E9.5080504@compuscan.co.za> On 2011/09/15 08:57 PM, Richard D. Moores wrote: > Thanks, all. Good to have that at hand. > > antigravity: any more? > > Dick > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > from __future__ import braces :) -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Fri Sep 16 09:12:40 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 16 Sep 2011 00:12:40 -0700 Subject: [Tutor] What's the keyword for the Python creed? In-Reply-To: <4E72F0E9.5080504@compuscan.co.za> References: <61310E38B60C8F4AB59757E88A3C967723F3020CD5@UMDAC-CCR2.ad.umu.se> <4E72F0E9.5080504@compuscan.co.za> Message-ID: On Thu, Sep 15, 2011 at 23:47, Christian Witts wrote: > from __future__ import braces Ha! (2.7 and 3.x) Dick From bodsda at googlemail.com Fri Sep 16 09:41:23 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Fri, 16 Sep 2011 07:41:23 +0000 Subject: [Tutor] If statement optimization Message-ID: <606259109-1316158883-cardhu_decombobulator_blackberry.rim.net-486964431-@b28.c12.bise7.blackberry> Hi, In a normal if,elif,elif,...,else statement, are the conditions checked in a linear fashion? I am wondering if I should be making an effort to put the most likely true condition at the beginning of the block Thanks, Bodsda Sent from my BlackBerry? wireless device From steve at pearwood.info Fri Sep 16 12:43:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 16 Sep 2011 20:43:45 +1000 Subject: [Tutor] If statement optimization In-Reply-To: <606259109-1316158883-cardhu_decombobulator_blackberry.rim.net-486964431-@b28.c12.bise7.blackberry> References: <606259109-1316158883-cardhu_decombobulator_blackberry.rim.net-486964431-@b28.c12.bise7.blackberry> Message-ID: <4E732861.1000306@pearwood.info> bodsda at googlemail.com wrote: > Hi, > > In a normal if,elif,elif,...,else statement, are the conditions checked in a linear fashion? Yes. > I am wondering if I should be making an effort to put the most likely true condition at the beginning of the block Probably not. The amount of time used in the average if...elif is unlikely to be significant itself. Don't waste your time trying to optimize something like this: if n < 0: ... elif n == 0: ... else: ... However, there are exceptions. If the tests are very expensive, then it might be worthwhile putting the most likely case first. Or at least, put the cheapest cases first, leave the expensive ones for last: if sum(mylist[1:]) > 1000 and mylist.count(42) == 3 and min(mylist) < 0: ... elif len(mylist) < 5: ... I probably should swap the order there, get the cheap len() test out of the way, and only perform the expensive test if that fails. If you have LOTS of elif cases, like *dozens*, then firstly you should think very hard about re-writing your code, because that's pretty poor design... but if you can't change the design, then maybe it is worthwhile to rearrange the cases. If you have something like this: if s == "spam": func_spam(x) elif s == "ham": func_ham(x) elif s == "cheese": func_cheese(x) you can often turn this into a dispatch table: table = {"spam": func_spam, "ham": func_ham, "cheese": func_cheese} func = table[s] # lookup in the dispatch table func(x) # finally call the function Note that inside table, you don't call the functions. This pattern is especially useful, as lookup in a table in this manner takes close enough to constant time, whether there is one item or a million. -- Steven From bodsda at googlemail.com Fri Sep 16 13:17:17 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Fri, 16 Sep 2011 11:17:17 +0000 Subject: [Tutor] If statement optimization In-Reply-To: <4E732861.1000306@pearwood.info> References: <606259109-1316158883-cardhu_decombobulator_blackberry.rim.net-486964431-@b28.c12.bise7.blackberry><4E732861.1000306@pearwood.info> Message-ID: <1468017522-1316171837-cardhu_decombobulator_blackberry.rim.net-196998180-@b28.c12.bise7.blackberry> Thanks for the explanation - very clear. Cheers, Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Steven D'Aprano Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Fri, 16 Sep 2011 20:43:45 To: Tutor - python List Subject: Re: [Tutor] If statement optimization bodsda at googlemail.com wrote: > Hi, > > In a normal if,elif,elif,...,else statement, are the conditions checked in a linear fashion? Yes. > I am wondering if I should be making an effort to put the most likely true condition at the beginning of the block Probably not. The amount of time used in the average if...elif is unlikely to be significant itself. Don't waste your time trying to optimize something like this: if n < 0: ... elif n == 0: ... else: ... However, there are exceptions. If the tests are very expensive, then it might be worthwhile putting the most likely case first. Or at least, put the cheapest cases first, leave the expensive ones for last: if sum(mylist[1:]) > 1000 and mylist.count(42) == 3 and min(mylist) < 0: ... elif len(mylist) < 5: ... I probably should swap the order there, get the cheap len() test out of the way, and only perform the expensive test if that fails. If you have LOTS of elif cases, like *dozens*, then firstly you should think very hard about re-writing your code, because that's pretty poor design... but if you can't change the design, then maybe it is worthwhile to rearrange the cases. If you have something like this: if s == "spam": func_spam(x) elif s == "ham": func_ham(x) elif s == "cheese": func_cheese(x) you can often turn this into a dispatch table: table = {"spam": func_spam, "ham": func_ham, "cheese": func_cheese} func = table[s] # lookup in the dispatch table func(x) # finally call the function Note that inside table, you don't call the functions. This pattern is especially useful, as lookup in a table in this manner takes close enough to constant time, whether there is one item or a million. -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From amonroe at columbus.rr.com Fri Sep 16 13:20:33 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri, 16 Sep 2011 07:20:33 -0400 Subject: [Tutor] Please review my code In-Reply-To: References: Message-ID: <281138045873.20110916072033@columbus.rr.com> > It was only tested on a Windows Box, but I see no reason why it would not > work on Unix family. https://github.com/janus/Text-Twist > I need you comments. I think you forgot to upload some needed images along with the python code: ['abase', 'abased', 'abed', 'ads', 'baa', 'baas', 'bad', 'bade', 'bas', 'base', 'based', 'bead', 'beads', 'bed', 'beds', 'dab', 'dab s', 'debs', 'sad', 'sea'] Traceback (most recent call last): File "haPu3.py", line 36, in IMAGE = PhotoImage(file=doom_image) #'C:\Python_way\doom2.gif') File "c:\python25\lib\lib-tk\Tkinter.py", line 3294, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "c:\python25\lib\lib-tk\Tkinter.py", line 3250, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open ".\doom2.gif": no such file or directory Alan From fomcl at yahoo.com Fri Sep 16 15:16:17 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 16 Sep 2011 06:16:17 -0700 (PDT) Subject: [Tutor] Strange zip syntax In-Reply-To: References: Message-ID: <1316178977.44515.YahooMailNeo@web110701.mail.gq1.yahoo.com> Hi, ? I would write the slightly longer, but more readable (for me at least) code: >>> a = ['a','1','b','2','c','3'] >>> [(a[i], a[i+1]) for i in range(0, len(a), 2)] [('a', '1'), ('b', '2'), ('c', '3')] >>> zip(*[iter(a)]*2) [('a', '1'), ('b', '2'), ('c', '3')] ? And it's also faster: ? >>> import timeit >>> t = timeit.Timer("zip(*[iter(['a', '1', 'b', '2', 'c', '3'])]*2)") >>> t.timeit() 5.1758860413823555 >>> t = timeit.Timer("a=['a', '1', 'b', '2', 'c', '3']; [(a[i], a[i+1]) for i in range(0, len(a), 2)]") >>> t.timeit() 2.5330216549868823 >>> Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From: Brett Ritter >To: *tutor python >Sent: Friday, September 16, 2011 4:35 AM >Subject: [Tutor] Strange zip syntax > >I ran into this article ( >http://blog.adku.com/2011/09/hodgepodge-of-python.html ) and found >myself temporarily stymied by one line it in: > >zip(*[iter(a)]*2) > >Used like this: > >>>> a = ['a','1','b','2','c','3'] >>>> zip(*[iter(a)]*2) >[('a', '1'), ('b', '2'), ('c', '3')] > >While I'm unlikely to use such a construct (if I can't easily follow >it now, I or my successor likely won't follow it should it need to be >debugged sometime in the future), I found the education I got in >deciphering it was worth the effort.? I'm sharing it here so others >can benefit from my puzzlement. > >iter(a) returns a list iterator for a.? See help(iter) for more. >[iter(a)] is a list containing one element, an iterator.? This is >created only so we can do the below: >[iter(a)]*2 is a list containing two elements, each the SAME list iterator. >For simplicity, let's break this out for further analysis: > >>>> b = iter(a) >>>> c = [b,b] > >*[iter(a)]*2 flattens the list when passed into a function call. >Using our more verbose but simple syntax: *c.? This only works when >passed to a function. >zip() creates tuples each holding the Nth elements from a number of >sequences.? See help(zip) for more. >Thus, zip(a) or zip(a,a) would return: >>>> zip(a) >[('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] >>>> zip(a,a) >[('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] > >What happens when we pass an iterator to zip?? That's not mentioned in >the docstring blurb. >>>> zip(iter(a)) >[('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] >Answer: It works as intended. > >Now we come to the magic of this little snippet. >zip(iter(a),iter(a)) wouldn't work, because each call to iter(a) >returns a DIFFERENT iterator. >>>> zip(iter(a), iter(a)) >[('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] > >But by creating the list of two elements each of which is the SAME >iterator, as each is asked to iterate it advances the common element >indicator: >>>> zip(*c) >[('a', '1'), ('b', '2'), ('c', '3')] >Notice that the flattening is required, because zip needs to get >multiple arguments: >>>> b = iter(a)? #our original iterator is spent, so we're assigning a new one >>>> c = [b,b] >>>> zip(c)? #Not flattened, is just a single list, like a. >[(,), (,)] >>>> zip(b,b)? # here it is two iterators sent to zip() (though they happen to be the SAME iterator) >[('a', '1'), ('b', '2'), ('c', '3')] > >I hope some of you enjoy playing with this, and hopefully someone >learned something useful!? While I'm not likely to use the listed >form, I can very well see myself saying: > >>>> a = ['a','1','b','2','c','3']? #well, I can see myself using this with meaningful variable names >>>> b = iter(a) >>>> zip(b,b)? # Group in sets of 2 elements > >-- >Brett Ritter / SwiftOne >swiftone at swiftone.org >_______________________________________________ >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 emekamicro at gmail.com Fri Sep 16 18:18:44 2011 From: emekamicro at gmail.com (Emeka) Date: Fri, 16 Sep 2011 17:18:44 +0100 Subject: [Tutor] Strange zip syntax In-Reply-To: References: Message-ID: iBrett, iter On Fri, Sep 16, 2011 at 3:35 AM, Brett Ritter wrote: > I ran into this article ( > http://blog.adku.com/2011/09/hodgepodge-of-python.html ) and found > myself temporarily stymied by one line it in: > > zip(*[iter(a)]*2) > > Used like this: > > >>> a = ['a','1','b','2','c','3'] > >>> zip(*[iter(a)]*2) > [('a', '1'), ('b', '2'), ('c', '3')] > > While I'm unlikely to use such a construct (if I can't easily follow > it now, I or my successor likely won't follow it should it need to be > debugged sometime in the future), I found the education I got in > deciphering it was worth the effort. I'm sharing it here so others > can benefit from my puzzlement. > > iter(a) returns a list iterator for a. See help(iter) for more. > [iter(a)] is a list containing one element, an iterator. This is > created only so we can do the below: > [iter(a)]*2 is a list containing two elements, each the SAME list iterator. > For simplicity, let's break this out for further analysis: > > >>> b = iter(a) > >>> c = [b,b] > iter(c) returns listiterator > > *[iter(a)]*2 flattens the list when passed into a function call. > Using our more verbose but simple syntax: *c. This only works when > passed to a function. > zip() creates tuples each holding the Nth elements from a number of > sequences. See help(zip) for more. > Thus, zip(a) or zip(a,a) would return: > >>> zip(a) > [('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] > >>> zip(a,a) > [('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] > > What happens when we pass an iterator to zip? That's not mentioned in > the docstring blurb. > >>> zip(iter(a)) > [('a',), ('1',), ('b',), ('2',), ('c',), ('3',)] > Answer: It works as intended. > > Now we come to the magic of this little snippet. > zip(iter(a),iter(a)) wouldn't work, because each call to iter(a) > returns a DIFFERENT iterator. > >>> zip(iter(a), iter(a)) > [('a', 'a'), ('1', '1'), ('b', 'b'), ('2', '2'), ('c', 'c'), ('3', '3')] > > But by creating the list of two elements each of which is the SAME > iterator, as each is asked to iterate it advances the common element > indicator: > >>> zip(*c) > [('a', '1'), ('b', '2'), ('c', '3')] > Notice that the flattening is required, because zip needs to get > multiple arguments: > >>> b = iter(a) #our original iterator is spent, so we're assigning a new > one > >>> c = [b,b] > >>> zip(c) #Not flattened, is just a single list, like a. > [(,), ( 0x024E32D0>,)] > >>> zip(b,b) # here it is two iterators sent to zip() (though they happen > to be the SAME iterator) > [('a', '1'), ('b', '2'), ('c', '3')] > > I hope some of you enjoy playing with this, and hopefully someone > learned something useful! While I'm not likely to use the listed > form, I can very well see myself saying: > > >>> a = ['a','1','b','2','c','3'] #well, I can see myself using this with > meaningful variable names > >>> b = iter(a) > >>> zip(b,b) # Group in sets of 2 elements > > -- > Brett Ritter / SwiftOne > swiftone at swiftone.org > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From emekamicro at gmail.com Sat Sep 17 00:09:00 2011 From: emekamicro at gmail.com (Emeka) Date: Sat, 17 Sep 2011 00:09:00 +0200 Subject: [Tutor] Please review my code In-Reply-To: <281138045873.20110916072033@columbus.rr.com> References: <281138045873.20110916072033@columbus.rr.com> Message-ID: Hello Alan, My bad, I have added the missing folder. To all, please make out time and review my code. I would like to have your comments. https://github.com/janus/Text-Twist Regards, emeka On Fri, Sep 16, 2011 at 1:20 PM, R. Alan Monroe wrote: > > > It was only tested on a Windows Box, but I see no reason why it would not > > work on Unix family. https://github.com/janus/Text-Twist > > I need you comments. > > I think you forgot to upload some needed images along with the python > code: > > ['abase', 'abased', 'abed', 'ads', 'baa', 'baas', 'bad', 'bade', 'bas', > 'base', 'based', 'bead', 'beads', 'bed', 'beds', 'dab', 'dab > s', 'debs', 'sad', 'sea'] > Traceback (most recent call last): > File "haPu3.py", line 36, in > IMAGE = PhotoImage(file=doom_image) #'C:\Python_way\doom2.gif') > File "c:\python25\lib\lib-tk\Tkinter.py", line 3294, in __init__ > Image.__init__(self, 'photo', name, cnf, master, **kw) > File "c:\python25\lib\lib-tk\Tkinter.py", line 3250, in __init__ > self.tk.call(('image', 'create', imgtype, name,) + options) > _tkinter.TclError: couldn't open ".\doom2.gif": no such file or directory > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at justuber.com Sat Sep 17 13:08:36 2011 From: lists at justuber.com (lists) Date: Sat, 17 Sep 2011 12:08:36 +0100 Subject: [Tutor] Using xml.etree Message-ID: Hi Tutors, I have been trying to learn how to parse XML with Python and learn how to use xml.etree. Lots of the tutorials seem to be very long winded. I'm trying to access a UK postcode API at www.uk-postcodes.com to take a UK postcode and return the lat/lng of the postcode. This is what the XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml The function below returns a dict with the xml tag as a key and the text as a value. Is this a correct way to use xml.etree? Thanks in advance! Chris def ukpostcodesapi(postcode): import urllib import xml.etree.ElementTree as etree baseURL='http://www.uk-postcodes.com/' geocodeRequest='postcode/'+postcode+'.xml' #grab the xml tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest)) root=tree.getroot() results={} for child in root[1]: #here's the geo tag results.update({child.tag:child.text}) #build a dict containing the geocode data return results #example usage (testing the function) results = ukpostcodesapi('hu11aa') print results['lat']+' '+results['lng'] From matthewpirritano at sbcglobal.net Sun Sep 18 01:51:19 2011 From: matthewpirritano at sbcglobal.net (Matthew Pirritano) Date: Sat, 17 Sep 2011 16:51:19 -0700 Subject: [Tutor] string formatting Message-ID: <001101cc7594$b37bdaf0$1a7390d0$@net> All, I know that I can do this: "the %s is %s" % ('sky', 'blue') But I have very large blocks of text and I thought there was another way like X = "sky" Y = "blue" "the %(X)s is %(Y)s" But I've tried this and it is not working. I'm just trying to get it to work in the interpreter right now. I'm using python 2.6.5. I need to use this version because it is compatible with the software that it is working with (SPSS). What am I missing? Thanks Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Sep 18 02:03:18 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 17 Sep 2011 20:03:18 -0400 Subject: [Tutor] string formatting In-Reply-To: <001101cc7594$b37bdaf0$1a7390d0$@net> References: <001101cc7594$b37bdaf0$1a7390d0$@net> Message-ID: On Sat, Sep 17, 2011 at 7:51 PM, Matthew Pirritano < matthewpirritano at sbcglobal.net> wrote: > All,**** > > ** ** > > I know that I can do this:**** > > ** ** > > "the %s is %s" % ('sky', 'blue')**** > > ** ** > > But I have very large blocks of text and I thought there was another way > like**** > > ** ** > > X = ?sky?**** > > Y = ?blue?**** > > ** ** > > "the %(X)s is %(Y)s" > Try this: "the %s is %s" % (X,Y) > **** > > ** ** > > But I?ve tried this and it is not working. I?m just trying to get it to > work in the interpreter right now.**** > > ** ** > > I?m using python 2.6.5. I need to use this version because it is compatible > with the software that it is working with (SPSS).**** > > ** ** > > What am I missing?**** > > ** ** > > Thanks**** > > Matt**** > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From sivanorkin at gmail.com Sun Sep 18 02:06:26 2011 From: sivanorkin at gmail.com (Sivan Orkin) Date: Sun, 18 Sep 2011 02:06:26 +0200 Subject: [Tutor] string formatting In-Reply-To: <001101cc7594$b37bdaf0$1a7390d0$@net> References: <001101cc7594$b37bdaf0$1a7390d0$@net> Message-ID: On Sun, Sep 18, 2011 at 01:51, Matthew Pirritano < matthewpirritano at sbcglobal.net> wrote: > All,**** > > ** ** > > I know that I can do this:**** > > ** ** > > "the %s is %s" % ('sky', 'blue')**** > > ** ** > > But I have very large blocks of text and I thought there was another way > like**** > > ** ** > > X = ?sky?**** > > Y = ?blue?**** > > ** ** > > "the %(X)s is %(Y)s"**** > > ** ** > > But I?ve tried this and it is not working. I?m just trying to get it to > work in the interpreter right now.**** > > ** ** > > I?m using python 2.6.5. I need to use this version because it is compatible > with the software that it is working with (SPSS).**** > > ** ** > > What am I missing?**** > > ** ** > > Thanks**** > > Matt > Hello Matt, Your problem lies in that Python doesn't know with what to replace the %(name)s. If you use plain %s (with no name in parentheses), Python will use the order of the tuple you give as argument to % to replace the %s in the string. However, if you want to use argument names (like %(x)s), Python needs to know what to replace these with. A hint: % either takes a tuple () as argument, or a dictionary {}. A dictionary has key-value pairs; what would be the key, and what the value? Hope that helps! Sivan -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Sep 18 03:57:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 18 Sep 2011 11:57:56 +1000 Subject: [Tutor] string formatting In-Reply-To: <001101cc7594$b37bdaf0$1a7390d0$@net> References: <001101cc7594$b37bdaf0$1a7390d0$@net> Message-ID: <4E755024.3060501@pearwood.info> Matthew Pirritano wrote: > But I have very large blocks of text and I thought there was another way > like > > X = "sky" > Y = "blue" > "the %(X)s is %(Y)s" Unless you use the string formatting operator %, strings containing "%" are just strings. Large or small, the way you do string formatting is with the % operator. Python will never do string formatting without an explicit command to do so: text % value # Single non-tuple argument text % (value, value, ...) # Multiple arguments They don't have to be string literals, they can be variables: text = "Hello, I'd like to have an %s" value = "argument" print text % value You can also use named arguments by using a dictionary: text = "Hello, I'd like to have an %(X)s" values = {"X": "argument"} print text % values More details in the Fine Manual: http://docs.python.org/library/stdtypes.html#string-formatting Alternatives include the new advanced formatting method: text.format() http://docs.python.org/library/string.html#formatstrings and "$" substitutions with the string module: import string string.Template http://docs.python.org/library/string.html#template-strings -- Steven From emailkgnow at gmail.com Sun Sep 18 11:57:22 2011 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Sun, 18 Sep 2011 12:57:22 +0300 Subject: [Tutor] why is this so? Message-ID: Hi All, why is this so? >>> type('love') >>> "love" is str False >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafadurancastaneda at gmail.com Sun Sep 18 13:13:28 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Sun, 18 Sep 2011 13:13:28 +0200 Subject: [Tutor] why is this so? In-Reply-To: References: Message-ID: You are comparing a string value with string class, so they can't be compared. You can do: >>> type("love") is str True >>> so you compare types 2011/9/18 Khalid Al-Ghamdi > Hi All, > > why is this so? > > >>> type('love') > > >>> "love" is str > False > >>> > > _______________________________________________ > 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 steve at pearwood.info Sun Sep 18 14:46:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 18 Sep 2011 22:46:51 +1000 Subject: [Tutor] why is this so? In-Reply-To: References: Message-ID: <4E75E83B.9080303@pearwood.info> Khalid Al-Ghamdi wrote: > Hi All, > > why is this so? > >>>> type('love') > >>>> "love" is str > False The "is" operator tests for object identity. The line "love" is str tests whether the instance "love" is the same object as the class str. Obviously that is not the case. You might be thinking of an "is-a" test: "love" is a string? For that, you want: isinstance("love", str) which returns True. (That's better than type("love") is str, since it will work for subclasses as well.) But before getting too used to isinstance, you should read this article: http://www.canonical.org/~kragen/isinstance/ -- Steven From lists at justuber.com Mon Sep 19 11:46:13 2011 From: lists at justuber.com (lists) Date: Mon, 19 Sep 2011 10:46:13 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: References: Message-ID: Hello again. So, any xml.etree experts out there who might have missed this over the weekend? Thanks in advance! Chris From mail at timgolden.me.uk Mon Sep 19 12:01:00 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 19 Sep 2011 11:01:00 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: References: Message-ID: <4E7712DC.3070507@timgolden.me.uk> On 19/09/2011 10:46, lists wrote: > Hello again. > > So, any xml.etree experts out there who might have missed this over the weekend? Not me, I'm afraid, but might I suggest that you ask on the mail Python list: http://mail.python.org/mailman/listinfo/python-list There's nothing wrong with asking here, but since this question is more specific to a particular library than to Python-the-language you're more likely to find people familiar with the package (including its maintainer in fact...) TJG From mail at timgolden.me.uk Mon Sep 19 12:05:57 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 19 Sep 2011 11:05:57 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: <4E7712DC.3070507@timgolden.me.uk> References: <4E7712DC.3070507@timgolden.me.uk> Message-ID: <4E771405.6000202@timgolden.me.uk> On 19/09/2011 11:01, Tim Golden wrote: > you're more likely to find people familiar with the package (including > its maintainer in fact...) Sorry, I misread your post and thought you were referring lxml.etree (which is a 3rd-party lib). My basic point still stands, though: you'll get more library-specific help on python-list. TJG From lists at justuber.com Mon Sep 19 13:47:51 2011 From: lists at justuber.com (lists) Date: Mon, 19 Sep 2011 12:47:51 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: <4E771405.6000202@timgolden.me.uk> References: <4E7712DC.3070507@timgolden.me.uk> <4E771405.6000202@timgolden.me.uk> Message-ID: Thanks Tim, Will do. Chris On Mon, Sep 19, 2011 at 11:05 AM, Tim Golden wrote: > On 19/09/2011 11:01, Tim Golden wrote: >> >> you're more likely to find people familiar with the package (including >> its maintainer in fact...) > > Sorry, I misread your post and thought you were referring lxml.etree > (which is a 3rd-party lib). My basic point still stands, though: > you'll get more library-specific help on python-list. > > TJG > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From ashish.gec at gmail.com Mon Sep 19 15:27:26 2011 From: ashish.gec at gmail.com (Ashish Gaonker) Date: Mon, 19 Sep 2011 18:57:26 +0530 Subject: [Tutor] How it is better than java Message-ID: My obvious thinking is : Java being compiled language , must be faster then a interpreted language. I know couple of points : Development time is less + easy to learn + python is expressive. Can you share some more especially as compared to Java / .net (two primarily used languages in enterprise language & web based applications) -- Thanks & Regards Ashish Gaonker -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Mon Sep 19 15:53:53 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 19 Sep 2011 15:53:53 +0200 Subject: [Tutor] How it is better than java In-Reply-To: References: Message-ID: <4E774971.4020306@compuscan.co.za> On 2011/09/19 03:27 PM, Ashish Gaonker wrote: > My obvious thinking is : Java being compiled language , must be faster > then a interpreted language. > > I know couple of points : Development time is less + easy to learn + > python is expressive. > > Can you share some more especially as compared to Java / .net (two > primarily used languages in enterprise language & web based applications) > > -- > Thanks & Regards > Ashish Gaonker > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I would suggest reading `Python is not Java` [1] and `Java is not Python, either` [2], old but good reads. And then ask what is your focus for development. Better is extremely subjective and can be liable to induce flame-wars, although this list is quite friendly. To me, I started using Python as a glue language, controlling process flows and the like, with still heavy uses of C and PL/SQL for what I do. Over time Python has taken center-stage for my projects due to ease-of-use and rapid application development and only moving time critical work that "needs" to be faster to C but in most cases that is not needed for me anymore. Add to that the great work on PyPy [3] which is extremely efficient, I hardly ever have to write in another language if I don't wish. [1] http://dirtsimple.org/2004/12/python-is-not-java.html [2] http://dirtsimple.org/2004/12/java-is-not-python-either.html [3] http://pypy.org/ -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Sep 19 16:13:16 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 19 Sep 2011 15:13:16 +0100 Subject: [Tutor] How it is better than java In-Reply-To: References: Message-ID: Hi Ashish, On 19 September 2011 14:27, Ashish Gaonker wrote: > My obvious thinking is : Java being compiled language , must be faster then > a interpreted language. > > I know couple of points : Development time is less + easy to learn + python > is expressive. > > Can you share some more especially as compared to Java / .net (two > primarily used languages in enterprise language & web based applications) > There's many pages on the internet comparing Python, Java and other languages. I suggest you check them out. Having said that, I'll point out that Python has several implementations, including one called "Jython", which actually targets the Java runtime and so should have comparable performance to Java on the same runtime. Additionally there's projects like PyPy which in some cases is faster even than C/C++. This page (from my bookmarks) has some interesting points of comparison for consideration: http://pythonconquerstheuniverse.wordpress.com/category/java-and-python/ Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From MPirritano at ochca.com Mon Sep 19 17:46:27 2011 From: MPirritano at ochca.com (Pirritano, Matthew) Date: Mon, 19 Sep 2011 08:46:27 -0700 Subject: [Tutor] string formatting In-Reply-To: <4E755024.3060501@pearwood.info> References: <001101cc7594$b37bdaf0$1a7390d0$@net> <4E755024.3060501@pearwood.info> Message-ID: Pythonistas, This is the resolution of a question I asked over the weekend. The method I was thinking of was in a program I wrote on my work computer but couldn't remember. Now I'm at work and I see. It is not including the tuple at the end of the string nor using a dictionary. There is another way using locals(). I was trying to remember this method: You some variables say: X = "sky" Y = "blue" Print "the %(x)s is %(y)s" % locals() the sky is blue That works! And in cases where I'm replacing over 20 strings it's much easier than having to include a tuple at the end. Especially when there's only two or three variables I'm replacing repeatedly, in which case a dictionary seems like overkill. Thanks Matt Matthew Pirritano, Ph.D. Research Analyst IV Medical Services Initiative (MSI) Orange County Health Care Agency (714) 568-5648 -----Original Message----- From: tutor-bounces+mpirritano=ochca.com at python.org [mailto:tutor-bounces+mpirritano=ochca.com at python.org] On Behalf Of Steven D'Aprano Sent: Saturday, September 17, 2011 6:58 PM To: tutor at python.org Subject: Re: [Tutor] string formatting Matthew Pirritano wrote: > But I have very large blocks of text and I thought there was another way > like > > X = "sky" > Y = "blue" > "the %(X)s is %(Y)s" Unless you use the string formatting operator %, strings containing "%" are just strings. Large or small, the way you do string formatting is with the % operator. Python will never do string formatting without an explicit command to do so: text % value # Single non-tuple argument text % (value, value, ...) # Multiple arguments They don't have to be string literals, they can be variables: text = "Hello, I'd like to have an %s" value = "argument" print text % value You can also use named arguments by using a dictionary: text = "Hello, I'd like to have an %(X)s" values = {"X": "argument"} print text % values More details in the Fine Manual: http://docs.python.org/library/stdtypes.html#string-formatting Alternatives include the new advanced formatting method: text.format() http://docs.python.org/library/string.html#formatstrings and "$" substitutions with the string module: import string string.Template http://docs.python.org/library/string.html#template-strings -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From waynejwerner at gmail.com Mon Sep 19 19:47:01 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 19 Sep 2011 12:47:01 -0500 Subject: [Tutor] string formatting In-Reply-To: References: <001101cc7594$b37bdaf0$1a7390d0$@net> <4E755024.3060501@pearwood.info> Message-ID: On Mon, Sep 19, 2011 at 10:46 AM, Pirritano, Matthew wrote: > You some variables say: > > X = "sky" > Y = "blue" > > Print "the %(x)s is %(y)s" % locals() > > the sky is blue > > That works! And in cases where I'm replacing over 20 strings it's much > easier than having to include a tuple at the end. Especially when > there's only two or three variables I'm replacing repeatedly, in which > case a dictionary seems like overkill. > I suspect your email program auto-capitalized the initial X and Y, and P for you, as that code would actually create a syntax and KeyError (or two). Technically speaking, locals() is already dictionary: >>> type(locals()) and just for the sake of completeness, in newer (2.6(?) or greater) versions of Python, you can use the format() method: x = 'sky' y = 'blue' print('The {x} is {y}.'.format(locals())) HTH, -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Mon Sep 19 20:11:00 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Mon, 19 Sep 2011 18:11:00 +0000 Subject: [Tutor] string formatting In-Reply-To: References: <001101cc7594$b37bdaf0$1a7390d0$@net><4E755024.3060501@pearwood.info> Message-ID: <1299425079-1316455860-cardhu_decombobulator_blackberry.rim.net-1619700894-@b28.c12.bise7.blackberry> Is there any additional overhead of using the locals() or format(locals()) instead of a tuple? - the format option is a double function call so I would expect that to be considerably slower Thanks, Bodsda -- my phone won't let me bottom post, sorry Sent from my BlackBerry? wireless device -----Original Message----- From: Wayne Werner Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Mon, 19 Sep 2011 12:47:01 To: Pirritano, Matthew Cc: Subject: Re: [Tutor] string formatting _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From waynejwerner at gmail.com Mon Sep 19 20:43:42 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 19 Sep 2011 13:43:42 -0500 Subject: [Tutor] string formatting In-Reply-To: <1299425079-1316455860-cardhu_decombobulator_blackberry.rim.net-1619700894-@b28.c12.bise7.blackberry> References: <001101cc7594$b37bdaf0$1a7390d0$@net> <4E755024.3060501@pearwood.info> <1299425079-1316455860-cardhu_decombobulator_blackberry.rim.net-1619700894-@b28.c12.bise7.blackberry> Message-ID: On Mon, Sep 19, 2011 at 1:11 PM, wrote: > Is there any additional overhead of using the locals() or format(locals()) > instead of a tuple? - the format option is a double function call so I would > expect that to be considerably slower > Using the following code and timeit, it appears that there is a difference, but unless you call 0.3-6 ns considerable (assuming I got my math correct: The difference was ~1.2 or ~1.3 seconds for the classic, ~1.9 for the % locals version, and timeit runs 1,000,000 times with the default settings), then the difference isn't terrible. -Wayne from __future__ import print_function import timeit def classicwithlocals(): x = 'hello' from __future__ import print_function import timeit def classicwithlocals(): x = 'hello' y = 'goodbye' combined = 'You say %(x)s, and I say %(y)s' % locals() def classicwithtuple(): x = 'hello' y = 'goodbye' combined = 'You say %s, and I say %s' % (x, y) def withargs(): x = 'hello' y = 'goodbye' combined = 'You say {0}, and I say {1}'.format(x, y) for f in [withargs, classicwithtuple, classicwithlocals]: t = timeit.Timer(f) print(t.timeit()) -------------- next part -------------- An HTML attachment was scrubbed... URL: From nozarm at triumf.ca Mon Sep 19 20:22:30 2011 From: nozarm at triumf.ca (Mina Nozar) Date: Mon, 19 Sep 2011 11:22:30 -0700 Subject: [Tutor] OptionParser Message-ID: <4E778866.9040905@triumf.ca> Hello, I am trying to use OptionParser (my first time) to set a variable (cvs_output). i.e. if --csv is given in the list of options, then cvs_output = True. Then I check, if cvs_output == True: [...] I have the following so far but something is missing. from optparse import OptionParser usage = "usage: %prog [options]" parser = OptionParser(usage=usage) parser.add_option("-cvs", dest="output", default=True, help="outputs the csv file for plotting activites") python dUCx_ActivityPlots.py python dUCx_ActivityPlots.2.py -h Usage: dUCx_ActivityPlots.2.py [options] Options: -h, --help show this help message and exit --cvs=OUTPUT_FLAG outputs the csv file for plotting activities I don't really understand what dest and action in the arguments to parser.add_option mean. Any help is appreciated. Mina -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Sep 19 21:05:57 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 19 Sep 2011 14:05:57 -0500 Subject: [Tutor] OptionParser In-Reply-To: <4E778866.9040905@triumf.ca> References: <4E778866.9040905@triumf.ca> Message-ID: On Mon, Sep 19, 2011 at 1:22 PM, Mina Nozar wrote: > ** > I don't really understand what dest and action in the arguments to > parser.add_option mean. > Any help is appreciated. > Have you read the fine manual, specifically the sections here: http://docs.python.org/library/optparse.html#optparse-standard-option-actions and here: http://docs.python.org/library/optparse.html#option-attributes Additionaly, I'm not sure you copied your code correctly, because after a copy and paste I get this: $ python localtest.py Traceback (most recent call last): File "localtest.py", line 5, in parser.add_option("-cvs", dest="output", default=True, help="outputs the csv file for plotting activites") File "/usr/lib/python2.6/optparse.py", line 1012, in add_option option = self.option_class(*args, **kwargs) File "/usr/lib/python2.6/optparse.py", line 566, in __init__ self._set_opt_strings(opts) File "/usr/lib/python2.6/optparse.py", line 606, in _set_opt_strings self) optparse.OptionError: invalid long option string '-cvs': must start with --, followed by non-dash and when I correct that: $ python localtest.py -h uwwerne at WWERNER /c $ I get no output. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Mon Sep 19 22:20:12 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 19 Sep 2011 22:20:12 +0200 Subject: [Tutor] Using xml.etree In-Reply-To: References: Message-ID: <4E77A3FC.4080103@gmail.com> On 17/09/11 13:08, lists wrote: > I have been trying to learn how to parse XML with Python and learn how > to use xml.etree. Lots of the tutorials seem to be very long winded. > > I'm trying to access a UK postcode API at www.uk-postcodes.com to take > a UK postcode and return the lat/lng of the postcode. This is what the > XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml > > The function below returns a dict with the xml tag as a key and the > text as a value. Is this a correct way to use xml.etree? Define correct, does it give the desired result? Then I would say yes it is correct. There may be alternative ways to get to the same result though. > def ukpostcodesapi(postcode): > import urllib Why do the import here, for speed? You are reading an xml file from the internet, guess where most of the time is spend in your function ;-). > import xml.etree.ElementTree as etree > > baseURL='http://www.uk-postcodes.com/' > geocodeRequest='postcode/'+postcode+'.xml' You could use string formatting here. url = 'http://www.uk-postcodes.com/postcode/%s.xml' % postcode Also what would happen if postcode includes a space? > > #grab the xml > tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest)) What happens if you get an error (a 404 error perhaps)? You might want to add a try/except block around reading the xml from the internet. > root=tree.getroot() > results={} > for child in root[1]: #here's the geo tag > results.update({child.tag:child.text}) #build a dict containing the > geocode data > return results As you only get 1 set of long/lat tags in the xml you could use find(). See below an example. from xml.etree import ElementTree as ET import urllib2 url = 'http://www.uk-postcodes.com/postcode/HU11AA.xml' xml = urllib2.urlopen(url).read() tree = ET.XML(xml) geo = {} for leaf in tree.find('geo'): geo[leaf.tag] = leaf.text Greets Sander From lists at justuber.com Tue Sep 20 00:33:10 2011 From: lists at justuber.com (lists) Date: Mon, 19 Sep 2011 23:33:10 +0100 Subject: [Tutor] Using xml.etree In-Reply-To: <4E77A3FC.4080103@gmail.com> References: <4E77A3FC.4080103@gmail.com> Message-ID: On Mon, Sep 19, 2011 at 9:20 PM, Sander Sweers wrote: > On 17/09/11 13:08, lists wrote: >> >> I have been trying to learn how to parse XML with Python and learn how >> to use xml.etree. Lots of the tutorials seem to be very long winded. >> >> I'm trying to access a UK postcode API at www.uk-postcodes.com to take >> a UK postcode and return the lat/lng of the postcode. This is what the >> XML looks like: http://www.uk-postcodes.com/postcode/HU11AA.xml >> >> The function below returns a dict with the xml tag as a key and the >> text as a value. Is this a correct way to use xml.etree? > > Define correct, does it give the desired result? Then I would say yes it is > correct. There may be alternative ways to get to the same result though. > >> def ukpostcodesapi(postcode): >> ? ? ? ?import urllib > > Why do the import here, for speed? You are reading an xml file from the > internet, guess where most of the time is spend in your function ;-). > >> ? ? ? ?import xml.etree.ElementTree as etree >> >> ? ? ? ?baseURL='http://www.uk-postcodes.com/' >> ? ? ? ? geocodeRequest='postcode/'+postcode+'.xml' > > You could use string formatting here. > ?url = 'http://www.uk-postcodes.com/postcode/%s.xml' % postcode > > Also what would happen if postcode includes a space? > >> >> ? ? ? ?#grab the xml >> ? ? ? ?tree=etree.parse(urllib.urlopen(baseURL+geocodeRequest)) > > What happens if you get an error (a 404 error perhaps)? You might want to > add a try/except block around reading the xml from the internet. > >> ? ? ? ?root=tree.getroot() >> ? ? ? ?results={} >> ? ? ? ?for child in root[1]: #here's the geo tag >> ? ? ? ? ? ? ? ?results.update({child.tag:child.text}) #build a dict >> containing the >> geocode data >> ? ? ? ?return results > > As you only get 1 set of long/lat tags in the xml you could use find(). See > below an example. > > from xml.etree import ElementTree as ET > import urllib2 > > url = 'http://www.uk-postcodes.com/postcode/HU11AA.xml' > xml = urllib2.urlopen(url).read() > tree = ET.XML(xml) > > geo = {} > > for leaf in tree.find('geo'): > ? ?geo[leaf.tag] = leaf.text > > Greets > Sander Thank you I've been working on this and ended up with http://pastebin.com/Y9keC9tB Chris From g.nius.ck at gmail.com Tue Sep 20 00:55:19 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Mon, 19 Sep 2011 18:55:19 -0400 Subject: [Tutor] iretator.send Message-ID: Dear tutor dudes, I know that a for loop uses a an iterators next method in this way for variable in iterator: execute_code(variable) is equivalent to while True: try: variable = iterator.next() except StopIteration: break else: execute_code(variable) Is there any syntax that uses the send method of an iterator? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Sep 20 02:30:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Sep 2011 10:30:02 +1000 Subject: [Tutor] iretator.send In-Reply-To: References: Message-ID: <4E77DE8A.5060905@pearwood.info> Christopher King wrote: > Is there any syntax that uses the send method of an iterator? No. -- Steven From steve at pearwood.info Tue Sep 20 02:27:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Sep 2011 10:27:12 +1000 Subject: [Tutor] How it is better than java In-Reply-To: References: Message-ID: <4E77DDE0.2020906@pearwood.info> Ashish Gaonker wrote: > My obvious thinking is : Java being compiled language , must be faster then > a interpreted language. There are three misunderstandings with that statement. Firstly: Languages are neither "compiled" or "interpreted". Languages are syntax and grammar. Implementations are either compiled, or interpreted, or both: for example, there are C interpreters and C compilers. And the quality of both can vary significantly. Asking which language is faster is like asking which is faster, Ford or Toyota? That depends on the particular model, and the conditions, and the skill of the driver. It is ironic that you contrast Java as "compiled" and Python as "interpreted", because that is *marketing*. When Java first came out, Sun didn't want people describing it as "interpreted", which it was, so they popularized the term "byte-code compiler" just so that they could talk about Java being compiled. Java would compile your Java source code to byte-code which was then interpreted by a virtual machine. That is *exactly* what Python does: it compiles Python source code to byte-code which is interpreted by a virtual machine, just like Java. What do you think the .pyc files contain, and what the compile() function does? And yet, even back in the 1980s, everybody swallowed Sun's marketing and called Java a compiled language and Python an interpreted language. This is a testament to Sun spending millions in advertising. Byte-code compilation is a lot older than Java. Pascal used something similar in the early 1970s, called a p-machine. Even Apple's Hypertalk did the same thing, only they called it "tokenized" code instead of compiled. Java's big innovation was to convince people to use the term "compiler" for what was functionally identical to an interpreter. Of course, Sun (now owned by Oracle) put in a lot of money into Java. Millions. Today, Java does have implementations which compile source code to machine code. But there are Python implementations that do the same, such as Nuitka and Compyler. (I don't know how successful or good they are.) Secondly, what do you mean by "faster"? Faster to write? Faster to compile? Faster to run? Faster for the engine to start up? Even today, after Sun has spent tens of millions on Java development, the Java Runtime Environment is a big, heavyweight machine that takes a long time to start up: cold starts can easily take 30 seconds. That makes Java completely unsuitable for small, lightweight tasks: in the time it takes for a *single* Java program just to start up, you could possibly run a dozen Python programs or a hundred interpreted bash scripts. But again, that's an *implementation*, not a hard rule about Java. There is at least one third-party JRE which claims to have startup times twice as fast as the Sun/Oracle JRE. Either way, once you take startup time into account, sometimes Python scripts are not only faster to write and faster to maintain, but faster to run as well. Thirdly, there is no rule of nature that a compiled program to do a job must be faster than an interpreted program to do the same thing. This depends entirely on the quality of implementation of both: a poor compiler may easily generate bad, slow code that takes longer to run than a wickedly fast and efficient interpreter. E.g. a compiled version of bubblesort will still be slower than an interpreted version of quicksort. Nothing drives this home more than PyPy, a Just In Time optimizing version of Python. PyPy uses a JIT compiler to run code sometimes FASTER than the equivalent program in optimized C. Yes. Faster than C. You read that right. http://morepypy.blogspot.com/2008/01/rpython-can-be-faster-than-c.html http://morepypy.blogspot.com/2011/02/pypy-faster-than-c-on-carefully-crafted.html http://morepypy.blogspot.com/2011/08/pypy-is-faster-than-c-again-string.html Of course, benchmarks are notoriously flawed, especially micro- benchmarks. What they *really* answer is not "which language is faster?" (a nonsense question, as I have tried to explain) but "which implementation is faster with these particular settings on this particular task?", a much more practical question. As exciting as it is to see Python code run faster than C code, it shouldn't really surprise anyone that a JIT dynamic compiler with cross module optimization beats a static compiler without it. What *is* surprising is that a small group of open-source developers have been able to build an optimizing JIT compiler for Python of such quality. Or at least, it is surprising to people who think that quality code can only come from big proprietary companies with huge budgets. What's really exciting though is that now PyPy can be fast enough for large programs that traditionally needed to be written in C can now be (sometimes!) written in Python: http://morepypy.blogspot.com/2011/07/realtime-image-processing-in-python.html Who cares whether Java, or C, is "faster" than Python? The important question should be, is Python fast enough for the job I have to do? > Can you share some more especially as compared to Java / .net (two primarily > used languages in enterprise language & web based applications) You can look at Jython (Python for the JRE) and IronPython (Python for .Net). There is also an older implementation, Python For .Net, which runs the standard CPython implementation on .Net, but I don't think it is still maintained -- IronPython has taken over its niche. There's also JPype, which claims to give full access to Java libraries in Python. -- Steven From steve at pearwood.info Tue Sep 20 03:11:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Sep 2011 11:11:42 +1000 Subject: [Tutor] string formatting In-Reply-To: References: <001101cc7594$b37bdaf0$1a7390d0$@net> <4E755024.3060501@pearwood.info> <1299425079-1316455860-cardhu_decombobulator_blackberry.rim.net-1619700894-@b28.c12.bise7.blackberry> Message-ID: <4E77E84E.9040708@pearwood.info> Wayne Werner wrote: > On Mon, Sep 19, 2011 at 1:11 PM, wrote: > >> Is there any additional overhead of using the locals() or format(locals()) >> instead of a tuple? - the format option is a double function call so I would >> expect that to be considerably slower >> > > Using the following code and timeit, it appears that there is a difference, > but unless you call 0.3-6 ns considerable (assuming I got my math correct: > The difference was ~1.2 or ~1.3 seconds for the classic, ~1.9 for the % > locals version, and timeit runs 1,000,000 times with the default settings), > then the difference isn't terrible. I get similar speeds with Python 2.7: >>> for f in [withargs, classicwithtuple, classicwithlocals]: ... t = timeit.Timer(f) ... print(t.timeit()) ... 1.72170519829 1.18233394623 1.96000385284 However, a single reading with timeit is subject to a lot of noise. Trying again: >>> for f in [withargs, classicwithtuple, classicwithlocals]: ... t = timeit.Timer(f) ... print(min(t.repeat(repeat=5))) # Best of five runs. ... 1.19279980659 1.01878404617 1.56821203232 So, roughly speaking, it looks like the format method is about 20% slower than % with a tuple, and using locals is about 60% slower. -- Steven From quasipedia at gmail.com Tue Sep 20 10:21:06 2011 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 20 Sep 2011 10:21:06 +0200 Subject: [Tutor] How it is better than java In-Reply-To: <4E77DDE0.2020906@pearwood.info> References: <4E77DDE0.2020906@pearwood.info> Message-ID: <20110920102106.5c34d212@jabbar> On Tue, 20 Sep 2011 10:27:12 +1000 Steven D'Aprano wrote: > There are three misunderstandings with that statement. > [snip] > There's also JPype, which claims to give full access to Java > libraries in Python. Now: this was one of the best write-ups on the subject I read. Concise, clear, documented. Nice way to start the day! :o /mac From waynejwerner at gmail.com Tue Sep 20 16:04:17 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 20 Sep 2011 09:04:17 -0500 Subject: [Tutor] How it is better than java In-Reply-To: <20110920102106.5c34d212@jabbar> References: <4E77DDE0.2020906@pearwood.info> <20110920102106.5c34d212@jabbar> Message-ID: On Tue, Sep 20, 2011 at 3:21 AM, Mac Ryan wrote: > On Tue, 20 Sep 2011 10:27:12 +1000 > Steven D'Aprano wrote: > > > > There are three misunderstandings with that statement. > > [snip] > > There's also JPype, which claims to give full access to Java > > libraries in Python. > > Now: this was one of the best write-ups on the subject I read. Concise, > clear, documented. Nice way to start the day! :o Ditto - and as a slight aside, it's interesting to note that .NET languages (VB, C# specifically) are also compiled into the MSIL which can't run without the .NET runtime. To my understanding, this is quite similar (or the same thing) as other "interpreted" languages. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Sep 20 23:27:15 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 20 Sep 2011 17:27:15 -0400 Subject: [Tutor] OptionParser In-Reply-To: <4E778866.9040905@triumf.ca> References: <4E778866.9040905@triumf.ca> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F16F338A3@EMARC112VS01.exchad.jpmchase.net> > from optparse import OptionParser I am not sure what version of Python you are using but from 2.7+ optparse is deprercated. You may want to use that if you can. > I don't really understand what dest and action in the arguments to parser.add_option mean. Here is your usage: >>> parser = OptionParser(usage="blahblahblah") >>> parser.add_option("-f", "--file", dest="filename")