From naheedcse at gmail.com Sun May 1 05:23:22 2011 From: naheedcse at gmail.com (naheed arafat) Date: Sun, 1 May 2011 09:23:22 +0600 Subject: [Tutor] confusions about re module Message-ID: someone please tell me why i'm getting this output? specially the 'e3%' ! ! ! >>> import re >>> re.findall('([\w]+.)','abdd.e3\45 dret.8dj st.jk') ['abdd.', 'e3%', 'dret.', '8dj ', 'st.', 'jk'] I am getting the same output for the following too.. >>> re.findall(r'([\w]+.)','abdd.e3\45 dret.8dj st.jk') ['abdd.', 'e3%', 'dret.', '8dj ', 'st.', 'jk'] wasn't i supposed to get ['abdd.','dret.'] ?? python version: 2.6.5 os: windows -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryan.strunk at gmail.com Sun May 1 05:49:51 2011 From: ryan.strunk at gmail.com (Ryan Strunk) Date: Sat, 30 Apr 2011 22:49:51 -0500 Subject: [Tutor] Combining two Dictionaries Message-ID: <006901cc07b2$d42d1840$7c8748c0$@gmail.com> Hello everyone, I had an interesting thing come up earlier in my programming, and I'm trying to wrap my mind around why it occurred. I wanted to take two dictionaries with the same keys and combine their values to make one, big super dictionary. def combine(d1, d2): for key in d1: if key in d2: d2[key] += d1[key] When I assign values to each dictionary, this works perfectly. d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'a': 10, 'b': 20, 'c': 30} combine(d1, d2) d1 = {'a': 1, 'b': 2, 'c': 3} d2 = {'a': 11, 'b': 22, 'c': 33} When I initialize the class which holds these dictionaries, though, I need to make sure that all the keys contained in d2 match the keys of d1. Thus I tried: d1 = {'a': 0, 'b': 0, 'c': 0} d2 = d1 My understanding was that d2 looked at d1 once, grabbed its keys and values, and went off to do its own thing. Just as if you typed: x = 3 y = x x = 6 y still holds the value 3. This turns out not to be the case with dictionaries, and I'm not sure why this is so. Why when you change a dictionary's keys in place does a copied dictionary take on the new values? Thanks for any help you can provide. Best, Ryan From knacktus at googlemail.com Sun May 1 06:46:34 2011 From: knacktus at googlemail.com (Knacktus) Date: Sun, 01 May 2011 06:46:34 +0200 Subject: [Tutor] Combining two Dictionaries In-Reply-To: <006901cc07b2$d42d1840$7c8748c0$@gmail.com> References: <006901cc07b2$d42d1840$7c8748c0$@gmail.com> Message-ID: <4DBCE5AA.8090200@googlemail.com> > > def combine(d1, d2): > for key in d1: > if key in d2: > d2[key] += d1[key] [Remark] I usually avoid changing function arguments. But later on you're talking about using this function as a method a class, so d1 and d2 would be instance attributes I guess. > When I initialize the class which holds these dictionaries, though, I need > to make sure that all the keys contained in d2 match the keys of d1. Thus I > tried: > d1 = {'a': 0, 'b': 0, 'c': 0} Now d1 holds the address of a dict in memory. The dict contains your data. > d2 = d1 Now d2 holds the same address of the same dict in memory. d1 and d2 refer to the same dictionary. > My understanding was that d2 looked at d1 once, grabbed its keys and values, > and went off to do its own thing. You would need to use copy() explicitly. import copy d2 = copy.copy(d1) # swallow copy # or a deep copy # -> copies also referenced objects recursively # usefull if you have e.g. lists as values in your dict # and want them copied too. d2 = copy.deepcopy(d1) Just as if you typed: > x = 3 > y = x > x = 6 > y still holds the value 3. Python has mutable and immutable types. Str and int, for example, are immutable. Dicts and list for example are mutable. The statement x=6 binds x to a new object, because the object with value 3 cannot be changed. There are a lot of explanations about mutable and immutable types. Much better then I could. You could search the list, for example here: http://dir.gmane.org/gmane.comp.python.tutor or the web or see this overview in the docs: http://docs.python.org/reference/datamodel.html#objects-values-and-types Generally, I wouldn't copy an existing dict to make sure the other dict has the same values. The data must come from somewhere. I would check the data, then you wouldn't need to check the container. Finally, you could use dict.get with a default set to 0, then you wouldn't need to care, e.g. (using dict comprehension and creating a new dict): def combine_2(d1, d2): return {key: d1[key]+d2.get(key, 0) for key in d1} But that's a bit dirty semantic wise, better to check the input data ... just to show you the syntax. HTH, Jan From andreengels at gmail.com Sun May 1 07:29:37 2011 From: andreengels at gmail.com (Andre Engels) Date: Sun, 1 May 2011 07:29:37 +0200 Subject: [Tutor] Combining two Dictionaries In-Reply-To: <006901cc07b2$d42d1840$7c8748c0$@gmail.com> References: <006901cc07b2$d42d1840$7c8748c0$@gmail.com> Message-ID: On Sun, May 1, 2011 at 5:49 AM, Ryan Strunk wrote: > When I initialize the class which holds these dictionaries, though, I need > to make sure that all the keys contained in d2 match the keys of d1. Thus I > tried: > d1 = {'a': 0, 'b': 0, 'c': 0} > d2 = d1 > My understanding was that d2 looked at d1 once, grabbed its keys and values, > and went off to do its own thing. ?Just as if you typed: > x = 3 > y = x > x = 6 > y still holds the value 3. > This turns out not to be the case with dictionaries, and I'm not sure why > this is so. Why when you change a dictionary's keys in place does a copied > dictionary take on the new values? > Thanks for any help you can provide. To answer your question, we have to look at Python's data model, which differs from that in other languages. What y = x does, is to calculate the object x and give it the name y, apart from whatever names it may or may not have already. Thus, it does _not_ make a copy, but x and y are two different names of the _same_ object. What happens in your example, is that you give the object 3 the name x, then give the object 3 (the outcome of the 'calculation' x) the name y, then give the object 6 the name x. After that y is still a name for 3. But if you're working with dictionaries, you're probably doing something like this: d1 = {'a': 0, 'b': 0, 'c': 0} # You create a dictionary and give it the name d1 d2 = d1 # You give _the same_ dictionary the name d2 d1['c'] = 1 # You _change_ the dictionary by changing its value for the key c. d1 and d2 still are names for the _same_ dictionary Just like in the integer situation, d2 is still a name for the same object as it was before, but this time _the object itself has changed_. And d2 'sees' the change of the object. -- Andr? Engels, andreengels at gmail.com From __peter__ at web.de Sun May 1 09:14:42 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 May 2011 09:14:42 +0200 Subject: [Tutor] confusions about re module References: Message-ID: naheed arafat wrote: > someone please tell me why i'm getting this output? > specially the 'e3%' ! ! ! >>>> import re >>>> re.findall('([\w]+.)','abdd.e3\45 dret.8dj st.jk') > ['abdd.', 'e3%', 'dret.', '8dj ', 'st.', 'jk'] > > I am getting the same output for the following too.. >>>> re.findall(r'([\w]+.)','abdd.e3\45 dret.8dj st.jk') > ['abdd.', 'e3%', 'dret.', '8dj ', 'st.', 'jk'] > > wasn't i supposed to get ['abdd.','dret.'] ?? > python version: 2.6.5 > os: windows Quoting http://docs.python.org/library/re.html : """ '.' (Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline. [...] '\' Either escapes special characters (permitting you to match characters like '*', '?', and so forth), or signals a special sequence; special sequences are discussed below. """ So you get the desired behaviour by escaping the dot: >>> re.findall(r'([\w]+\.)','abdd.e3\45 dret.8dj st.jk') ['abdd.', 'dret.', 'st.'] >>> re.findall(r'([\w]+[.])','abdd.e3\45 dret.8dj st.jk') ['abdd.', 'dret.', 'st.'] (assuming that you left out the last match accidentally) From steve at pearwood.info Sun May 1 10:28:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 01 May 2011 18:28:56 +1000 Subject: [Tutor] Combining two Dictionaries In-Reply-To: <4DBCE5AA.8090200@googlemail.com> References: <006901cc07b2$d42d1840$7c8748c0$@gmail.com> <4DBCE5AA.8090200@googlemail.com> Message-ID: <4DBD19C8.1070908@pearwood.info> Knacktus wrote: >> When I initialize the class which holds these dictionaries, though, I >> need >> to make sure that all the keys contained in d2 match the keys of d1. >> Thus I >> tried: >> d1 = {'a': 0, 'b': 0, 'c': 0} > > Now d1 holds the address of a dict in memory. [...] Let me guess... did you learn C before learning Python? Trust me, d1 does not hold the address of anything. Try it and see for yourself: >>> d1 = {'a': 0, 'b': 0, 'c': 0} >>> print d1 {'a': 0, 'c': 0, 'b': 0} Does that look like a memory address to you? Just to be sure: >>> type(d1) d1 holds a dict, as expected. Forget about addresses. This isn't C, or assembly language. All that low-level stuff about address and memory locations has nothing to do with Python code and just confuses issues. You can't access memory addresses in pure Python code. Python abstracts all those low-level details away, and just cares about objects and names, in the same way that languages like C abstracts away the only operation a computer really can do: flip bits on or off. (However, it is sometimes useful when thinking about the implementation of the Python virtual machine.) >> d2 = d1 > > Now d2 holds the same address of the same dict in memory. d1 and d2 > refer to the same dictionary. No, and yes. d1 and d2 are two names for the same object: >>> d2 is d1 True >> My understanding was that d2 looked at d1 once, grabbed its keys and >> values, >> and went off to do its own thing. > > You would need to use copy() explicitly. > > import copy > > d2 = copy.copy(d1) # swallow copy I think you mean "shallow" copy. You can do that, but for dicts there is a much simpler way to make a copy: >>> d3 = d1.copy() >>> d3 is d1 False >>> d3 == d1 True -- Steven From naheedcse at gmail.com Sun May 1 10:48:01 2011 From: naheedcse at gmail.com (naheed arafat) Date: Sun, 1 May 2011 14:48:01 +0600 Subject: [Tutor] confusions about re module In-Reply-To: References: Message-ID: ya.you'r right. left it accidentally.thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun May 1 14:00:09 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 01 May 2011 22:00:09 +1000 Subject: [Tutor] Combining two Dictionaries In-Reply-To: References: <006901cc07b2$d42d1840$7c8748c0$@gmail.com> Message-ID: <4DBD4B49.4050205@pearwood.info> Andre Engels wrote: > To answer your question, we have to look at Python's data model, which > differs from that in other languages. Strictly speaking, that is true: Python's data model is different from that of (say) C, or Pascal, or Forth. But it's also the same as that in other languages, like Ruby, and Java (mostly), and others. -- Steven From glchristian at comcast.net Sun May 1 20:28:43 2011 From: glchristian at comcast.net (Greg Christian) Date: Sun, 1 May 2011 12:28:43 -0600 Subject: [Tutor] Compound if statement question. Message-ID: <3A31334CAD9941B1A1CF81669770E6E8@GREGPC> Is there a way to write an if statement that will pick up duplicates (two ?1?s): L = ['1', '4', '1'] if (L[0]) != (L[1]) != (L[2]): print "THEY ARE NOT EQUAL" else: print "THEY ARE EQUAL" When I run this code, it prints ?THEY ARE NOT EQUAL? when it should print the else ?THEY ARE EQUAL?. list L has two ?1?s; therefore I am trying to get an if statement that will recognize this. When using the != (not equal) operator, shouldn?t the if be true when items in list are not the same? Any input would be appreciated. Thanks, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sun May 1 20:52:38 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 01 May 2011 14:52:38 -0400 Subject: [Tutor] Compound if statement question. In-Reply-To: <3A31334CAD9941B1A1CF81669770E6E8@GREGPC> References: <3A31334CAD9941B1A1CF81669770E6E8@GREGPC> Message-ID: <4DBDABF6.1040805@aim.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/01/2011 02:28 PM, Greg Christian wrote: > Is there a way to write an if statement that will pick up duplicates (two ?1?s): > > L = ['1', '4', '1'] > if (L[0]) != (L[1]) != (L[2]): > print "THEY ARE NOT EQUAL" > else: > print "THEY ARE EQUAL" > > When I run this code, it prints ?THEY ARE NOT EQUAL? when it should print the else ?THEY ARE EQUAL?. > Well, think about what that if-statement is doing. It's making sure that the first three elements of L aren't equal to each other. Due to python's short-circuit evaluation, it breaks the if after the first one, because '1' != '4'. The parentheses there are useless. You might look at [1] to see if there is anything that will count how many times something appears in a list... [1] -- http://docs.python.org/tutorial/datastructures.html#more-on-lists - -- Corey Richardson -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJNvav2AAoJEAFAbo/KNFvpx/IH/iT54cNeVSSJsRQit13Hf91H y6zy9Cx3pE9Pxf+crK+9tT53C67TxQIdLRcD83fuXF1iEZJYwVlgQv5Py7U7KIy2 X0SU9ScL4xy/b3k8QB+kj7w7wt4Aa0yPhAx6mZI0KXErj6hVjeIljQf6E3irY7K1 Uot5TY5vY6YieKX+Sc/C2Kv3nmPCM2x1TcuwzX+zIGFBNEuGDb1jNdTR8LkVG+nb WqBPEtO5sEy9/5NULtExSgS80xUT/fLCRc6gpf5yQBIi/xm+lOBTx1hUCgYfrsLp gCKOIrXtPaI1bYdxf2tApDUWXVAe5U7tB9z4s9Uz9bV3x8od2w5gsCmxLLJgLHs= =Sz54 -----END PGP SIGNATURE----- From joel.goldstick at gmail.com Sun May 1 21:16:54 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 1 May 2011 15:16:54 -0400 Subject: [Tutor] Compound if statement question. In-Reply-To: <3A31334CAD9941B1A1CF81669770E6E8@GREGPC> References: <3A31334CAD9941B1A1CF81669770E6E8@GREGPC> Message-ID: On Sun, May 1, 2011 at 2:28 PM, Greg Christian wrote: > Is there a way to write an if statement that will pick up duplicates > (two ?1?s): > > L = ['1', '4', '1'] > if (L[0]) != (L[1]) != (L[2]): > print "THEY ARE NOT EQUAL" > else: > print "THEY ARE EQUAL" > > When I run this code, it prints ?THEY ARE NOT EQUAL? when it *should*print the else ?THEY ARE EQUAL?. > > list L has two ?1?s; therefore I am trying to get an if statement that will > recognize this. When using the != (not equal) operator, shouldn?t the if be > true when items in list are not the same? Any input would be appreciated. > > Thanks, > > Greg > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Learn about sets.: len(set(L)) == 1 is only true if they are all the same If you want to see if L[0] value is duplicated try if L[0] in set(L[1:]) if you want to see if there are any duplicates all all try len(L) != len(set(L)) -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon May 2 02:14:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 02 May 2011 10:14:16 +1000 Subject: [Tutor] Compound if statement question. In-Reply-To: <3A31334CAD9941B1A1CF81669770E6E8@GREGPC> References: <3A31334CAD9941B1A1CF81669770E6E8@GREGPC> Message-ID: <4DBDF758.2050301@pearwood.info> Greg Christian wrote: > Is there a way to write an if statement that will pick up duplicates (two ?1?s): > > L = ['1', '4', '1'] > if (L[0]) != (L[1]) != (L[2]): > print "THEY ARE NOT EQUAL" > else: > print "THEY ARE EQUAL" > > When I run this code, it prints ?THEY ARE NOT EQUAL? when it should print the else ?THEY ARE EQUAL?. You don't need to put brackets ("parentheses" for any Americans reading) around each term. That just adds noise to the code and makes it harder to read. Your test says: L[0] != L[1] != L[2] which evaluates to: '1' != '4' != '1' which is obviously correct, they are *not* ALL equal. Python comparisons chain: the above is equivalent to the longer: '1' != '4' and '4' != '1' which is clearly true. The test you probably want is: if L[0] == L[1] or L[0] == L[2]: print "THEY ARE EQUAL" For longer lists, this might be better: if any(L[0] == x for x in L[1:]): print "first item equals some other item" or easier to write: if L.count(L[0]) > 1: print "first item duplicate detected" -- Steven From mat.korycinski at gmail.com Mon May 2 03:01:30 2011 From: mat.korycinski at gmail.com (=?ISO-8859-2?Q?Mateusz_Koryci=F1ski?=) Date: Mon, 2 May 2011 03:01:30 +0200 Subject: [Tutor] Ipython console Message-ID: Hi, I am using ipython console on one of servers and it's great. Because of that I've tried to install it on my laptop, but unfortunately I am getting this error: Traceback (most recent call last): > File "/usr/bin/ipython", line 26, in > import IPython.Shell > File "/usr/lib/python2.7/dist-packages/IPython/__init__.py", line 58, in > > __import__(name,glob,loc,[]) > File "/usr/lib/python2.7/dist-packages/IPython/ipstruct.py", line 17, in > > from IPython.genutils import list2dict2 > File "/usr/lib/python2.7/dist-packages/IPython/genutils.py", line 20, in > > import doctest > File "/usr/lib/python2.7/doctest.py", line 329, in > class _OutputRedirectingPdb(pdb.Pdb): > AttributeError: 'module' object has no attribute 'Pdb' > I know it means that Ipython missing some methods / objects, but I don't know what should I install additionally. I am using Ubuntu so I've installed Ipython from repo. Thanks in advice! Cheers, Mateusz -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon May 2 09:09:41 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 May 2011 09:09:41 +0200 Subject: [Tutor] Ipython console References: Message-ID: Mateusz Koryci?ski wrote: > Hi, > > I am using ipython console on one of servers and it's great. Because of > that I've tried to install it on my laptop, but unfortunately I am getting > this error: > > Traceback (most recent call last): >> File "/usr/bin/ipython", line 26, in >> import IPython.Shell >> File "/usr/lib/python2.7/dist-packages/IPython/__init__.py", line 58, >> in >> >> __import__(name,glob,loc,[]) >> File "/usr/lib/python2.7/dist-packages/IPython/ipstruct.py", line 17, >> in >> >> from IPython.genutils import list2dict2 >> File "/usr/lib/python2.7/dist-packages/IPython/genutils.py", line 20, >> in >> >> import doctest >> File "/usr/lib/python2.7/doctest.py", line 329, in >> class _OutputRedirectingPdb(pdb.Pdb): >> AttributeError: 'module' object has no attribute 'Pdb' >> > > I know it means that Ipython missing some methods / objects, but I don't > know what should I install additionally. I am using Ubuntu so I've > installed Ipython from repo. Installing from "repo" means that Ubuntu should automatically install IPython's dependencies. Furthermore pdb is part of the standard library: http://docs.python.org/library/pdb.html Therefore I'd guess that you have called one of your own Python modules "pdb.py" which shades the Python debugger. You should be OK if you remove that (and the associated pyc file). Here's a demo (using 2.6):$ python -c 'import IPython.Shell' $touch pdb.py # create an empty pdb module in the working directory$ python -c 'import IPython.Shell' Traceback (most recent call last): File "", line 1, in File "/usr/lib/pymodules/python2.6/IPython/__init__.py", line 58, in __import__(name,glob,loc,[]) File "/usr/lib/pymodules/python2.6/IPython/ipstruct.py", line 17, in from IPython.genutils import list2dict2 File "/usr/lib/pymodules/python2.6/IPython/genutils.py", line 20, in import doctest File "/usr/lib/python2.6/doctest.py", line 318, in class _OutputRedirectingPdb(pdb.Pdb): AttributeError: 'module' object has no attribute 'Pdb' $rm pdb.py pdb.pyc # remove the empty pdb module$ python -c 'import IPython.Shell' From susana.delgado_s at utzmg.edu.mx Mon May 2 21:36:24 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 2 May 2011 14:36:24 -0500 Subject: [Tutor] Unpack requires a string argument of length 8 Message-ID: I'm working on getting information that comes from a dbf file (database), this dbf file is related to another file in the system, a shapefile. My code is trying to get all the dbf name records, but when the systen gets an empty file, my code fails: Traceback (most recent call last): File "", line 1, in File "get_dbf.py", line 32, in dbf = Dbf(d,new=False, readOnly=True) File "C:\Python26\lib\site-packages\dbf.py", line 135, in __init_ self.header = self.HeaderClass.fromStream(self.stream) File "C:\Python26\lib\site-packages\header.py", line 109, in from (_cnt, _hdrLen, _recLen) = struct.unpack(">> How can I fix it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon May 2 22:17:30 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 2 May 2011 13:17:30 -0700 Subject: [Tutor] Unpack requires a string argument of length 8 In-Reply-To: References: Message-ID: On Mon, May 2, 2011 at 12:36 PM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > I'm working on getting information that comes from a dbf file (database), > this dbf file is related to another file in the system, a shapefile. My code > is trying to get all the dbf name records, but when the systen gets an empty > file, my code fails: > Traceback (most recent call last): > File "", line 1, in > File "get_dbf.py", line 32, in > dbf = Dbf(d,new=False, readOnly=True) > File "C:\Python26\lib\site-packages\dbf.py", line 135, in __init_ > self.header = self.HeaderClass.fromStream(self.stream) > File "C:\Python26\lib\site-packages\header.py", line 109, in from > (_cnt, _hdrLen, _recLen) = struct.unpack(" struct.error: unpack requires a string argument of length 8 > >>> > How can I fix it? > You said that this happens when you're trying to process an empty file. If that's the case, then I would certainly expect this: "_data[4:12]" not to return a string of length 8! So you have two options: - "Get permission" > if (some check to make sure the file isn't empty): > dbf = Dbf(d,new=False, readOnly=True) > or - "Ask forgiveness". > try: > dbf = Dbf(d,new=False, readOnly=True) > except: > (cleanup code to handle aborted file opening) > > Which is correct? That depends on your own preference, and also on how often the error occurs. If you rarely run across empty files, then "ask forgiveness" makes more sense, since otherwise you waste time checking for an error that hardly ever happens; on the other hand, if you run into lots of empty files, then it makes sense to check first, each time. Now, it seems to me that whoever wrote the dbf module could have done a little error-checking or -trapping... but this is how I would go about working with the existing module. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aj.rodgers at live.com Tue May 3 00:26:14 2011 From: aj.rodgers at live.com (Austin Rodgers) Date: Mon, 2 May 2011 18:26:14 -0400 Subject: [Tutor] (no subject) Message-ID: I?m trying to learn by using pyschools.com, and ran across a question I can?t answer. I tried to google it, but I don?t even know what type of function I?m looking for. I know I am supposed to modify the list, but I just can?t figure out how. anyway, here?s the question: Write a function getSumofLastDigits() that takes in a list of positive numbers and returns the sum of all the last digits in the list. Examples >>> getSumofLastDigits([2, 3, 4]) 9 >>> getSumofLastDigits([1, 23, 456]) 10 how would I go about writing this function? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue May 3 02:05:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 03 May 2011 10:05:12 +1000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4DBF46B8.8000703@pearwood.info> Austin Rodgers wrote: > I?m trying to learn by using pyschools.com, and ran across a question I can?t answer. I tried to google it, but I don?t even know what type of function I?m looking for. I know I am supposed to modify the list, but I just can?t figure out how. anyway, here?s the question: > > Write a function getSumofLastDigits() that takes in a list of positive numbers and returns the sum of all the last digits in the list. > > Examples > > >>> getSumofLastDigits([2, 3, 4]) > 9 > >>> getSumofLastDigits([1, 23, 456]) > 10 > how would I go about writing this function? This question has two parts: 1 Get the last digit of a number. 2 Do #1 for a bunch of numbers and add the results. Put them together and you get this pseudo code: def getSumOfLastDigits(list_of_numbers): for each number in list_of_numbers: get the last digit add them together and return the result Let me give a few hints: - The sum() function takes a list of numbers and adds them. - Or, you can do the same by hand with a for-loop: def my_sum(numbers): total = 0 for number in numbers: total += number return number - The % operator returns the remainder after division, e.g. 17 % 10 = 7. Now try to write some code and come back if you have any further problems. Good luck! P.S. in future, please try to include a *meaningful* Subject line, not just blank or "no subject". -- Steven From aznjonn at me.com Tue May 3 12:30:37 2011 From: aznjonn at me.com (Johnson Tran) Date: Tue, 03 May 2011 03:30:37 -0700 Subject: [Tutor] ValueError Message-ID: Hi All, i am trying to create a program module with two functions (conversion inches to centimeters then centimeter to inches, I have my program working although I am trying to adda Value Error function to my program but cannot seem to it to work: def Conversion(): print "This program converts the first value from inches to centimeters and second value centimeters to inches." print "(1 inch = 2.54 centimeters)" inches = input("Enter length in inches: ") centimeters = 2.54 * inches print "That is", centimeters, "centimeters." centimeters = input("Enter length in centimeters: ") inch = centimeters / 2.54 print "That is", inch, "inches." except ValueError: print "Invalid digit, please try again." Conversion() Any advice would be great, thanks! JT From nitinpawar432 at gmail.com Tue May 3 12:41:33 2011 From: nitinpawar432 at gmail.com (Nitin Pawar) Date: Tue, 3 May 2011 16:11:33 +0530 Subject: [Tutor] ValueError In-Reply-To: References: Message-ID: When you take input its bydefault is in string format you might want to typecast and validate teh input On Tue, May 3, 2011 at 4:00 PM, Johnson Tran wrote: > Hi All, > > i am trying to create a program module with two functions (conversion > inches to centimeters then centimeter to inches, I have my program working > although I am trying to adda Value Error function to my program but cannot > seem to it to work: > > > def Conversion(): > print "This program converts the first value from inches to centimeters > and second value centimeters to inches." > print "(1 inch = 2.54 centimeters)" > inches = input("Enter length in inches: ") > centimeters = 2.54 * inches > print "That is", centimeters, "centimeters." > > centimeters = input("Enter length in centimeters: ") > inch = centimeters / 2.54 > print "That is", inch, "inches." > > except ValueError: > print "Invalid digit, please try again." > > Conversion() > > > > Any advice would be great, thanks! > > JT > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Nitin Pawar -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Tue May 3 13:00:23 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 03 May 2011 07:00:23 -0400 Subject: [Tutor] ValueError In-Reply-To: References: Message-ID: <4DBFE047.8060605@aim.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/03/2011 06:30 AM, Johnson Tran wrote: > Hi All, > > i am trying to create a program module with two functions (conversion inches to centimeters then centimeter to inches, I have my program working although I am trying to adda Value Error function to my program but cannot seem to it to work: > > > def Conversion(): > print "This program converts the first value from inches to centimeters and second value centimeters to inches." > print "(1 inch = 2.54 centimeters)" > inches = input("Enter length in inches: ") > centimeters = 2.54 * inches > print "That is", centimeters, "centimeters." > > centimeters = input("Enter length in centimeters: ") > inch = centimeters / 2.54 > print "That is", inch, "inches." > > except ValueError: > print "Invalid digit, please try again." > > Conversion() > > > > Any advice would be great, thanks! > > JT Well, you need a 'try' block before that except. Example: try: foo = int("blargh") except ValueError: pass It looks like you're forgetting an important operation on the inches variable, as well as centimeters later on. Take a look at http://docs.python.org/library/stdtypes.html#typesnumeric For future questions, it's best to include what your program /is/ doing that you think it shouldn't be, as well as any errors (tracebacks, copy the whole thing!) you get. - -- Corey Richardson -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJNv+BHAAoJEAFAbo/KNFvpCdwH/0DRxVjevNxZy2HtYuxykzlA x2ni1VnDMyS2YCsHvqIaglfK2hBeL+nstGL8kmEhGu4t5Z85nqGt9Ea2spPhPDxE UJJ1O2nYFtLUZ1BC03vkC8aHI0aiijZjg7v7adKW4sD2laGTaeryLLR1qbGh3ZBP rKTWK/NuyyMDRYjnP0gXsiYYNPc6E6WsbBTYWxGcMPwLnlvgmmXJBOLC6qj07eXu X/fd5FwKSRJPMYIGT47zsnFdZdrN1SOOM537XH8CX+xQPTg/J8NeaiqoaWjTKLMn PpXizt1AbuV1/0/Zqp6VKgTA/sxYtMfc4mFWjfovHlxJ/ahA19DaQjeWneIjldk= =LkuV -----END PGP SIGNATURE----- From aznjonn at me.com Tue May 3 13:27:27 2011 From: aznjonn at me.com (Johnson Tran) Date: Tue, 03 May 2011 04:27:27 -0700 Subject: [Tutor] ValueError In-Reply-To: <4DBFE047.8060605@aim.com> References: <4DBFE047.8060605@aim.com> Message-ID: <5B123049-D6CD-488A-866B-F79F740AF39E@me.com> Thanks for the replies..so I added the "try" block but it still does not seem to be outputting my default error message: def Conversion(): try: print "This program converts the first value from inches to centimeters and second value centimeters to inches." print "(1 inch = 2.54 centimeters)" inches = input("Enter length in inches: ") centimeters = 2.54 * float(inches) print "That is", centimeters, "centimeters." centimeters = input("Enter length in centimeters: ") inch = float(centimeters) / 2.54 print "That is", inch, "inches." except ValueError: print "Invalid digit, please try again." Conversion() Error message: Traceback (most recent call last): File "/Users/JT/Desktop/hw#2.py", line 16, in Conversion() File "/Users/JT/Desktop/hw#2.py", line 9, in Conversion centimeters = input("Enter length in centimeters: ") File "", line 1, in NameError: name 'fs' is not defined On May 3, 2011, at 4:00 AM, Corey Richardson wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On 05/03/2011 06:30 AM, Johnson Tran wrote: >> Hi All, >> >> i am trying to create a program module with two functions (conversion inches to centimeters then centimeter to inches, I have my program working although I am trying to adda Value Error function to my program but cannot seem to it to work: >> >> >> def Conversion(): >> print "This program converts the first value from inches to centimeters and second value centimeters to inches." >> print "(1 inch = 2.54 centimeters)" >> inches = input("Enter length in inches: ") >> centimeters = 2.54 * inches >> print "That is", centimeters, "centimeters." >> >> centimeters = input("Enter length in centimeters: ") >> inch = centimeters / 2.54 >> print "That is", inch, "inches." >> >> except ValueError: >> print "Invalid digit, please try again." >> >> Conversion() >> >> >> >> Any advice would be great, thanks! >> >> JT > > Well, you need a 'try' block before that except. Example: > > try: > foo = int("blargh") > except ValueError: > pass > > It looks like you're forgetting an important operation on the inches > variable, as well as centimeters later on. > > Take a look at > http://docs.python.org/library/stdtypes.html#typesnumeric > > For future questions, it's best to include what your program /is/ doing > that you think it shouldn't be, as well as any errors (tracebacks, copy > the whole thing!) you get. > > - -- > Corey Richardson > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v2.0.17 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ > > iQEcBAEBAgAGBQJNv+BHAAoJEAFAbo/KNFvpCdwH/0DRxVjevNxZy2HtYuxykzlA > x2ni1VnDMyS2YCsHvqIaglfK2hBeL+nstGL8kmEhGu4t5Z85nqGt9Ea2spPhPDxE > UJJ1O2nYFtLUZ1BC03vkC8aHI0aiijZjg7v7adKW4sD2laGTaeryLLR1qbGh3ZBP > rKTWK/NuyyMDRYjnP0gXsiYYNPc6E6WsbBTYWxGcMPwLnlvgmmXJBOLC6qj07eXu > X/fd5FwKSRJPMYIGT47zsnFdZdrN1SOOM537XH8CX+xQPTg/J8NeaiqoaWjTKLMn > PpXizt1AbuV1/0/Zqp6VKgTA/sxYtMfc4mFWjfovHlxJ/ahA19DaQjeWneIjldk= > =LkuV > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Tue May 3 14:01:03 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 May 2011 14:01:03 +0200 Subject: [Tutor] ValueError References: <4DBFE047.8060605@aim.com> <5B123049-D6CD-488A-866B-F79F740AF39E@me.com> Message-ID: Johnson Tran wrote: > Thanks for the replies..so I added the "try" block but it still does not > seem to be outputting my default error message: > > def Conversion(): > try: > > print "This program converts the first value from inches to > centimeters and second value centimeters to inches." print "(1 > inch = 2.54 centimeters)" inches = input("Enter length in inches: > ") centimeters = 2.54 * float(inches) > print "That is", centimeters, "centimeters." > centimeters = input("Enter length in centimeters: ") > inch = float(centimeters) / 2.54 > print "That is", inch, "inches." > > except ValueError: > print "Invalid digit, please try again." > Conversion() > > Error message: > > Traceback (most recent call last): > File "/Users/JT/Desktop/hw#2.py", line 16, in > Conversion() > File "/Users/JT/Desktop/hw#2.py", line 9, in Conversion > centimeters = input("Enter length in centimeters: ") > File "", line 1, in > NameError: name 'fs' is not defined input() in Python 2.x tries to evaluate your input as a Python expression, so if you enter "2*2" it gives you 4, and when you enter "fs" it tries to look up the value of a global variable "fs" in your python script. You don't have such a variable in your script, so it complains with a NameError. The best way to avoid such puzzling behaviour is to use raw_input() instead of input(). Also you should make the try...except as narrow as possible try: centimeters = float(centimeters) except ValueError as e: print e is likely to catch the float conversion while with many statements in the try-suite you are more likely to hide a problem that is unrelated to that conversion. PS: In Python 3.x raw_input() is gone, but input() behaves like raw_input() in 2.x From aznjonn at me.com Tue May 3 14:12:00 2011 From: aznjonn at me.com (Johnson Tran) Date: Tue, 03 May 2011 05:12:00 -0700 Subject: [Tutor] ValueError In-Reply-To: References: <4DBFE047.8060605@aim.com> <5B123049-D6CD-488A-866B-F79F740AF39E@me.com> Message-ID: <80976326-1C1F-4C41-B094-876C60464201@me.com> I am using python 2.5...and adding raw_input has fixed the issue, thank you! On May 3, 2011, at 5:01 AM, Peter Otten wrote: > Johnson Tran wrote: > >> Thanks for the replies..so I added the "try" block but it still does not >> seem to be outputting my default error message: >> >> def Conversion(): >> try: >> >> print "This program converts the first value from inches to >> centimeters and second value centimeters to inches." print "(1 >> inch = 2.54 centimeters)" inches = input("Enter length in inches: >> ") centimeters = 2.54 * float(inches) >> print "That is", centimeters, "centimeters." >> centimeters = input("Enter length in centimeters: ") >> inch = float(centimeters) / 2.54 >> print "That is", inch, "inches." >> >> except ValueError: >> print "Invalid digit, please try again." >> Conversion() >> >> Error message: >> >> Traceback (most recent call last): >> File "/Users/JT/Desktop/hw#2.py", line 16, in >> Conversion() >> File "/Users/JT/Desktop/hw#2.py", line 9, in Conversion >> centimeters = input("Enter length in centimeters: ") >> File "", line 1, in >> NameError: name 'fs' is not defined > > input() in Python 2.x tries to evaluate your input as a Python expression, > so if you enter "2*2" it gives you 4, and when you enter "fs" it tries to > look up the value of a global variable "fs" in your python script. You don't > have such a variable in your script, so it complains with a NameError. > > The best way to avoid such puzzling behaviour is to use raw_input() instead > of input(). > > Also you should make the try...except as narrow as possible > > try: > centimeters = float(centimeters) > except ValueError as e: > print e > > is likely to catch the float conversion while with many statements in the > try-suite you are more likely to hide a problem that is unrelated to that > conversion. > > PS: In Python 3.x raw_input() is gone, but input() behaves like raw_input() > in 2.x > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From wallenpb at gmail.com Tue May 3 18:35:16 2011 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 3 May 2011 09:35:16 -0700 Subject: [Tutor] Alternate credentials Message-ID: I am needing to run a Python networked application with a specific set of credentials, Windows AD, rather than the user's own so that the app can access the needed CIFS shares. Where should I start? --Bill Sent from my iPhone From mail at timgolden.me.uk Tue May 3 21:02:42 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 03 May 2011 20:02:42 +0100 Subject: [Tutor] Alternate credentials In-Reply-To: References: Message-ID: <4DC05152.3040508@timgolden.me.uk> On 03/05/2011 5:35 PM, Bill Allen wrote: > I am needing to run a Python networked application with a specific > set of credentials, Windows AD, rather than the user's own so that > the app can access the needed CIFS shares. Where should I start? By saying what operating system you're running on, which will make quite a bit of difference to the answer. TJG From s.charonis at gmail.com Wed May 4 00:20:17 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Tue, 3 May 2011 23:20:17 +0100 Subject: [Tutor] Filtering out unique list elements Message-ID: Dear All, I have built a list with multiple occurrences of a string after some text processing that goes something like this: [cat, dog, cat, cat, cat, dog, dog, tree, tree, tree, bird, bird, woods, woods] I am wondering how to truncate this list so that I only print out the unique elements, i.e. the same list but with one occurrence per element: [cat, dog, tree, bird, woods] Any help much appreciated! Regards, Spyros -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Wed May 4 00:38:11 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Tue, 3 May 2011 18:38:11 -0400 Subject: [Tutor] Filtering out unique list elements In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA36974B2@EMARC112VS01.exchad.jpmchase.net> >>> set(['cat', 'dog', 'cat', 'cat', 'cat', 'dog', 'dog', 'tree', 'tree', 'tree', 'bird', 'bird', 'woods', 'wood']) set(['woods', 'tree', 'dog', 'cat', 'wood', 'bird']) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Spyros Charonis Sent: Tuesday, May 03, 2011 5:20 PM To: tutor Subject: [Tutor] Filtering out unique list elements Dear All, I have built a list with multiple occurrences of a string after some text processing that goes something like this: [cat, dog, cat, cat, cat, dog, dog, tree, tree, tree, bird, bird, woods, woods] I am wondering how to truncate this list so that I only print out the unique elements, i.e. the same list but with one occurrence per element: [cat, dog, tree, bird, woods] Any help much appreciated! Regards, Spyros This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Wed May 4 00:42:35 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 03 May 2011 18:42:35 -0400 Subject: [Tutor] Filtering out unique list elements In-Reply-To: References: Message-ID: <4DC084DB.2090107@aim.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/03/2011 06:20 PM, Spyros Charonis wrote: > [cat, dog, cat, cat, cat, dog, dog, tree, tree, tree, bird, bird, woods, > woods] > > I am wondering how to truncate this list so that I only print out the unique > elements, i.e. the same list but with one occurrence per element: > > [cat, dog, tree, bird, woods] > > Any help much appreciated! The set type enforces uniqueness: http://docs.python.org/library/stdtypes.html#set You would use list(set(l)) to get the list from l where everything is unique. - -- Corey Richardson -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJNwITbAAoJEAFAbo/KNFvp9FYH/RMM0lqzBCoC5L3W4xIk6jNF gU1vs3phP/EaD/l2kil/FjRrO6nNuV91415GeSfVFKo3FXZsq0LnEaOz1b4sZCdk vmdFdONBugMixuuS8Iid3zB1hNmporc5kU2ze423MvxaDmPR0MGYYsZQ3LzFZDKK eVFTQcdvP4Tw3o21jXBcoaVHbW+GFgmxzFzsp90CgU7Dgt9o0i4YEn2IYOMETNdC 6o/EgWL7oPiWnq0os6pzo9PbhbJ9VU38ICCW/KQkk1xqrXUtXU+RHZqktWSp8kEv AQ7FqlYamOc0wZin/SSasGo7TOzVX3MFkW/rr/d8ZormCXs2tabDUcBw1XBKzok= =UcP6 -----END PGP SIGNATURE----- From alan.gauld at btinternet.com Wed May 4 01:18:20 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 May 2011 00:18:20 +0100 Subject: [Tutor] Alternate credentials References: Message-ID: "Bill Allen" wrote >I am needing to run a Python networked application > with a specific set of credentials, Windows AD, rather > than the user's own so that the app can access the > needed CIFS shares. Where should I start? Since its more a Windows question than a Python one I suggest you try a Windows forum. comp.python.windows might be worth a try? Or even the ctypes group? While we do have some Windows users here its not really a python nwewbie type question. Alan G. From wallenpb at gmail.com Wed May 4 01:56:11 2011 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 3 May 2011 16:56:11 -0700 Subject: [Tutor] Alternate credentials In-Reply-To: <4DC05152.3040508@timgolden.me.uk> References: <4DC05152.3040508@timgolden.me.uk> Message-ID: <4FE184F1-8132-4EDE-959F-D01A17E7EFF2@gmail.com> I am running on MS Windows XP & Server 2003. Sent from my iPhone On May 3, 2011, at 12:02, Tim Golden wrote: > On 03/05/2011 5:35 PM, Bill Allen wrote: >> I am needing to run a Python networked application with a specific >> set of credentials, Windows AD, rather than the user's own so that >> the app can access the needed CIFS shares. Where should I start? > > By saying what operating system you're running on, which will > make quite a bit of difference to the answer. > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From weaselkeeper at gmail.com Wed May 4 06:25:27 2011 From: weaselkeeper at gmail.com (Jim Richardson) Date: Tue, 3 May 2011 21:25:27 -0700 Subject: [Tutor] Unpack requires a string argument of length 8 In-Reply-To: References: Message-ID: On Mon, May 2, 2011 at 1:17 PM, Marc Tompkins wrote: > On Mon, May 2, 2011 at 12:36 PM, Susana Iraiis Delgado Rodriguez > wrote: >> >> I'm working on getting information that comes from a dbf file (database), >> this dbf file is related to another file in the system, a shapefile. My code >> is trying to get all the dbf name records, but when the systen gets an empty >> file, my code fails: >> Traceback (most recent call last): >> ? File "", line 1, in >> ? File "get_dbf.py", line 32, in >> ??? dbf = Dbf(d,new=False, readOnly=True) >> ? File "C:\Python26\lib\site-packages\dbf.py", line 135, in __init_ >> ??? self.header = self.HeaderClass.fromStream(self.stream) >> ? File "C:\Python26\lib\site-packages\header.py", line 109, in from >> ??? (_cnt, _hdrLen, _recLen) = struct.unpack("> struct.error: unpack requires a string argument of length 8 >> >>> >> How can I fix it? > > You said that this happens when you're trying to process an empty file.? If > that's the case, then I would certainly expect this: "_data[4:12]"? not to > return a string of length 8! > > So you have two options: > - "Get permission" >> >> if (some check to make sure the file isn't empty): >> ??? dbf = Dbf(d,new=False, readOnly=True) > > or > - "Ask forgiveness". >> >> try: >> ??? dbf = Dbf(d,new=False, readOnly=True) >> except: >> ??? (cleanup code to handle aborted file opening) >> > > Which is correct?? That depends on your own preference, and also on how > often the error occurs.? If you rarely run across empty files, then "ask > forgiveness" makes more sense, since otherwise you waste time checking for > an error that hardly ever happens; on the other hand, if you run into lots > of empty files, then it makes sense to check first, each time. Also, the first option does leave the possibility of a race condition, however slim that might be. Personally, I'd use the try/except pair, and optimize later if it turned out to be an issue. -- http://neon-buddha.net From kushal.kumaran+python at gmail.com Wed May 4 06:40:43 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Wed, 4 May 2011 10:10:43 +0530 Subject: [Tutor] ValueError In-Reply-To: References: <4DBFE047.8060605@aim.com> <5B123049-D6CD-488A-866B-F79F740AF39E@me.com> Message-ID: On Tue, May 3, 2011 at 5:31 PM, Peter Otten <__peter__ at web.de> wrote: > > > Also you should make the try...except as narrow as possible > > try: > ? ?centimeters = float(centimeters) > except ValueError as e: > ? ?print e > > is likely to catch the float conversion while with many statements in the > try-suite you are more likely to hide a problem that is unrelated to that > conversion. > I would have expected it to be the other way. If you cannot reasonable expect to continue after an exception, then the try block should extend all the way across the block of code you want to skip. In your snippet, what if some code later is relying on the 'centimeters' variable having a useful float value? IMO, encapsulating small bits of code in try ... except blocks really makes code written using exceptions look ugly. -- regards, kushal From mail at timgolden.me.uk Wed May 4 09:57:15 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 04 May 2011 08:57:15 +0100 Subject: [Tutor] Alternate credentials In-Reply-To: References: Message-ID: <4DC106DB.1050005@timgolden.me.uk> On 04/05/2011 00:18, Alan Gauld wrote: > Since its more a Windows question than a Python one I suggest you try a > Windows forum. comp.python.windows might be worth a try? Or even the > ctypes group? > > While we do have some Windows users here its not really a python nwewbie > type question. True enough. I should be able to help nonetheless; but I would second the recommendation to post this kind of question to the python-win32 mailing list: http://mail.python.org/mailman/listinfo/python-win32 where you'll get the benefit of a lot more knowledge and experience in the Windows area. You could obviously achieve this *outside* Python -- ie by using RunAs to launch a process as a different user. This may or may not suit your case. If you want to do the switch from within the Python process, you'll need to use the LogonUser [1] and ImpersonateLoggedOnUser [2] APIs which are both available in the pywin32 win32security module. If you only want to make a connection under this alternative identity (and not to do anything locally) then you could connect transiently with specific credentials. To do this you'd use the WNetAddConnection family of APIs [3]. Feel free to come back (or post to the python-win32 list) for more information TJG [1] http://msdn.microsoft.com/en-us/library/aa378184%28v=vs.85%29.aspx [2] http://msdn.microsoft.com/en-us/library/aa378612%28v=vs.85%29.aspx [3] http://msdn.microsoft.com/en-us/library/aa385418%28v=vs.85%29.aspx From alan.gauld at btinternet.com Wed May 4 10:57:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 May 2011 09:57:16 +0100 Subject: [Tutor] ValueError References: <4DBFE047.8060605@aim.com><5B123049-D6CD-488A-866B-F79F740AF39E@me.com> Message-ID: "Kushal Kumaran" wrote >> Also you should make the try...except as narrow as possible >> >> try: >> centimeters = float(centimeters) >> except ValueError as e: >> print e >>... > > I would have expected it to be the other way. If you cannot > reasonable expect to continue after an exception, then the try block > should extend all the way across the block of code you want to skip. There are at least 2 schools of thought on the use of try/except. One says put all of the "happy path" processing in the try block and handle all exceptions at the end. This is very much the original ADA style that was envisioned when try/except style first appeared and also in early C++ texts they recommended that style. The other says keep try/except as narrow as possible so you can localise (and maybe correct!) the error. Both approaches have merit. The first leads to much more readable code and that in turn has proven to result in more reliable code, however the second tends to be more practical in real world projects. The problem with the first approach is that there can be multiple places in a block raising the same error and then determining the cause in the except becomes hard. This is especially true when the block contains calls to functions which may unexpectedly raise errors that may not be documented in their spec. On the other hand putting try/except around each line of code leads to unreadable and unmanageable code. So a compromise is needed and most programmers settle for something like an "atomic transaction" style of block. A short group of lines that does something meaningful and which needs to pass or fail as a unit. If we plan to attempt error recovery then it also needs to only raise any given exception type once. (Or we need to be prepared to use introspection to determine the cause). But like most design decisions it is a compromise solution in either case and the programmer must decide where to make the trade-off. As an example, consider the case of reading a set of config values from a file. We have a choice of what to do if things go wrong: a) Just bomb out with an error message saying we couldn't read the config data b) On any error set the config data to a set of default values and continue c) Detect which value failed and set that to a default using any other values from the file. For a and b the open plus all of the read/convert/assign operations can be done within the try block. For c we would need a try/except around each read/convert/assign operation. Style c is probably the most user friendly, provided there are no complex dependencies between the config values, but there is no absolute right or wrong decision it is down to the designer. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Wed May 4 11:43:19 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 May 2011 11:43:19 +0200 Subject: [Tutor] ValueError References: <4DBFE047.8060605@aim.com> <5B123049-D6CD-488A-866B-F79F740AF39E@me.com> Message-ID: Kushal Kumaran wrote: > On Tue, May 3, 2011 at 5:31 PM, Peter Otten <__peter__ at web.de> wrote: >> >> >> Also you should make the try...except as narrow as possible >> >> try: >> centimeters = float(centimeters) >> except ValueError as e: >> print e >> >> is likely to catch the float conversion while with many statements in the >> try-suite you are more likely to hide a problem that is unrelated to that >> conversion. >> > > I would have expected it to be the other way. If you cannot > reasonable expect to continue after an exception, then the try block > should extend all the way across the block of code you want to skip. > In your snippet, what if some code later is relying on the > 'centimeters' variable having a useful float value? IMO, > encapsulating small bits of code in try ... except blocks really makes > code written using exceptions look ugly. Instead of repeating what Alan said I'll give you a side-by-side example: import sys def make_raw_input(stdin, stdout): def raw_input(message): stdout.write(message) s = stdin.readline() stdout.write(s) return s.rstrip("\n") return raw_input if not sys.stdin.isatty(): raw_input = make_raw_input(sys.stdin, sys.stdout) _conversion_factors = {"in": (2.54, "cm"), "cm": (1/2.54, "in")} def thorough_convert(): default_unit = "in" while True: s = raw_input("Enter a length in inches or cm (like '7 in' or '1.3 cm') ") if not s: print "That's all, folks" break try: value, unit = s.split(None, 1) except ValueError as e: value = s unit = default_unit print "using default unit:", unit try: conversion_factor, target_unit = _conversion_factors[unit] except KeyError: print "unrecognized length unit: {!r}".format(unit) continue default_unit = unit try: value = float(value) except ValueError as e: print e else: target_value = value * conversion_factor print "{} {} --> {} {}".format(value, unit, target_value, target_unit) def simple_convert(): while True: try: s = raw_input("Enter a length in inches or cm (like '7 in' or '1.3 cm') ") if not s: break value, unit = s.split() factor, target_unit = _conversion_factors[unit] print s, "-->", float(value)*factor, target_unit except Exception as e: print e if __name__ == "__main__": if "--simple" in sys.argv: convert = simple_convert else: convert = thorough_convert if "--demo" in sys.argv: from StringIO import StringIO raw_input = make_raw_input(StringIO("""\ 1 cm 2 in 3 x 4 """), sys.stdout) convert() Let's run the demo: $python2.7 inch.py --demo --simple Enter a length in inches or cm (like '7 in' or '1.3 cm') 1 cm 1 cm --> 0.393700787402 in Enter a length in inches or cm (like '7 in' or '1.3 cm') 2 in 2 in --> 5.08 cm Enter a length in inches or cm (like '7 in' or '1.3 cm') 3 x 'x' Enter a length in inches or cm (like '7 in' or '1.3 cm') 4 need more than 1 value to unpack Enter a length in inches or cm (like '7 in' or '1.3 cm')$ python2.7 inch.py --demo --thorough Enter a length in inches or cm (like '7 in' or '1.3 cm') 1 cm 1.0 cm --> 0.393700787402 in Enter a length in inches or cm (like '7 in' or '1.3 cm') 2 in 2.0 in --> 5.08 cm Enter a length in inches or cm (like '7 in' or '1.3 cm') 3 x unrecognized length unit: 'x' Enter a length in inches or cm (like '7 in' or '1.3 cm') 4 using default unit: in 4.0 in --> 10.16 cm Enter a length in inches or cm (like '7 in' or '1.3 cm') That's all, folks While thorough_convert() is three times as long as simple_convert() and both do almost the same I'd argue that the user experience is significantly improved by better error messages and smarter defaults. From steve at pearwood.info Wed May 4 12:12:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 04 May 2011 20:12:44 +1000 Subject: [Tutor] Filtering out unique list elements In-Reply-To: References: Message-ID: <4DC1269C.5030009@pearwood.info> Spyros Charonis wrote: > Dear All, > > I have built a list with multiple occurrences of a string after some text > processing that goes something like this: > > [cat, dog, cat, cat, cat, dog, dog, tree, tree, tree, bird, bird, woods, > woods] > > I am wondering how to truncate this list so that I only print out the unique > elements, i.e. the same list but with one occurrence per element: > > [cat, dog, tree, bird, woods] Others have already mentioned set(), but unless I missed something, nobody pointed out that sets are unordered, and so will lose whatever order was in the list: >>> # words = [cat, dog, cat, cat, cat etc...] >>> set(words) set(['bird', 'woods', 'tree', 'dog', 'cat']) They also didn't mention that sets require the items to be hashable: >>> set(['bird', {}, 'cow']) Traceback (most recent call last): File "", line 1, in TypeError: dict objects are unhashable If neither of those limitations matter to you, then sets will be the fastest and easiest solution. Alternatively, if you only have a few elements: unique = [] for element in items: if element not in unique: unique.append(element) However this will be SLOW if you have many items. Here are some more recipes: http://code.activestate.com/recipes/52560-remove-duplicates-from-a-sequence/ -- Steven From wallenpb at gmail.com Wed May 4 17:40:58 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 4 May 2011 08:40:58 -0700 Subject: [Tutor] Alternate credentials In-Reply-To: <4DC106DB.1050005@timgolden.me.uk> References: <4DC106DB.1050005@timgolden.me.uk> Message-ID: On May 4, 2011, at 0:57, Tim Golden wrote: > On 04/05/2011 00:18, Alan Gauld wrote: >> Since its more a Windows question than a Python one I suggest you try a >> Windows forum. comp.python.windows might be worth a try? Or even the >> ctypes group? >> >> While we do have some Windows users here its not really a python nwewbie >> type question. > > > > Feel free to come back (or post to the python-win32 list) for more > information > > TJG Tim, yes Alan is right about that. I was unaware of the python-win32 group. I think you have given me a good place to start on this and I really appreciate the help. --Bill From jeffpeery at seametrics.com Wed May 4 17:38:28 2011 From: jeffpeery at seametrics.com (Jeff Peery) Date: Wed, 4 May 2011 08:38:28 -0700 Subject: [Tutor] Problem Automating Internet Explorer Printing Message-ID: <22D249B9E041654AA140F32C0E6F942753D53464F8@EXVMBX018-3.exch018.msoutlookonline.net> Hello, I'm using the code pasted below to print a document. The code worked great on my XP machine. I moved it to my W7 machine and it gives the error below. The weird thing is that it works great if printing a html doc from the web (such as www.google.com), but it errors when printing a html doc from my desktop. The document loads as I can see it on the screen, but it chokes when printing. any ideas? thanks, Jeff line 23, in Print win32com.client.constants.OLECMDEXECOPT_DONTPROMPTUSER) File "C:\Python27\lib\site-packages\win32com\gen_py\EAB22AC0-30C1-11CF-A7EB-0000C05BAE0Bx0x1x1.py", line 1186, in ExecWB , cmdexecopt, pvaIn, pvaOut) File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 456, in _ApplyTypes_ self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args), com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221248), None) import win32com.client from time import sleep class Printer(): def __init__(self): pass def WaitBusy(self, ie): while ie.Busy: sleep(0.5) def WaitUntilReady(self, ie): while ie.ReadyState!=4: sleep(0.5) def Print(self, doc_name): ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 ie.Navigate(doc_name) # wait for ie to open before printing self.WaitBusy(ie) ie.ExecWB(win32com.client.constants.OLECMDID_PRINT, win32com.client.constants.OLECMDEXECOPT_DONTPROMPTUSER) ## ie.Quit() p = Printer() p.Print('test.htm') -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.charonis at gmail.com Wed May 4 20:31:07 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Wed, 4 May 2011 19:31:07 +0100 Subject: [Tutor] triple-nested for loop not working Message-ID: Hello everyone, I have written a program, as part of a bioinformatics project, that extracts motif sequences (programmatically just strings of letters) from a database and writes them to a file. I have written another script to annotate the database file (in plaintext ASCII format) by replacing every match of a motif with a sequence of tildes (~). Primitive I know, but not much more can be done with ASCII files. The code goes as follows: motif_file = open('myfolder/pythonfiles/final motifs_11SGLOBULIN', 'r') # => final motifs_11sglobulin contains the output of my first program align_file = open('myfolder/pythonfiles/11sglobulin.seqs', 'a+') # => 11sglobulin.seqs is the ASCII sequence alignment file which I want to "annotate" (modify) finalmotif_seqs = [] finalmotif_length = [] # store length of each motif finalmotif_annot = [] for line in finalmotifs: finalmotif_seqs.append(line) mot_length = len(line) finalmotif_length.append(mot_length) for item in finalmotif_length: annotation = '~' * item finalmotif_annot.append(annotation) finalmotifs = motif_file.readlines() seqalign = align_file.readlines() for line in seqalign: for i in len(finalmotif_seqs): # for item in finalmotif_seqs: for i in len(finalmotif_annot): # for item in finalmotif_annot: if finalmotif_seqs[i] in line: # if item in line: newline = line.replace(finalmotif_seqs[i], finalmotif_annot[i]) #sys.stdout.write(newline) # => print the lines out on the shell align_file.writelines(newline) motif_file.close() align_file.close() My coding issue is that although the script runs, there is a logic error somewhere in the triple-nested for loop as I when I check my file I'm supposedly modifying there is no change. All three lists are built correctly (I've confirmed this on the Python shell). Any help would be much appreciated! I am running Python 2.6.5 -------------- next part -------------- An HTML attachment was scrubbed... URL: From glchristian at comcast.net Wed May 4 20:37:39 2011 From: glchristian at comcast.net (Greg Christian) Date: Wed, 4 May 2011 12:37:39 -0600 Subject: [Tutor] Reading elements in a file Message-ID: <0490F53EC69042DE9318585574B5125A@GREGPC> I am kind of stuck on what is probably a simple thing: If we have a file of words like this: ?first?,?word?,?in?,?that?,?another?,?part?,?of?,?this? f = open('words.txt', "r") words = f.read() will read the whole file, is there a way to read just the words: first word in that another part of this I guess I have to separate on the ?,? but I am not quite sure how to go about this. Any input would be appreciated. Regards, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From glchristian at comcast.net Wed May 4 20:40:08 2011 From: glchristian at comcast.net (Greg Christian) Date: Wed, 4 May 2011 12:40:08 -0600 Subject: [Tutor] Reading elements in a file Message-ID: Python version = 2.7.1 Platform = win32 I am kind of stuck on what is probably a simple thing: If we have a file of words like this: ?first?,?word?,?in?,?that?,?another?,?part?,?of?,?this? f = open('words.txt', "r") words = f.read() will read the whole file, is there a way to read just the words: first word in that another part of this I guess I have to separate on the ?,? but I am not quite sure how to go about this. Any input would be appreciated. Regards, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From ademlookes at gmail.com Wed May 4 21:01:17 2011 From: ademlookes at gmail.com (Adam Lucas) Date: Wed, 4 May 2011 14:01:17 -0500 Subject: [Tutor] triple-nested for loop not working In-Reply-To: References: Message-ID: On Wed, May 4, 2011 at 13:31, Spyros Charonis wrote: > Hello everyone, > > I have written a program, as part of a bioinformatics project, that > extracts motif sequences (programmatically just strings of letters) from a > database and writes them to a file. > I have written another script to annotate the database file (in plaintext > ASCII format) by replacing every match of a motif with a sequence of tildes > (~). Primitive I know, but not much more can be done with ASCII files. The > code goes as follows: > > > motif_file = open('myfolder/pythonfiles/final motifs_11SGLOBULIN', 'r') # > => final motifs_11sglobulin contains the output of my first program > align_file = open('myfolder/pythonfiles/11sglobulin.seqs', 'a+') # > => 11sglobulin.seqs is the ASCII sequence alignment file which I want to > "annotate" (modify) > > finalmotif_seqs = [] > finalmotif_length = [] # store length of each motif > finalmotif_annot = [] > > for line in finalmotifs: > finalmotif_seqs.append(line) > mot_length = len(line) > finalmotif_length.append(mot_length) > > for item in finalmotif_length: > annotation = '~' * item > finalmotif_annot.append(annotation) > > finalmotifs = motif_file.readlines() > seqalign = align_file.readlines() > > for line in seqalign: > for i in len(finalmotif_seqs): # for item in finalmotif_seqs: > for i in len(finalmotif_annot): # for item in finalmotif_annot: > if finalmotif_seqs[i] in line: # if item in line: > newline = line.replace(finalmotif_seqs[i], > finalmotif_annot[i]) > #sys.stdout.write(newline) # => print the lines out > on the shell > align_file.writelines(newline) > Pay attention to scope with the elements of your iteration loops. If you call everything 'item' you can confuse yourself, others, and the interpreter as to which 'item' you're talking about. > > motif_file.close() > align_file.close() > > > My coding issue is that although the script runs, there is a logic error > somewhere in the triple-nested for loop as I when I check my file I'm > supposedly modifying there is no change. All three lists are built correctly > (I've confirmed this on the Python shell). Any help would be much > appreciated! > I am running Python 2.6.5 > > > _______________________________________________ > 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 alchemy.com Wed May 4 21:09:30 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 04 May 2011 12:09:30 -0700 Subject: [Tutor] Reading elements in a file In-Reply-To: References: Message-ID: <4DC1A46A.2040802@alchemy.com> On 04-May-11 11:40, Greg Christian wrote: > Python version = 2.7.1 > Platform = win32 > I am kind of stuck on what is probably a simple thing: > If we have a file of words like this: > ?first?,?word?,?in?,?that?,?another?,?part?,?of?,?this? It depends on exactly how "just like" that example the file is. For example, if it's a comma-separated value (CSV) file, with values enclosed optionally in quotes (as shown in your example), you can very easily and yet robustly read it using the csv module in the standard library. Otherwise you could use regular expressions to find text inside "" quotes and ignore the commas. Or split on ',' then strip quotes, or... CSV is easiest if that's a match for your problem domain. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From jeffpeery at seametrics.com Wed May 4 21:34:34 2011 From: jeffpeery at seametrics.com (Jeff Peery) Date: Wed, 4 May 2011 12:34:34 -0700 Subject: [Tutor] Reading elements in a file In-Reply-To: <0490F53EC69042DE9318585574B5125A@GREGPC> References: <0490F53EC69042DE9318585574B5125A@GREGPC> Message-ID: <22D249B9E041654AA140F32C0E6F942753D53465B6@EXVMBX018-3.exch018.msoutlookonline.net> Greg, You might try? Import sting delimiter = ?.? f = open('words.txt', "r") lines = f.readlines() for line in lines: line_items = string.split(line,delimiter) From: tutor-bounces+jeffpeery=seametrics.com at python.org [mailto:tutor-bounces+jeffpeery=seametrics.com at python.org] On Behalf Of Greg Christian Sent: Wednesday, May 04, 2011 11:38 AM To: tutor at python.org Subject: [Tutor] Reading elements in a file I am kind of stuck on what is probably a simple thing: If we have a file of words like this: ?first?,?word?,?in?,?that?,?another?,?part?,?of?,?this? f = open('words.txt', "r") words = f.read() will read the whole file, is there a way to read just the words: first word in that another part of this I guess I have to separate on the ?,? but I am not quite sure how to go about this. Any input would be appreciated. Regards, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Wed May 4 22:41:32 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 4 May 2011 16:41:32 -0400 Subject: [Tutor] Reading elements in a file In-Reply-To: <22D249B9E041654AA140F32C0E6F942753D53465B6@EXVMBX018-3.exch018.msoutlookonline.net> References: <0490F53EC69042DE9318585574B5125A@GREGPC> <22D249B9E041654AA140F32C0E6F942753D53465B6@EXVMBX018-3.exch018.msoutlookonline.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA36983C9@EMARC112VS01.exchad.jpmchase.net> Use of string module directly seems to be deprecated; you can access any member functions from the string directly. See below. delimiter = ?.? f = open('words.txt', "r") lines = f.readlines() for line in lines: line_items = line.split(delimiter) Also, you can read a single line at a time with readline() (and yes I am sure there is a more pythonic way to do the while loop). delimiter = ?.? f = open('words.txt', "r") line = f.readline() while line line_items = line.split(delimiter) line = f.readline() Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Jeff Peery Sent: Wednesday, May 04, 2011 2:35 PM To: Greg Christian; tutor at python.org Subject: Re: [Tutor] Reading elements in a file Greg, You might try? Import sting delimiter = ?.? f = open('words.txt', "r") lines = f.readlines() for line in lines: line_items = string.split(line,delimiter) This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Wed May 4 22:35:53 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 4 May 2011 16:35:53 -0400 Subject: [Tutor] triple-nested for loop not working In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA36983A0@EMARC112VS01.exchad.jpmchase.net> Your problem is most likely here. for line in seqalign: for i in len(finalmotif_seqs): # for item in finalmotif_seqs: for i in len(finalmotif_annot): # for item in finalmotif_annot: instead of for line in seqalign: for i in xrange(len(finalmotif_seqs)): # for item in finalmotif_seqs: for i in xrange(len(finalmotif_annot)): # for item in finalmotif_annot: len just returns one number. So for each loop, you are running through the loop only once where i= whatever len returned. >>> for x in (5,6,7,8): ... print x ... 5 6 7 8 Honestly, I am not sure why you are not getting the following error >>> for x in len((5,6,7,8)): ... print x ... TypeError: 'int' object is not iterable I would also avoid using "i" as your nested loop counter. It might work in this instance, but gives you more confusion and less flexibility. See the following example >>> for x in xrange(3): ... print "level 1=", x ... for x in xrange(4,5): ... print "level 2=", x ... for x in xrange(6,9): ... print "level 3=", x ... level 1= 0 level 2= 4 level 3= 6 level 3= 7 level 3= 8 level 1= 1 level 2= 4 level 3= 6 level 3= 7 level 3= 8 level 1= 2 level 2= 4 level 3= 6 level 3= 7 level 3= 8 Instead use separate variables. This allows for easier understandability and for accessing them from nested loop levels. >>> for x in xrange(3): ... print "level 1=", x ... for y in xrange(4,5): ... print "level 2=", y ... for z in xrange(6,9): ... print "level 3=", z, ' | level 2=', y , ' | level 1=', x ... level 1= 0 level 2= 4 level 3= 6 | level 2= 4 | level 1= 0 level 3= 7 | level 2= 4 | level 1= 0 level 3= 8 | level 2= 4 | level 1= 0 level 1= 1 level 2= 4 level 3= 6 | level 2= 4 | level 1= 1 level 3= 7 | level 2= 4 | level 1= 1 level 3= 8 | level 2= 4 | level 1= 1 level 1= 2 level 2= 4 level 3= 6 | level 2= 4 | level 1= 2 level 3= 7 | level 2= 4 | level 1= 2 level 3= 8 | level 2= 4 | level 1= 2 Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Spyros Charonis Sent: Wednesday, May 04, 2011 1:31 PM To: tutor Subject: [Tutor] triple-nested for loop not working Hello everyone, I have written a program, as part of a bioinformatics project, that extracts motif sequences (programmatically just strings of letters) from a database and writes them to a file. I have written another script to annotate the database file (in plaintext ASCII format) by replacing every match of a motif with a sequence of tildes (~). Primitive I know, but not much more can be done with ASCII files. The code goes as follows: motif_file = open('myfolder/pythonfiles/final motifs_11SGLOBULIN', 'r') # => final motifs_11sglobulin contains the output of my first program align_file = open('myfolder/pythonfiles/11sglobulin.seqs', 'a+') # => 11sglobulin.seqs is the ASCII sequence alignment file which I want to "annotate" (modify) finalmotif_seqs = [] finalmotif_length = [] # store length of each motif finalmotif_annot = [] for line in finalmotifs: finalmotif_seqs.append(line) mot_length = len(line) finalmotif_length.append(mot_length) for item in finalmotif_length: annotation = '~' * item finalmotif_annot.append(annotation) finalmotifs = motif_file.readlines() seqalign = align_file.readlines() for line in seqalign: for i in len(finalmotif_seqs): # for item in finalmotif_seqs: for i in len(finalmotif_annot): # for item in finalmotif_annot: if finalmotif_seqs[i] in line: # if item in line: newline = line.replace(finalmotif_seqs[i], finalmotif_annot[i]) #sys.stdout.write(newline) # => print the lines out on the shell align_file.writelines(newline) motif_file.close() align_file.close() My coding issue is that although the script runs, there is a logic error somewhere in the triple-nested for loop as I when I check my file I'm supposedly modifying there is no change. All three lists are built correctly (I've confirmed this on the Python shell). Any help would be much appreciated! I am running Python 2.6.5 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed May 4 22:58:56 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 04 May 2011 16:58:56 -0400 Subject: [Tutor] triple-nested for loop not working In-Reply-To: References: Message-ID: <4DC1BE10.1090404@gmail.com> On 5/4/2011 2:31 PM, Spyros Charonis wrote: > Hello everyone, > > I have written a program, as part of a bioinformatics project, that > extracts motif sequences (programmatically just strings of letters) > from a database and writes them to a file. > I have written another script to annotate the database file (in > plaintext ASCII format) by replacing every match of a motif with a > sequence of tildes (~). Primitive I know, but not much more can be > done with ASCII files. The code goes as follows: > > > motif_file = open('myfolder/pythonfiles/final motifs_11SGLOBULIN', > 'r') # => final motifs_11sglobulin contains the output of my first > program > align_file = open('myfolder/pythonfiles/11sglobulin.seqs', 'a+') > # => 11sglobulin.seqs is the ASCII sequence alignment file which I > want to "annotate" (modify) > > finalmotif_seqs = [] > finalmotif_length = [] # store length of each motif > finalmotif_annot = [] > Following line will fail, as finalmotifs is not defined. It appears to be defined 10 lines later. > for line in finalmotifs: > finalmotif_seqs.append(line) > mot_length = len(line) > finalmotif_length.append(mot_length) > > for item in finalmotif_length: > annotation = '~' * item > finalmotif_annot.append(annotation) > > finalmotifs = motif_file.readlines() > seqalign = align_file.readlines() > > for line in seqalign: Next 2 for statements both use i as the loop index. Even though the program will run it is not a good idea. > for i in len(finalmotif_seqs): # for item in finalmotif_seqs: > for i in len(finalmotif_annot): # for item in > finalmotif_annot: > if finalmotif_seqs[i] in line: # if item in line: > newline = line.replace(finalmotif_seqs[i], > finalmotif_annot[i]) > #sys.stdout.write(newline) # => print the lines > out on the shell > align_file.writelines(newline) > > motif_file.close() > align_file.close() > You need 2 loops, not 3. That is way overkill.You accomplish the same thing with: # open the 3 files finalmotifs = motif_file.readlines() for line in seqalign: for item in finalmotifs: if item in line: align_file.write('~' * len(line) + '\n') # close the 3 files -- Bob Gailer 919-636-4239 Chapel Hill NC From tical_1985 at hotmail.com Wed May 4 19:30:38 2011 From: tical_1985 at hotmail.com (Patrick P.) Date: Wed, 4 May 2011 19:30:38 +0200 Subject: [Tutor] Need help with arrays Message-ID: Hello, I hope this is the right way to ask my question, if not, sorry to bother you. Maybe you can tell me who to ask. Ok so here is my code ---------------------------------------------------------------------------- import numpy as np nH = 2.2 nL = 1.7 welle = 0.5 wurzel = (8.85*10**(-12) * 12.57*10**(-7))**0.5 * 10**6 w = np.arange(0.50, 1.50, 0.01) inc = 25 inc1 = np.arcsin((1/nH))*np.sin(inc) inc2 = np.arcsin((nH/nL)*np.sin(inc1)) del0 = 2*np.pi*welle*np.cos(inc)/w del1 = 2*np.pi*nH*(welle/nH)*np.cos(inc)/w del2 = 2*np.pi*nL*(welle/nL)*np.cos(inc1)/w nu1 = wurzel*nH*np.cos(inc1) nu2 = wurzel*nL*np.cos(inc2) # Matrix 1 m111 = np.cos(del1) m121 = 1j*np.sin(del1)/nu1 m211 = 1j*nu1*np.sin(del1) m221 = np.cos(del1) A = np.array([[m111,m121], [m211,m221]]) # Matrix 2 m112 = np.cos(del2) m122 = 1j*np.sin(del2)/nu2 m212 = 1j*nu2*np.sin(del2) m222 = np.cos(del2) B = np.array([[m112,m122], [m212,m222]]) print(np.dot(A,B)) Traceback (most recent call last): File "C:/Python26/helpfiletest.py", line 36, in print(np.dot(A,B)) ValueError: objects are not aligned ------------------------------------------------------------------------------------- I get it why theres and error message, because it's trying to multiply a 2x2x100 array with another 2x2x100 array and doesn't know how to do that. What I actually want is 100 2x2 arrays and then mutliply them individually. Can anyone help me with that? Thanks a lot! Best, Patrick -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu May 5 00:23:34 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 May 2011 23:23:34 +0100 Subject: [Tutor] Need help with arrays References: Message-ID: "Patrick P." wrote > I hope this is the right way to ask my question, if not, > sorry to bother you. Maybe you can tell me who to ask. The way you ask the question is fine but the place is maybe not so good. This is a list for people learning Python but you are really asking about numpy so you might be better posting the question on a numpy forum. I believe there is a dedicated numpy mailing list. But you may be lucky and find someone here who knows the answer. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 5 00:44:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 May 2011 23:44:10 +0100 Subject: [Tutor] triple-nested for loop not working References: Message-ID: "Spyros Charonis" wrote > motif_file = open('myfolder/pythonfiles/final motifs_11SGLOBULIN', > 'r') > align_file = open('myfolder/pythonfiles/11sglobulin.seqs', 'a+') > finalmotif_seqs = [] > finalmotif_length = [] # store length of each motif > finalmotif_annot = [] > > finalmotifs = motif_file.readlines() > seqalign = align_file.readlines() NB. I've moved the lines to after the initialisation, but... > for line in finalmotifs: > finalmotif_seqs.append(line) > mot_length = len(line) > finalmotif_length.append(mot_length) > > for item in finalmotif_length: > annotation = '~' * item > finalmotif_annot.append(annotation) This seems very verbose. Why not go directly to the tildes? for line in finalmotifs: finalmotof_seqs.append(line) finalmotif_annot.append('~' * len(line)) You don't seem to use the list of lens for anything else? > for line in seqalign: > for i in len(finalmotif_seqs): # for item in > finalmotif_seqs: len() returns an integer not a sequence so you can't iterate over it, you would need range(), but... > for i in len(finalmotif_annot): # for item in > finalmotif_annot: > if finalmotif_seqs[i] in line: # if item in > line: > newline = line.replace(finalmotif_seqs[i], > finalmotif_annot[i]) > #sys.stdout.write(newline) # => print the lines > out on > the shell > align_file.writelines(newline) You comments are better python than your code is! with open(align_file) as seqalign: for line in seqalign: for seq in finalmotif_seqs: for annot in finalmotif_annot: line = line.replace(seq, annot) # +'\n'??? align_file.write(line) > motif_file.close() > align_file.close() If you use 'with' you don't need these... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 5 00:59:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 May 2011 23:59:17 +0100 Subject: [Tutor] Reading elements in a file References: <0490F53EC69042DE9318585574B5125A@GREGPC> <22D249B9E041654AA140F32C0E6F942753D53465B6@EXVMBX018-3.exch018.msoutlookonline.net> Message-ID: "Jeff Peery" wrote > Import sting Its lower case import and I've no idea what sting is! :-) If its meant to be string you don't need it. > delimiter = ?.? > f = open('words.txt', "r") > lines = f.readlines() > for line in lines: > line_items = string.split(line,delimiter) You don't need the readlines(), just do with open('words.txt', "r") as f: line_items = [line.split(',') for line in f] The string methods are builtin and the string module is really only needed for backwatds compatibility these days. Also this code returns a list of lists of words. The original code threw away the words after each line. If you want a single list of words the code would look more like: with open('words.txt', "r") as f: for line in f: line_items += line.split(',') To the OP: If you want to get rid of the " signs around your words you can use the strip() method too. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 5 01:56:41 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 5 May 2011 00:56:41 +0100 (BST) Subject: [Tutor] triple-nested for loop not working In-Reply-To: References: Message-ID: <837741.6525.qm@web86701.mail.ird.yahoo.com> CC'd to list > Thanks for your suggestions. I now see I was using far too much unnecessary > code plus data structures (lists) that were useless. I modified the entire > program to the following lines based on suggestions from yourself and > other people on the mailing list: > import os, string you don't use either os or string, so you can lose the import line > motif_file = open('myfolder/pythonfiles/final motifs_11SGLOBULIN', 'r') > align_file = open('myfolder/pythonfiles/11sglobulin.seqs', 'a+') Here is where I think the problem occurs. Do you really want to append your output to the end of the align file? Or do you want to overwrite the old content with the new? In either case the problem with opening in append mode is that the file cursor is at the end of the file. So... > finalmotifs = motif_file.readlines() > seqalign = align_file.readlines() I suspect seqalign is empty - check with a print statement to see.... for line in seqalign: and if seqalign is empty nothing else gets executed... for item in finalmotifs: if item in line: newline = line.replace(item, '' * len(item)) align_file.writelines(newline) motif_file.close() align_file.close() If you use the with statement you can dospense with the closes. Alternatively try: finalmotifs = open('myfolder/pythonfiles/final motifs_11SGLOBULIN', 'r').readlines() seqalign = open('myfolder/pythonfiles/11sglobulin.seqs', 'r').readlines() with open('myfolder/pythonfiles/11sglobulin.seqs', 'a') as align_file: for line in seqalign: # as before HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From l.leichtnam at gmail.com Thu May 5 04:45:19 2011 From: l.leichtnam at gmail.com (louis leichtnam) Date: Wed, 4 May 2011 22:45:19 -0400 Subject: [Tutor] Pictures In-Reply-To: References: <1669823197-1303962063-cardhu_decombobulator_blackberry.rim.net-2126492393-@bda740.bisx.prod.on.blackberry> Message-ID: Hello, I tried it and it works, though if I change the web site from http://finance.blog.lemonde.fr to http://www. ...something else it doesn't work. DO I have to change the '([\S]+)' in x=re.findall(r" > Observing the page source i think : > > page=urllib.urlopen('http://finance.blog.lemonde.fr').read() > > x=re.findall(r" #matches image source of the pattern like: > # y=re.findall(r" # matches image source of the pattern like: > # x.extend(y) > x=list(set(x)) > for img in x: > image=img.split('.')[-1] > if image=='jpg': > print img > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From l.leichtnam at gmail.com Thu May 5 04:51:51 2011 From: l.leichtnam at gmail.com (louis leichtnam) Date: Wed, 4 May 2011 22:51:51 -0400 Subject: [Tutor] Titles from a web page Message-ID: Hello Everyone, I'm trying to write a program that looks in a webpage in find the titles of a subsection of the page: For example you have the list of the title of stories in a newspaper under the section "World" and you you click on it you have the entire story. I want a program that print the title only of this special section of the page. Can you help me out? I tried using regular expression but I keep hitting walls and I don't know what to do... Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Thu May 5 05:52:39 2011 From: modulok at gmail.com (Modulok) Date: Wed, 4 May 2011 21:52:39 -0600 Subject: [Tutor] Titles from a web page In-Reply-To: References: Message-ID: You might look into the third party module, 'BeautifulSoup'. It's designed to help you interrogate markup (even poor markup), extracting nuggets of data based on various criteria. -Modulok- On 5/4/11, louis leichtnam wrote: > Hello Everyone, > > I'm trying to write a program that looks in a webpage in find the titles of > a subsection of the page: > > For example you have the list of the title of stories in a newspaper under > the section "World" and you you click on it you have the entire story. > > I want a program that print the title only of this special section of the > page. > > Can you help me out? I tried using regular expression but I keep hitting > walls and I don't know what to do... > > Thank you > From prologic at shortcircuit.net.au Thu May 5 07:16:36 2011 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 5 May 2011 15:16:36 +1000 Subject: [Tutor] Titles from a web page In-Reply-To: References: Message-ID: On Thu, May 5, 2011 at 1:52 PM, Modulok wrote: > You might look into the third party module, 'BeautifulSoup'. It's designed to > help you interrogate markup (even poor markup), extracting nuggets of data based > on various criteria. lxml is also work looking into which provides similar functionality. -- -- James Mills -- -- "Problems are solved by method" From motoom at xs4all.nl Thu May 5 07:27:11 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 5 May 2011 07:27:11 +0200 Subject: [Tutor] Titles from a web page In-Reply-To: References: Message-ID: <498EC3C7-AA27-4EAD-886E-35370BD3BA7C@xs4all.nl> On May 5, 2011, at 07:16, James Mills wrote: > On Thu, May 5, 2011 at 1:52 PM, Modulok wrote: >> You might look into the third party module, 'BeautifulSoup'. It's designed to >> help you interrogate markup (even poor markup), extracting nuggets of data based >> on various criteria. > > lxml is also work looking into which provides similar functionality. For especially broken markup you might even consider version 3.07a of BeautifulSoup. The parser in later versions got slightly less forgiving. Greetings, -- "Control over the use of one's ideas really constitutes control over other people's lives; and it is usually used to make their lives more difficult." - Richard Stallman From andreengels at gmail.com Thu May 5 09:22:37 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 5 May 2011 09:22:37 +0200 Subject: [Tutor] triple-nested for loop not working In-Reply-To: References: Message-ID: I have not checked the rest of your code, but: > for line in seqalign: > ?? ?for i in len(finalmotif_seqs): ? ? ?# for item in finalmotif_seqs: > ?? ? ? ?for i in len(finalmotif_annot): ? ? # for item in finalmotif_annot: I see two problems here: 1. You are using the same loop variable in both loops here. That's likely to cause problems 2. You let the loops go over len(finalmotif_seqs). len(finalmotif_seqs) is a number, and you can't loop over a number. You should use the form as you write after the #. -- Andr? Engels, andreengels at gmail.com From kbenak86 at yahoo.com Thu May 5 02:19:57 2011 From: kbenak86 at yahoo.com (Kyle Benak) Date: Wed, 4 May 2011 17:19:57 -0700 (PDT) Subject: [Tutor] assigning a variable a value Message-ID: <777142.46671.qm@web43513.mail.sp1.yahoo.com> Hi, I am learning python and I am trying to write a simple "guess the number" game.?I wrote the program in the IDLE, and?I set the variable tries=1 to keep up with the number of tries it takes to guess the number, but when I try to run the program it gives the error message "improper syntax" and highlights the word tries.? So, I assigned the variable tries the value 1 in the python shell window and it works fine there.? Can you tell me why it won't work in the program? A copy of my code is below for clarification. #Guess My Number # #The computer picks a random number between 1 and 100 #The player tries to guess it and the computer lets #the player know if the guess is too high, too low, or correct import random print('Welcome to "Guess My Number"!') print('\nI\'m thinking of a number between 1 and 100.') print('Try and guess the number in as few turns as possible.') #set initial values num = random.randint(1,100) guess = int(input('Take a guess: ') tries = 1 while guess != num: ??? if guess > num: ????????? print('Too high. Guess lower.') ??? else: ????????? print('Too low. Guess higher.') ??? guess=input('Take another guess: ') ??? tries += 1 print('You guessed it. The number was',num) print('Congratulations, You guessed the correct answer.' print('It only took you',tries,'tries.') ????? input('\n\nPress enter to exit.') I highlighted the problem in red.? Thanks for any help. Kyle -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu May 5 09:54:17 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 5 May 2011 09:54:17 +0200 Subject: [Tutor] assigning a variable a value In-Reply-To: <777142.46671.qm@web43513.mail.sp1.yahoo.com> References: <777142.46671.qm@web43513.mail.sp1.yahoo.com> Message-ID: On Thu, May 5, 2011 at 2:19 AM, Kyle Benak wrote: > I am learning python and I am trying to write a simple "guess the number" > game.?I wrote the program in the IDLE, and?I set the variable tries=1 to > keep up with the number of tries it takes to guess the number, but when I > try to run the program it gives the error message "improper syntax" and > highlights the word tries.? So, I assigned the variable tries the value 1 in > the python shell window and it works fine there.? Can you tell me why it > won't work in the program? A copy of my code is below for clarification. If the parser tells you there's a syntax error, it is often in the line it shows, but also often in the line preceding that. In this case, it is the latter: You have two opening brackets there, but only one closing bracket. -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Thu May 5 10:03:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 May 2011 09:03:30 +0100 Subject: [Tutor] assigning a variable a value References: <777142.46671.qm@web43513.mail.sp1.yahoo.com> Message-ID: "Kyle Benak" wrote > I am learning python and I am trying to write a simple "guess the > number" > game. I wrote the program in the IDLE, and I set the variable > tries=1 to keep up > with the number of tries it takes to guess the number, but when I > try to run the > program it gives the error message "improper syntax" and highlights > the word > tries. First please post the actual error in full, not just a rough summary. Pythopn error messages are very informative and helpful once you know how to read them. However, in this case its not needed. The thing to remember with errors, especially syntax errors, is that Python reports them where it identifies the problem. But that may be a line or so later than where the actual error occurs. That is what happened here. Look at the guess= line and count the parentheses.... num = random.randint(1,100) guess = int(input('Take a guess: ') tries = 1 > print('Too low. Guess higher.') > guess=input('Take another guess: ') you probably need to convert to int() here too... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 5 10:13:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 May 2011 09:13:11 +0100 Subject: [Tutor] Titles from a web page References: Message-ID: "louis leichtnam" wrote > I'm trying to write a program that looks in a webpage in find the > titles of > a subsection of the page: > > Can you help me out? I tried using regular expression but I keep > hitting > walls and I don't know what to do... Regular expressions are the wrong tool for parsing HTML unless you are searching for something very simple. There is an html parser in the Python standard library (*) that you can use if the HTML is reasonably well formed. If its sloppy you would be better with something like BeautifulSoup or lxml. If the page is written in XHTML then you could also use the element tree module which is designed for XML parsing. (*)In fact there are two! - htmllib and HTMLParser. The former is more powerful but more complex. Some brief examples can be found in my tutor here: http://www.alan-g.me.uk/tutor/tutwebc.htm Note, the topic is not complete, the last few sections are placeholders only... HTH, Alan G. From matt.gregory at oregonstate.edu Thu May 5 18:49:31 2011 From: matt.gregory at oregonstate.edu (Matt Gregory) Date: Thu, 05 May 2011 09:49:31 -0700 Subject: [Tutor] Need help with arrays In-Reply-To: References: Message-ID: On 5/4/2011 10:30 AM, Patrick P. wrote: > Hello, > > I hope this is the right way to ask my question, if not, sorry to bother > you. Maybe you can tell me who to ask. > Ok so here is my code > > [snip] > > A = np.array([[m111,m121], [m211,m221]]) > B = np.array([[m112,m122], [m212,m222]]) > print(np.dot(A,B)) > > Traceback (most recent call last): > File "C:/Python26/helpfiletest.py", line 36, in > print(np.dot(A,B)) > ValueError: objects are not aligned > ------------------------------------------------------------------------------------- > I get it why theres and error message, because it's trying to multiply a > 2x2x100 array with another 2x2x100 array and doesn't know how to do that. > What I actually want is 100 2x2 arrays and then mutliply them individually. > Can anyone help me with that? As Alan said, you'll likely get good help on the numpy listserv, but I think this might be what you want, although I'm not sure it's the tersest way to express it: # Swap axes twice on A and B to make them (100, 2, 2) A_new = np.swapaxes(np.swapaxes(A, 0, 2), 1, 2) B_new = np.swapaxes(np.swapaxes(B, 0, 2), 1, 2) # Multiply the 2x2 arrays together using list comprehension C = np.array([np.dot(a, b) for a, b in zip(A_new, B_new)]) print C I'm certain there is a more clever way (ie. some function within numpy) to do that last part. matt From bgailer at gmail.com Thu May 5 22:08:15 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 05 May 2011 16:08:15 -0400 Subject: [Tutor] Reading elements in a file In-Reply-To: References: <0490F53EC69042DE9318585574B5125A@GREGPC> <22D249B9E041654AA140F32C0E6F942753D53465B6@EXVMBX018-3.exch018.msoutlookonline.net> Message-ID: <4DC303AF.6020605@gmail.com> On 5/4/2011 6:59 PM, Alan Gauld wrote: > > The string methods are builtin and the string > module is really only needed for backwatds > compatibility these days. Yes, except for: 8.1.5. String functions The following functions are available to operate on string and Unicode objects. They are not available as string methods. string.capwords(s[, sep]) string.maketrans(from, to) -- Bob Gailer 919-636-4239 Chapel Hill NC From ramit.prasad at jpmchase.com Thu May 5 22:43:56 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 5 May 2011 16:43:56 -0400 Subject: [Tutor] Reading elements in a file In-Reply-To: <4DC303AF.6020605@gmail.com> References: <0490F53EC69042DE9318585574B5125A@GREGPC> <22D249B9E041654AA140F32C0E6F942753D53465B6@EXVMBX018-3.exch018.msoutlookonline.net> <4DC303AF.6020605@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA37F5AC3@EMARC112VS01.exchad.jpmchase.net> > string.capwords(s[, sep]) So capwords is a little bit different but you can use a combination of split() and title() to do some of it. Title() will work for the default case, but if you split on non-whitespace then you will need to manually use split(). 'test test test'.title() 'Test Test Test' This is the only one I think you cannot do from the str object. (Well, not in Python2. Python3 has maketrans built into the str object.). >string.maketrans(from, to) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From l.leichtnam at gmail.com Fri May 6 03:56:16 2011 From: l.leichtnam at gmail.com (louis leichtnam) Date: Thu, 5 May 2011 21:56:16 -0400 Subject: [Tutor] dictionary Message-ID: HEllo everyone, I have a dictionnary, and I would like to print only the values that have more/equal than 3 spaces in them for example: My name is Xavier. Can you help me out, Thanks Louis -------------- next part -------------- An HTML attachment was scrubbed... URL: From naheedcse at gmail.com Fri May 6 04:45:06 2011 From: naheedcse at gmail.com (naheed arafat) Date: Fri, 6 May 2011 08:45:06 +0600 Subject: [Tutor] dictionary In-Reply-To: References: Message-ID: Supposing your dictionary like this: dict={1:'My name is X',2:'My name is x y z',3: 'i am X'} You can use len(list) : >>> dict={1:'My name is X',2:'My name is x y z',3: 'i am X'} >>> for values in dict.values(): ... if len(values.split(' '))>3: ... print values My name is X My name is x y z On Fri, May 6, 2011 at 7:56 AM, louis leichtnam wrote: > HEllo everyone, > > I have a dictionnary, and I would like to print only the values that have > more/equal than 3 spaces in them for example: My name is Xavier. > > Can you help me out, > > Thanks > > Louis > > _______________________________________________ > 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 Fri May 6 05:05:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 06 May 2011 13:05:51 +1000 Subject: [Tutor] dictionary In-Reply-To: References: Message-ID: <4DC3658F.8010705@pearwood.info> louis leichtnam wrote: > HEllo everyone, > > I have a dictionnary, and I would like to print only the values that have > more/equal than 3 spaces in them for example: My name is Xavier. d = {1: "Hello world", 2: "My name is Xavier", 3: "ham and eggs", 4: "Eat more cheese please!", 5: "spam spam spam spam spam spam", 6: "how much wood would a woodchuck chuck if a woodchuck would" " chuck wood?", 7: "nice cup of tea and a slice of cake"} for value in d.values(): if value.count(" ") >= 3: print(value) -- Steven From susana.delgado_s at utzmg.edu.mx Fri May 6 16:29:57 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Fri, 6 May 2011 09:29:57 -0500 Subject: [Tutor] Unpack requires a string argument of length 8 In-Reply-To: References: Message-ID: Hello Marc and Jim! First of all, thanks to both of you! I already changed the code, I added the try statement and the script runned without ponting to an error. But now, I have another problem, even though, it doesn't show an error message and makes the txt files, the files don't have any lines written. Before I added the try/catch lines, it showed the error, made the files and writted them. I really need those txt files. What did I do wrong? import os,fnmatch from osgeo import ogr,gdal,osr from dbf import * gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk( "C:\\" ): for filename in fnmatch.filter(files, '*.shp'): file_list.append(os.path.join(root, filename)) for row, filepath in enumerate(file_list, start=1): (ruta, filename) = os.path.split(filepath) shapeData = ogr.Open(filepath) if shapeData is None: print 'Error al abrir el archivo' +filepath else: n = os.path.splitext(filepath) f = os.path.splitext(filename) b = f[0]+'_bd.txt' d = n[0]+'.dbf' if os.path.lexists(d): filepath1 = "C:\\Python26\\dbf\\" a = open (filepath1 +b,"w+") try: Dbf(d,new=False, readOnly=True) for fldName in dbf.fieldDefs: a.write(fldName.name) a.write(" || ") a.write(fldName.typeCode) a.write("\n") dbf.close() a.close() print n except: print 'El archivo ' +filepath+ ' esta vacio' else: print "El archivo " +n[0]+".shp" " no tiene dbf" print "Listo" -------------- next part -------------- An HTML attachment was scrubbed... URL: From pwnedomina at gmail.com Fri May 6 18:28:23 2011 From: pwnedomina at gmail.com (pwnedomina) Date: Fri, 06 May 2011 16:28:23 +0000 Subject: [Tutor] password cipher Message-ID: <4DC421A7.1020106@gmail.com> hi. i wonder if its possible to generate cipher a tabula recta in python like the one show here http://lifehacker.com/?_escaped_fragment_=5715794/how-to-write-down-and-encrypt-your-passwords-with-an-old+school-tabula-recta#!5715794/how-to-write-down-and-encrypt-your-passwords-with-an-old+school-tabula-recta , i need to generate a chart like this image sheet its possible to this using a python code? -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: medium_img_0945_01.jpg Type: image/jpeg Size: 40908 bytes Desc: not available URL: From alan.gauld at btinternet.com Fri May 6 19:10:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 May 2011 18:10:35 +0100 Subject: [Tutor] password cipher References: <4DC421A7.1020106@gmail.com> Message-ID: "pwnedomina" wrote > hi. i wonder if its possible to generate cipher a tabula recta in > python > like the one show here > http://lifehacker.com/?_escaped_fragment_=5715794/how-to-write-down-and-encrypt-your-passwords-with-an-old+school-tabula-recta#!5715794/how-to-write-down-and-encrypt-your-passwords-with-an-old+school-tabula-recta > , i need to generate a chart like this image sheet > its possible to this using a python code? Yes it's very possible. All you need are some print statements with suitable formatting. Or you could create an HTML file with a table... What is your problem exactly? What bit do you not understand? Can you write Python code already? Or are you a complete beginner? Do you know how to produce the table by hand - using pen and paper say? Is this a homework assignment? Or do you have a specific use for this? (There may be other, simpler, ways to do what you want.) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri May 6 19:20:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 May 2011 18:20:23 +0100 Subject: [Tutor] Unpack requires a string argument of length 8 References: Message-ID: "Susana Iraiis Delgado Rodriguez" wrote > I already changed the code, I added the try statement and the script > runned > without ponting to an error. So to be clear. You run the script and it does NOT print 'El archivo ' +filepath+ ' esta vacio' But your file could still be empty since > if os.path.lexists(d): > filepath1 = "C:\\Python26\\dbf\\" > a = open (filepath1 +b,"w+") > try: > Dbf(d,new=False, readOnly=True) > for fldName in dbf.fieldDefs: Have you tried printing dbf.fieldDefs? If that is empty then the following code will not run. try/except is not a magic cure-all. It needs something to trigger the exception, if you try to itertate over an empty list that won't do it. > a.write(fldName.name) > a.write(" || ") > a.write(fldName.typeCode) > a.write("\n") > dbf.close() > a.close() > print n > except: > print 'El archivo ' +filepath+ ' esta vacio' You should probably change the except to catch specific errors rather than be a catch-all, but I'm not sure which errors you might catch. That depends on the Dbf class design. > else: > print "El archivo " +n[0]+".shp" " no tiene dbf" > print "Listo" HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From pwnedomina at gmail.com Fri May 6 23:10:52 2011 From: pwnedomina at gmail.com (pwnedomina) Date: Fri, 06 May 2011 21:10:52 +0000 Subject: [Tutor] password cipher In-Reply-To: References: <4DC421A7.1020106@gmail.com> Message-ID: <4DC463DC.4010602@gmail.com> Em 06-05-2011 17:10, Alan Gauld escreveu: > > "pwnedomina" wrote > >> hi. i wonder if its possible to generate cipher a tabula recta in python >> like the one show here >> http://lifehacker.com/?_escaped_fragment_=5715794/how-to-write-down-and-encrypt-your-passwords-with-an-old+school-tabula-recta#!5715794/how-to-write-down-and-encrypt-your-passwords-with-an-old+school-tabula-recta >> >> , i need to generate a chart like this image sheet >> its possible to this using a python code? > > Yes it's very possible. All you need are some print statements > with suitable formatting. Or you could create an HTML file with > a table... > > What is your problem exactly? What bit do you not understand? > > Can you write Python code already? Or are you a complete beginner? > Do you know how to produce the table by hand > - using pen and paper say? > > Is this a homework assignment? > Or do you have a specific use for this? > (There may be other, simpler, ways to do what you want.) > > HTH, > > im a beginner, can you show a sample of code in order to do this task? From alan.gauld at btinternet.com Sat May 7 00:59:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 May 2011 23:59:31 +0100 Subject: [Tutor] password cipher References: <4DC421A7.1020106@gmail.com> <4DC463DC.4010602@gmail.com> Message-ID: "pwnedomina" wrote >> Can you write Python code already? Or are you a complete beginner? >> Do you know how to produce the table by hand >> - using pen and paper say? >> >> > im a beginner, can you show a sample of code in order to do this > task? I could but it may not mean anything to you. Can you write code to print a table of any kind? For example can you print out a multiplication table, say the 3 times table, like this: 1 x 3 = 3 2 x 3 = 6 3 x 3 = 9 4 x 3 = 12 5 x 3 = 15 If you can do that then it is very little extra work to print out the encoding table provided you know the contents. So can you do that initial step of printing the 3 times table? Show us your code. That will give us an idea of where your understanding and skill level lies. PS. There is code in my tutorial for printing multiplication tables if you are really stuck. Try the end of the "more sequences" topic for a start... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From pwnedomina at gmail.com Sat May 7 02:20:35 2011 From: pwnedomina at gmail.com (pwnedomina) Date: Sat, 07 May 2011 00:20:35 +0000 Subject: [Tutor] password cipher In-Reply-To: References: <4DC421A7.1020106@gmail.com> <4DC463DC.4010602@gmail.com> Message-ID: <4DC49053.2010806@gmail.com> Em 06-05-2011 22:59, Alan Gauld escreveu: > > "pwnedomina" wrote > >>> Can you write Python code already? Or are you a complete beginner? >>> Do you know how to produce the table by hand >>> - using pen and paper say? >>> >>> >> im a beginner, can you show a sample of code in order to do this task? > > I could but it may not mean anything to you. > Can you write code to print a table of any kind? > For example can you print out a multiplication table, > say the 3 times table, like this: > > 1 x 3 = 3 > 2 x 3 = 6 > 3 x 3 = 9 > 4 x 3 = 12 > 5 x 3 = 15 > > If you can do that then it is very little extra work to print out the > encoding table provided you know the contents. So can you > do that initial step of printing the 3 times table? > > Show us your code. That will give us an idea of where your > understanding and skill level lies. > > PS. There is code in my tutorial for printing multiplication > tables if you are really stuck. Try the end of the > "more sequences" topic for a start... > > HTH, > i have no code to show this is why im asking for samples in order to do this.. From alan.gauld at btinternet.com Sat May 7 02:29:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 May 2011 01:29:00 +0100 Subject: [Tutor] password cipher References: <4DC421A7.1020106@gmail.com> <4DC463DC.4010602@gmail.com> <4DC49053.2010806@gmail.com> Message-ID: "pwnedomina" wrote >> Can you write code to print a table of any kind? >> For example can you print out a multiplication table, >> say the 3 times table, like this: >> >> 1 x 3 = 3 >> 2 x 3 = 6 >> ... >> Show us your code. That will give us an idea of where your >> understanding and skill level lies. >> >> PS. There is code in my tutorial for printing multiplication >> > i have no code to show this is why im asking for samples in order to > do this.. We are here to help you learn to program not to write programs for you. You can only learn to program by writing code. So, as I suggested, try writing code to print out the 3 times table. Post it here and we can discuss how to go forward. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From pwnedomina at gmail.com Sat May 7 03:40:05 2011 From: pwnedomina at gmail.com (pwnedomina) Date: Sat, 07 May 2011 01:40:05 +0000 Subject: [Tutor] password cipher In-Reply-To: References: <4DC421A7.1020106@gmail.com> <4DC463DC.4010602@gmail.com> <4DC49053.2010806@gmail.com> Message-ID: <4DC4A2F5.70300@gmail.com> Em 07-05-2011 00:29, Alan Gauld escreveu: > "pwnedomina" wrote > >>> Can you write code to print a table of any kind? >>> For example can you print out a multiplication table, >>> say the 3 times table, like this: >>> >>> 1 x 3 = 3 >>> 2 x 3 = 6 >>> ... >>> Show us your code. That will give us an idea of where your >>> understanding and skill level lies. >>> >>> PS. There is code in my tutorial for printing multiplication >>> >> i have no code to show this is why im asking for samples in order to >> do this.. > > We are here to help you learn to program not to write > programs for you. You can only learn to program by > writing code. So, as I suggested, try writing code to > print out the 3 times table. Post it here and we can > discuss how to go forward. > okay, thanks for the help anyway. From brownam at gmail.com Sat May 7 05:35:15 2011 From: brownam at gmail.com (Aaron Brown) Date: Fri, 6 May 2011 23:35:15 -0400 Subject: [Tutor] Need some help Message-ID: Here is the code I have, and the error.I don't understand the TUPLE problem. Can someone explain. #Main Program def main(): notGreenCost = (12,float) goneGreenCost = (12, float) savings = (12, float) months = "January ","February","March ","April ","May ","June ","July ","August ","September ","October ","November ","December " for index in range(12): print "Enter NOT GREEN energy costs for ", months[index] notGreenCost[index]=raw_input("Enter now-> ") for index in range(12): print "Enter GONE GREEN energy costs for ", months[index] goneGreenCost[index]=input("Enter now-> ") print "--------------------------------------- " print "SAVINGS NOT GREEN GONE GREEN MONTH" print "--------------------------------------- " for index in range(12): savings[index] = notGreenCost(index) - goneGreenCost[index] print "$", savings[index] print "$ ", notGreenCost[index] print "$", goneGreenCost[index] print months[index] main() Enter NOT GREEN energy costs for January Enter now-> 0 Traceback (most recent call last): File "C:\Users\USER\Desktop\P08.py", line 24, in main() File "C:\Users\USER\Desktop\P08.py", line 11, in main notGreenCost[index]=raw_input("Enter now-> ") TypeError: 'tuple' object does not support item assignment >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat May 7 10:08:31 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 07 May 2011 18:08:31 +1000 Subject: [Tutor] Need some help In-Reply-To: References: Message-ID: <4DC4FDFF.50907@pearwood.info> Aaron Brown wrote: > Here is the code I have, and the error.I don't understand the TUPLE problem. > Can someone explain. The error you get is: TypeError: 'tuple' object does not support item assignment This tells you that tuples are immutable (fixed) objects. You cannot do this: >>> t = (1, 2, 3) >>> t[1] = 42 # Change the item in place. Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment Instead, you can recreate the tuple as needed, using slicing: >>> t = (1, 2, 3) >>> t = t[0:1] + (42,) + t[2:] # note the comma in the middle term >>> t (1, 42, 3) or you can use lists instead: >>> t = [1, 2, 3] >>> t[1] = 42 >>> t [1, 42, 3] -- Steven From lina.lastname at gmail.com Sat May 7 11:17:36 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 7 May 2011 17:17:36 +0800 Subject: [Tutor] how to read data Message-ID: Hi, As you will see I am a new beginner of learning python, I met a problem, hope someone can guide me one or two and help me learn. Here is the issue. "e c #3B3B3B " /* "1.15" */, "f c #343434 " /* "1.19" */, "g c #2E2E2E " /* "1.23" */, "h c #272727 " /* "1.27" */, "i c #212121 " /* "1.31" */, "j c #1A1A1A " /* "1.35" */, "k c #141414 " /* "1.38" */, "l c #0D0D0D " /* "1.42" */, "m c #070707 " /* "1.46" */, "n c #000000 " /* "1.5" */, from below we can see the e = 1.15 .... n = 1.5.. "nnnnnnnnnneZVKWcbglnnnnnnnnADKSYjknnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnnnnlcdZTQSLGJMMDAnnnnncngbGKMHPTFJSWSZfhcejnnneSZdiilnnggnnkgnnnnnnjnnn", "nnnnnnnnnnnmmjeaVRPLHGMJDADnnnnnlnnnUadTcfPNaeVbjkdcglnnnhnnnnnnnnnnnnlnnnnnnmnnn", "nnnnnnnnnimfhfZURQLEJJKDADMnnnnnnnnncglcmnTXknYknniginnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnndiggfYTSOIHKGDADJMnnnnnjnmlZaicljPWiiShnjedfjnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnkmhebQSQJFLKDADKMJnnnnhXiZYRMYYeYFVecPdjeaeijnnhfZnnnnnnnnnnnnnnnnnnnnnn", and for above I want those a-Z get back to their numerical value, so I can use this matrix and read by matlab. Thanks ahead for any advice about how to achieve it. I have attached the whole file. try.xpm at the end and as attachment. Best regards, lina /* XPM */ /* Generated on May 5th */ /* This is the file*/ /* title: "None" */ /* legend: "Distance (nm)" */ /* x-label: "Residue Index" */ /* y-label: "Residue Index" */ /* type: "Continuous" */ static char *gromacs_xpm[] = { "81 81 40 1", "A c #FFFFFF " /* "0" */, "B c #F8F8F8 " /* "0.0385" */, "C c #F2F2F2 " /* "0.0769" */, "D c #EBEBEB " /* "0.115" */, "E c #E5E5E5 " /* "0.154" */, "F c #DEDEDE " /* "0.192" */, "G c #D8D8D8 " /* "0.231" */, "H c #D1D1D1 " /* "0.269" */, "I c #CBCBCB " /* "0.308" */, "J c #C4C4C4 " /* "0.346" */, "K c #BEBEBE " /* "0.385" */, "L c #B7B7B7 " /* "0.423" */, "M c #B1B1B1 " /* "0.462" */, "N c #AAAAAA " /* "0.5" */, "O c #A3A3A3 " /* "0.538" */, "P c #9D9D9D " /* "0.577" */, "Q c #969696 " /* "0.615" */, "R c #909090 " /* "0.654" */, "S c #898989 " /* "0.692" */, "T c #838383 " /* "0.731" */, "U c #7C7C7C " /* "0.769" */, "V c #767676 " /* "0.808" */, "W c #6F6F6F " /* "0.846" */, "X c #696969 " /* "0.885" */, "Y c #626262 " /* "0.923" */, "Z c #5C5C5C " /* "0.962" */, "a c #555555 " /* "1" */, "b c #4E4E4E " /* "1.04" */, "c c #484848 " /* "1.08" */, "d c #414141 " /* "1.12" */, "e c #3B3B3B " /* "1.15" */, "f c #343434 " /* "1.19" */, "g c #2E2E2E " /* "1.23" */, "h c #272727 " /* "1.27" */, "i c #212121 " /* "1.31" */, "j c #1A1A1A " /* "1.35" */, "k c #141414 " /* "1.38" */, "l c #0D0D0D " /* "1.42" */, "m c #070707 " /* "1.46" */, "n c #000000 " /* "1.5" */, /* x-axis: 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 */ /* x-axis: 81 */ /* y-axis: 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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 */ /* y-axis: 81 */ "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnigebUSQNFHLOVUnnnnnnnnnnhfilgPdhWXMMNPGDA", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnkkfZWWQJJLKFJJnnnnnnnnnnnjknkXcgXUOTTNDAD", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnjcebVPSQHHMQOQUnnnnnnnnmkeabeaPVYPPLOLDADG", "nnnnnnnnnnnnnnnnnnnnnnnnnmjnnnnnnnnnnnicWaXQKQRJLSVUUannnnnnnkebWTSTQIKOHKGKDADNP", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmjbcdZQSWRKSYadjnnnnnnnfeZSUUUNGPRGLJDADLTN", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmnnjadeXPZeeeinnnnnnnnnibeccVQTRGFDADKOTM", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnlnmfZdcSSXbYWbnnnnnnnnnmhhdcZRRSJDADJGLOM", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnmnnhaihXZfhcSZnnnnnnnnngdfZWSNMHDADFLKPUX", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnngkmgVagXXdigeknnnnnnngcTRXQMGFHDADJGGHPXW", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnlehmfUbkbdknmknnnnnnnniZSTVMGHIDADHSRROYgh", "nnnnnnnnnnnnnnnnnnnnnnnnnlgnnnnnnnnnnmdXRWaTLTZSVdfdclnnnnmflcTONNFHIDADHMRTPKVcd", "nnnnnnnnnnnnnnnnnnnnnnnnnnknnnnnnnnnnjebTUWUKJSRGRXcfmnnnnjggWRKGKJJDADIFNRQGIPXP", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnkiXcihUVjeZknnnnnnnnndgTNFHMIDADIHGSZVNQakg", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnfcRXecSVhffmnnnnnnnkjXeVKINMDADJHGMWccUTenl", "nnnnnnnnnnnnnnnnnnnnnnnnnngnnnnnnnnnhgWVJRXXNNcaahmmnnnnnabMXOFHIDADIJFMQZdcUSbki", "nnnnnnnnnnnnnnnnnnnnnnnnnngnnnnnnnnmgcVWJNUUKIWXVchknnnnndVQRJHIDADMMKNVXfheUTajf", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnggTYeeTOgfYinnnnnnnlgVVKIDADINHGNTRdhbSWenh", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnndfPYfhWUkjgnnnnnnnngeRTMDADIHIFKOSTgmiZbknn", "nnnnnnnnnnnnnnnnnnnnnnnnnnlnnnnnnnnnjhXaKTaeVShignnnnnnnnbXLMDADIHFKNRTZcnnneemnn", "nnnnnnnnnnnnnnnnnnnnnnnnnninnnnnnnngbcSYGQXdaShlfnnnnnnkeVPIDADMKJOVTWcignnnfknnn", "nnnnnnnnnnnnnnnnnnnnnnnnnninnnnnlkgbXZSZNPYgfXjnknnnnnndYPLDADMTVRXegglnnnnnnnnnn", "nnnnnnnnnnnnnnnnnnnnnhnnnndnnnnndgbVPTLTIMWddaknnnnnnnfVPGDADILRVQMXdgfnnnnnnnnnn", "nnnnnnnnnnnnnnennlennZZnnnZnnnmcSMGHHKIRNGRZbaflmnnnnnbSIDADLPXegVbjnjmnnnnnnnnnn", "nnnnnnnnnnnnnninnhlnkTfnnhSnnnkfTZVPGPKKRPXbfilnnnnnnnSJDADGPVbgldaknnnnnnnnnnnnn", "nnnnnnnnnnnnnngnnjnnnahnnnennmcXNOPJGQQZdUdlnnnnnnnnnnLDADIPYennnnnnnnnnnnnnnnnnn", "nnnnnnnnnnnnnnlnnnnnnknnnnnnnmaZSXXSQbajlennnnnnnnnnnnDADJSVdknnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnkYWRXZXXijnnnnnnnnnnnnnnnADLSbfnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnnnnnnnnnnnnnjjnlnnnnnnnnnnnnnnnnjegeQUXSIJDAnnnnnnnnnnnnnnnmlnkZbijaUJU", "nnnnnnnnnnnnnnnnnnnnnnifigjnnnnnnnnnnnnlileWYaONSUMDADnnnnnnnnnnnnnnnfckeSWedUQJV", "nnnnnnnnnnnnnnnnnnnnnkedgcennnnnnnnnnnnhegYSUTJKOMDADJnnnnnnnnnnnkmnncdmgcYeaUOFO", "nnnnnnnnnnnnnnnnnninniaeidcnnnnnnnnnngkfcaURSMFKJDADMInnnnnnnnnnnhmnnXfnihbeYVQKL", "nnnnnnnnnnnnnnnnnninnnejnkhnnnnnnnnnndheZWSRNHGJDADMUSnnnnnnnnnnichmkRdkdfXZSSMLH", "nnnnnnnnnnnnnnnnnnnnnnjnnjfnnnnnnnnnngeaUURNHIIDADJOSXnnnnmnkfggYVafZGVdXZSPKLHJF", "nnnnnnnnnnnnnnnnnnnnnhdhkbZnnnnnnnnnkeaVRSMGIJDADJKKNUnnnnlnnlijfXafeRSbXXSXRJHJN", "nnnnnnnnnnnnnnnnniZdfXPSYVSnnnnnnnljeWURNLFIJDADIGFJOQnnnlfkjhhkgWchjSZkghceWRQQQ", "nnnnnnnnnnnnnnnnnnnnngcineWnnnnnnnigfVROIIIIDADJIHMTaennniaaXSSUOINVVJTbaiddSQSWS", "nnnnnnnnnnnnnnnnnnnnndeikaSnnnnnnnnkcXPKFKIDADJIHNSUYgnnnfbdfaVWTKNSUKLUVaZaQKPWU", "nnnnnnnnnnnnnnnnniefbVVWXNJnnnnnnnlfUQLFJKDADIIGNRRSWennlbZdgdeheUXchUTfghfjZQVZb", "nnnnnnnnnnnnlhUaZQPURGFPTPFnnnnjXkZVKKFIIDADIIFMRSUYejnndXRWYXafeUXeiWammnmndXbfe", "nnnnnnnnnnnnnnknnmlnnZYjnfTnnnnnaeVPMKHKDADKKILSUWaglnneUPGMPQTYYNRXcUWhknnncaekg", "nnnnnnnnnnnnnnnnnnnnlYelmcPnnnnnmnleRQIDADIJFINRUZceinnldRNINGKPTJJRXTRegmlmbWcki", "nnnnnnnnnnnnnnhniadgYLYccTHnnnnnenfZHKDADKIFKORVaefhlnnjZKRTZYafgWVcibXlnnnnjcjnn", "nnnnnnnnnnnnnnhnnhiniSYildMnnnnmYgWPHDADIHFLPRUaehknnnjaQKILSSXdgVWfkednnnnnminnn", "nnnnnnnnnnnnnlXhiaVddMMagaKnnnlcPZOJDADKQKKQXVWegdgnnnibQPKTZchnncgnnjmnnnnnnnnnn", "nnnnnnnnnnnnnfTfbTWbWERZcUGnnkfXKTKDADHHRMKUcfeknnnnnnXQGGHPXbjnnghnnnnnnnnnnnnnn", "nnnnnnnnnnnnnnZnnfdmmVYlnnbnnmfVKJDADJPZePVfkgjnnnnnnnXSJPHVbgnnnmnnnnnnnnnnnnnnn", "nnnnnnnnnnnnjiWkmdalnXZmnngnneZOIDADKOWflVZlnilnnnnnnnZXPVGbgnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnnngdXineennginnnnkiVTJDADJTZgnneknnnnnnnnnnnXXOZMgknnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnnngbPdeTXfgSXjnlcjdVMDADIKKPYemaXnnnnnnnnnnnRSNTSdlnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnnnbSSdgXcknehnnnnYUKDADJOVXcmnnnjnnnnnnnnnnnWZXfcnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnnlcQUdeYfmnknnnnnSJDADMTZfflnnnnnnnnnnnnnnnnYackmnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnjeWIRZbYdknnnnnnnKDADKVVemknnnnnnnnnnnnnnnnnkmmnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnkdYLWdZdjnnnnnnnnDADJUdinnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnneZVKWcbglnnnnnnnnADKSYjknnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnnnnnlcdZTQSLGJMMDAnnnnncngbGKMHPTFJSWSZfhcejnnneSZdiilnnggnnkgnnnnnnjnnn", "nnnnnnnnnnnmmjeaVRPLHGMJDADnnnnnlnnnUadTcfPNaeVbjkdcglnnnhnnnnnnnnnnnnlnnnnnnmnnn", "nnnnnnnnnimfhfZURQLEJJKDADMnnnnnnnnncglcmnTXknYknniginnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnndiggfYTSOIHKGDADJMnnnnnjnmlZaicljPWiiShnjedfjnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnkmhebQSQJFLKDADKMJnnnnhXiZYRMYYeYFVecPdjeaeijnnhfZnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnkldbWRPLEGJDADGJGGnnnkeSgXVEMSLYZGVdgXhnniknnnkaTZhnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnefWWUQKFJIDADKKJHLnnnnngnnmWdiYlnRbnnfnnnnnnnnnnknnnnnnnnnnnnnnnnnnnnnnn", "nnnnnhnnmVZTSSLFIJDADJLHELSnnkmkfnlmbdngnnUfnndnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnmnnnWZXRNFIIDADIGFILPQljdfcXeadWVidnlPennZnniinnnnnnlennnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnnecUOIHJDADJJEJOQRTgdYYXTedfTahanmQinninnnnnnnnnjhlnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnjXUKGIIDADIIFLQSRVZbZbegenmnbininnZnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnfZecMMMHJDADJIFKPSTUadcdZdddiknfhnnnnannnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnnnnmZWRHDADIHFLQRQYZecWWRUSPXWZTXhhnkUnnnnnnnnnnnnlgiennnnnnnnnnnnnnnnnnnnnn", "nnnnnnnniaUMDADJIINSUWbffjlKLIQSbdinflnnnnhnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnnnjheZQKDADHHGORSWbeghmnVYWcbggjnnnnnnnlnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnlnabXRKDADMRMKUXTWdhgfmnZdelnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnihUSOJDADKUWMUcZZflmimnnekjnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnmYWKJIDADKQaZMXeWVekkdinnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nnnVbMJDADJRZimcjnnmnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "nniUVLDADIOXennennnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "njbPMDADJJSbhnnZnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "gYQGDADLMKUajnnfnnmhnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "VQHDADMVbWhnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "TKDADGPUVYilnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "LDADHQbinmnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "DADKQYjnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn", "ADLTVgnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn" -------------- next part -------------- A non-text attachment was scrubbed... Name: try.xpm Type: image/x-xpixmap Size: 8878 bytes Desc: not available URL: From alan.gauld at btinternet.com Sat May 7 14:05:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 May 2011 13:05:33 +0100 Subject: [Tutor] Need some help References: Message-ID: "Aaron Brown" wrote > Here is the code I have, and the error. Actually you have a lot of errors! > I don't understand the TUPLE problem. As Steven pointed out you cannot assign to a tuple once it has vbeen created. You can only create a new tuple. If you want to change the collection use a list instead. > def main(): > notGreenCost = (12,float) > goneGreenCost = (12, float) > savings = (12, float) I'm not sure why you have the float there. That is a reference to the "function" used for converting values to floating point. But you never use it.... Are you coming from some other language where you dimension an array and tell it the type or something? That doesn't work (or even mean anything) in Python since collections can hold any type and can grow dynamically. > months = "January ","February","March ","April ","May ","June > ","July > ","August ","September ","October ","November ","December " > for index in range(12): > print "Enter NOT GREEN energy costs for ", months[index] > notGreenCost[index]=raw_input("Enter now-> ") Even if you used a list this would store a string in the list and would only work for the first two elements since you cannot assign to an index that doesn't exist. You probably want to use the append method of a list: notGreenCost = [] # an empty list .... for index in range(len(months)): print "Enter NOT GREEN energy costs for ", months[index] notGreenCost.append( float(raw_input("Enter now-> ")) ) > for index in range(12): This loops around 12 times for each month in the loop above. Is that really what you want? Surely this should just be part of the same outer loop? > print "Enter GONE GREEN energy costs for ", months[index] > goneGreenCost[index]=input("Enter now-> ") And this has all the same issues as the notGreenCost assignment above. > print "--------------------------------------- " > print "SAVINGS NOT GREEN GONE GREEN MONTH" > print "--------------------------------------- " Again, I don't think this is where you want this > for index in range(12): And this will loop for every item in the inner loop. In other wortds this will get executed 12*12*12 times - a total of 1728 times! > savings[index] = notGreenCost(index) - > goneGreenCost[index] As it stands this tries to subtract two strings. Thats why you should convert the raw_uinput values to floats. > print "$ ", savings[index] > print "$", notGreenCost[index] > print "$ ", goneGreenCost[index] > print months[index] This will print something like $20$ 50 30 March Is that really the output format you want? I would have thought adding at least an explanatory label would be nice? HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dlwdan002 at uct.ac.za Sat May 7 14:01:19 2011 From: dlwdan002 at uct.ac.za (dlwdan002 at uct.ac.za) Date: Sat, 7 May 2011 12:01:19 +0000 Subject: [Tutor] How to extract a value from a matrix. Message-ID: <1470317542-1304769567-cardhu_decombobulator_blackberry.rim.net-1935287834-@b14.c17.bise7.blackberry> Hi there I am a student and is new to python. I would like to know how to exact a value from a list that has been opened from a text file in python. Thanks Danielle Sent from my BlackBerry? wireless device From waynejwerner at gmail.com Sat May 7 14:17:07 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 7 May 2011 07:17:07 -0500 Subject: [Tutor] how to read data In-Reply-To: References: Message-ID: 2011/5/7 lina > Hi, > > As you will see I am a new beginner of learning python, > > I met a problem, hope someone can guide me one or two and help me learn. > Have you tried anything yet? Do you know how to read in from a file? Can you go over it line by line? There are several tutorials available, such as Alan Gauld's wonderful tutorial: http://www.alan-g.me.uk/ or the Python Beginner's Guide has a list of tutorials for both non-programmers and those with previous experience: http://wiki.python.org/moin/BeginnersGuide Take a look at those and pay special attention to: 1. File I/0 2. Dictionaries 3. The string.replace method http://docs.python.org/library/string.html#string.replace 4. String slicing If I understand what you're asking, you want the large cluster of text at the end to, instead of having lots of 'n's, have the number after the hash, correct? i.e. n is #000000, which is 0 in base 10, and the first non-zero value on that line is #212121 (or 2171169 decimal) so you want something like this: 0 0 0 0 0 0 0 0 0 0 ... 0 0 2171169 ... correct? If so, for something like this I would probably make two files, one containing the first part ('A c #FFFFFF ...') and another containing the matrix at the end. The steps I would follow are: 1. Open the "translation" file 2. For each line in the file a. Get the character on the line b. Get the numeric value the character refers to c. Store these values in a way that allows me to use the character to retrieve the number 3. close the translation file (not strictly necessary, since Python does this for you when the script finishes, but good practice) 4. open the matrix file and an output file 5. for each line in the matrix a. for each character in my translation i. replace the characters in the line with the numeric value followed by a space ( so instead of 0000 you have 0 0 0 0 ) b. write the line to the output file 6. close the matrix file and the output file (if you don't close the output file, there may be no data in it!) 7. Go to matlab and do whatever you wanted to. Since you sound like you're familiar with matlab, just remember that in Python, arrays start with 0, not 1. If you get stuck at any of these points, come back and let us know 1. What you tried 2. What you thought should happen 3. What really happened 4. If an error occurred, the full text of any messages you got. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat May 7 15:04:17 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 7 May 2011 21:04:17 +0800 Subject: [Tutor] how to read data In-Reply-To: References: Message-ID: Thanks so much for your detailful information. I spent sometime in learning before. On Sat, May 7, 2011 at 8:17 PM, Wayne Werner wrote: > 2011/5/7 lina >> >> Hi, >> >> As you will see I am a new beginner of learning python, >> >> I met a problem, hope someone can guide me one or two and help me learn. >> > > Have you tried anything yet? Do you know how to read in from a file? Can you I only know the basic about how to read a file and print it out. ## python recolor.py filename from sys import argv script, filename = argv txt = open(filename) print txt.read() > go over it line by line? There are several tutorials available, such as Alan > Gauld's wonderful tutorial:?http://www.alan-g.me.uk/?or the Python > Beginner's Guide has a list of tutorials for both non-programmers and those > with previous experience:?http://wiki.python.org/moin/BeginnersGuide > Take a look at those and pay special attention to: > 1. File I/0 > 2. Dictionaries > 3. The string.replace > method?http://docs.python.org/library/string.html#string.replace > 4. String slicing > If I understand what you're asking, you want the large cluster of text at > the end to, instead of having lots of 'n's, have the number after the hash, > correct? i.e. n is #000000, which is 0 in base 10, and the first non-zero those #000000 are color, I want to recolor them, (so I thought it might work in matlab (if I provided the matrix). > value on that line is #212121 (or 2171169 decimal) so you want something > like this: > 0 0 0 0 0 0 0 0 0 0 ... 0 0?2171169 ... > correct? > If so, for something like this I would probably make two files, one > containing the first part ('A c #FFFFFF ...') and another containing the > matrix at the end. The steps I would follow are: > 1. Open the "translation" file > 2. For each line in the file > ? ? a. Get the character on the line > ? ? b. Get the numeric value the character refers to > ? ? c. Store these values in a way that allows me to use the character to > retrieve the number > 3. close the translation file (not strictly necessary, since Python does > this for you when the script finishes, but good practice) > 4. open the matrix file and an output file > 5. for each line in the matrix > ? ? a. for each character in my translation > ? ? ? ? i. replace the characters in the line with the numeric value > followed by a space ( so instead of 0000 you have 0 0 0 0 ) > ? ? b. write the line to the output file > 6. close the matrix file and the output file (if you don't close the output > file, there may be no data in it!) > 7. Go to matlab and do whatever you wanted to. > Since you sound like you're familiar with matlab, just remember that in > Python, arrays start with 0, not 1. > > If you get stuck at any of these points, come back and let us know > 1. What you tried > 2. What you thought should happen > 3. What really happened > 4. If an error occurred, the full text of any messages you got. > HTH, > Wayne Thanks again for the programming process. I will try. -- Best Regards, lina From kushal.kumaran+python at gmail.com Sat May 7 18:15:20 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sat, 7 May 2011 21:45:20 +0530 Subject: [Tutor] ValueError In-Reply-To: References: <4DBFE047.8060605@aim.com> <5B123049-D6CD-488A-866B-F79F740AF39E@me.com> Message-ID: On Wed, May 4, 2011 at 3:13 PM, Peter Otten <__peter__ at web.de> wrote: > Kushal Kumaran wrote: > >> On Tue, May 3, 2011 at 5:31 PM, Peter Otten <__peter__ at web.de> wrote: >>> >>> >>> Also you should make the try...except as narrow as possible >>> >>> try: >>> centimeters = float(centimeters) >>> except ValueError as e: >>> print e >>> >>> is likely to catch the float conversion while with many statements in the >>> try-suite you are more likely to hide a problem that is unrelated to that >>> conversion. >>> >> >> I would have expected it to be the other way. ?If you cannot >> reasonable expect to continue after an exception, then the try block >> should extend all the way across the block of code you want to skip. >> In your snippet, what if some code later is relying on the >> 'centimeters' variable having a useful float value? ?IMO, >> encapsulating small bits of code in try ... except blocks really makes >> code written using exceptions look ugly. > > Instead of repeating what Alan said I'll give you a side-by-side example: > > Thanks Peter. That was an interesting example. -- regards, kushal From bgailer at gmail.com Sat May 7 20:03:55 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 07 May 2011 14:03:55 -0400 Subject: [Tutor] How to extract a value from a matrix. In-Reply-To: <1470317542-1304769567-cardhu_decombobulator_blackberry.rim.net-1935287834-@b14.c17.bise7.blackberry> References: <1470317542-1304769567-cardhu_decombobulator_blackberry.rim.net-1935287834-@b14.c17.bise7.blackberry> Message-ID: <4DC5898B.1050809@gmail.com> On 5/7/2011 8:01 AM, dlwdan002 at uct.ac.za wrote: > Hi there Hi > I am a student and is new to python. Welcome > I would like to know how to exact a value from a list that has been opened from a text file in python. Your question is much too vague to give any meaningful answer. Exactly what does "list that has been opened from a text file" mean? Is the source of the list important (e.g. does it matter whether it comes from a file)? Please provide an example. What does the list look like? How do you determine which element you want? Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Sun May 8 02:50:53 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 08 May 2011 10:50:53 +1000 Subject: [Tutor] How to extract a value from a matrix. In-Reply-To: <1470317542-1304769567-cardhu_decombobulator_blackberry.rim.net-1935287834-@b14.c17.bise7.blackberry> References: <1470317542-1304769567-cardhu_decombobulator_blackberry.rim.net-1935287834-@b14.c17.bise7.blackberry> Message-ID: <4DC5E8ED.1070805@pearwood.info> dlwdan002 at uct.ac.za wrote: > Hi there > > I am a student and is new to python. I would like to know how to exact a value from a list that has been opened from a text file in python. Exactly the same way that you would get a value from any other list. >>> my_list = [10, 20, 30, 40, 50] >>> print my_list[2] # get a value from the list 30 Don't forget that Python starts counting from 0, not 1. Does this answer your question? If not, you will need to be more specific about what you are trying to do. -- Steven From mammar at gmail.com Sun May 8 21:49:27 2011 From: mammar at gmail.com (mammar) Date: Mon, 9 May 2011 00:49:27 +0500 Subject: [Tutor] python ctypes dll issue Message-ID: Hi All, I have created a DLL with the following function exported in it int myFunction(char *id, char *name); Below is the python code to load the dll and call myFunction from ctypes import * # Load DLL into memory mydll= windll.LoadLibrary("my.dll") id = create_string_buffer("030725002") name = create_string_buffer("mammar") print mydll.myFunction(id, name) But when i run the above code i am getting error dialog box with following info Debug Assertion Failed! Program: C:\Python27\pythonw.exe file: fread.c line: 93 Expression: (buffer != NULL) Whats the problem? Any idea? Regards. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon May 9 02:04:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 May 2011 01:04:21 +0100 Subject: [Tutor] python ctypes dll issue References: Message-ID: "mammar" wrote > > I have created a DLL with the following function exported in it > > int myFunction(char *id, char *name); > This is a bit beyond beginner python, I suspect you will get a better response if you ask on the ctypes mailling list/forum. > Below is the python code to load the dll and call myFunction > > from ctypes import * > # Load DLL into memory > mydll= windll.LoadLibrary("my.dll") > id = create_string_buffer("030725002") > name = create_string_buffer("mammar") > print mydll.myFunction(id, name) > > Program: C:\Python27\pythonw.exe > file: fread.c > line: 93 > > Expression: (buffer != NULL) Looks like a problem in the C code but I don't know if thats the C in Python or the C in your DLL. I suspect we would need to see the C in the DLL function. You could add some print statements to find out where the error arises... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bugcy013 at gmail.com Mon May 9 15:04:12 2011 From: bugcy013 at gmail.com (Ganesh Kumar) Date: Mon, 9 May 2011 18:34:12 +0530 Subject: [Tutor] How to compile source code in debian Message-ID: Hi Gurus, I want compile ubuntu software centre source code from debian how to compile...please help me.. I downloaded all file contents have python file .. https://launchpad.net/ubuntu/maverick/+source/software-center/3.0.4 Advance thanks.. Ganesh -- Did I learn something today? If not, I wasted it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon May 9 15:30:49 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 9 May 2011 14:30:49 +0100 Subject: [Tutor] How to compile source code in debian In-Reply-To: References: Message-ID: Hello, On 9 May 2011 14:04, Ganesh Kumar wrote: > Hi Gurus, > > I want compile ubuntu software centre source code from debian how to > compile...please help me.. > I downloaded all file contents have python file .. > > https://launchpad.net/ubuntu/maverick/+source/software-center/3.0.4 > > Python is not a compiled language (in the traditional sense.) So you can go ahead and edit the python sources directly, run the app etc, and/or run the setup.py file as normal to install the application system wide. (E.g. "python setup.py install" etc. If that doesn't make sense then I'd say you need to become more familiar with the Python "lay of the lands". Actually offhand I'm not sure how this will interact with/affect the default software-center installed on Ubuntu, but suffice it to say once you've built up enough familiarity with Python and Ubuntu you'll be able to answer such uncertainties easily yourself by doing a few experiments... ) See how you go, and if you're still stuck post back and we'll try to help. But be specific please, say what you've tried, what you expected, and what you actually got. Post the full text of any error messages you get. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Mon May 9 17:19:00 2011 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 9 May 2011 08:19:00 -0700 Subject: [Tutor] python ctypes dll issue References: Message-ID: "mammar" wrote in message news:BANLkTin90dmfRkBu5O=dZ-p36fp3NL_Uww at mail.gmail.com... > Hi All, > > > I have created a DLL with the following function exported in it > > int myFunction(char *id, char *name); > > > Below is the python code to load the dll and call myFunction > > > from ctypes import * > > # Load DLL into memory > mydll= windll.LoadLibrary("my.dll") > > id = create_string_buffer("030725002") > name = create_string_buffer("mammar") > > print mydll.myFunction(id, name) > > > > But when i run the above code i am getting error dialog box with following > info > > Debug Assertion Failed! > > Program: C:\Python27\pythonw.exe > file: fread.c > line: 93 > > Expression: (buffer != NULL) > > > Whats the problem? Any idea? "windll" requires the function called to be __stdcall calling convention. The default is normally __cdecl. Try "cdll" instead. -Mark From matthew_rezaei at hotmail.com Tue May 10 00:42:52 2011 From: matthew_rezaei at hotmail.com (Matthew Rezaei) Date: Tue, 10 May 2011 08:42:52 +1000 Subject: [Tutor] Python assignment Message-ID: Hi There, I am hoping you can help me! I have a python assignment and I need help regarding it, is there anyone that can help me out with it? Regards Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue May 10 01:25:57 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 10 May 2011 00:25:57 +0100 Subject: [Tutor] Python assignment In-Reply-To: References: Message-ID: Hello Matthew, On 9 May 2011 23:42, Matthew Rezaei wrote: > Hi There, > > > > I am hoping you can help me! > > > > I have a python assignment and I need help regarding it, is there anyone > that can help me out with it? > Yes. We won't do the assignment for you, but if you try to solve it and get stuck then we'll try to provide hints to get you unstuck. Remember to include full error messages and actual source code if you get stuck. Don't paraphrase code, don't shorten error messages. Don't make assumptions about what is wrong and then send us input based on those assumptions. Do send as much information as possible. Remember to "Reply-all" to ensure responses do go to the list as well. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Tue May 10 01:27:06 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Mon, 9 May 2011 19:27:06 -0400 Subject: [Tutor] Python assignment In-Reply-To: References: Message-ID: On Mon, May 9, 2011 at 6:42 PM, Matthew Rezaei wrote: > I have a python assignment and I need help regarding it, is there anyone > that can? help me out with it? The answer you will inevitably get is something like: Hi, we're happy to help you understand the problems you're encountering as you work on your assignment. In order to help with that: * Tell us the specific problem you are trying to solve * Show us the code that is giving you a problem (succinct!), including a cut-and-paste of the exact error message you get (if it's an error as opposed to unexpected results) * Give a clear question to answer. If you haven't gotten this from someone else, then consider this that response :) -- Brett Ritter / SwiftOne swiftone at swiftone.org From jamani.sana at hotmail.com Tue May 10 06:27:20 2011 From: jamani.sana at hotmail.com (Clara Mintz) Date: Mon, 9 May 2011 23:27:20 -0500 Subject: [Tutor] Dictionary File character reader Message-ID: Sorry I am completely new at python and don't understand why this function is returning an empty dictionary. I want it to take a list of files open them then return the number of characters as the value and the file name as the key. def fileLengths(files): d = {} files = [] for file in files: reader = open(file) for line in reader: char = sum(len(line)) d[file] = char reader.close return d Thank you sorry I don't understand what I am doing wrong. -Clara -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Tue May 10 08:38:56 2011 From: enalicho at gmail.com (Noah Hall) Date: Tue, 10 May 2011 07:38:56 +0100 Subject: [Tutor] Dictionary File character reader In-Reply-To: References: Message-ID: On Tue, May 10, 2011 at 5:27 AM, Clara Mintz wrote: > Sorry I am completely new at python and don't understand why this function > is returning an empty dictionary. I want it to take a list of files open > them then return the number of characters as the value and the file name as > the key. > def fileLengths(files): > ?? ?d = {} > ?? ?files = [] Here's why. You take the name "files" and assign it to an empty list, so you lose the "files" that you sent to the function. >>> files = ["file_1.txt", "file_2.doc"] >>> files ['file_1.txt', 'file_2.doc'] >>> files = [] >>> files [] You don't need that line at all, so remove it, and see what happens. :) > ?? ?for file in files: > ?? ? ? ?reader = open(file) > ?? ? ? ?for line in reader: > ?? ? ? ? ? ?char = sum(len(line)) As a side not, this doesn't need to be "sum" in this case - the len is simply len, throwing away what it previously was. In fact, this probably isn't what you want. At any one point, char is the length of a single line, not the sum of every length of every line in the file. What you want is something that takes the length of each line, and add it to the sum. A simple way would be to do >>>sum(len(line) for line in file) > ?? ? ? ?d[file] = char > ?? ? ? ?reader.close > ?? ?return d > Thank you sorry I don't understand what I am doing wrong. > -Clara > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Hope this helped. From alan.gauld at btinternet.com Tue May 10 10:15:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 May 2011 09:15:37 +0100 Subject: [Tutor] Dictionary File character reader References: Message-ID: "Noah Hall" wrote > What you want is something that takes the length of each line, > and add it to the sum. A simple way would be to do >>>sum(len(line) for line in file) And if you just want the total count for the file an even simpler way is to use file.read() count = len(file.read()) One other thing to consider is whether you want to include line feed characters in the count... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Tue May 10 11:55:31 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 10 May 2011 05:55:31 -0400 Subject: [Tutor] Dictionary File character reader In-Reply-To: References: Message-ID: <4DC90B93.1070405@ieee.org> On 01/-10/-28163 02:59 PM, Clara Mintz wrote: > > Sorry I am completely new at python and don't understand why this function is returning an empty dictionary. I want it to take a list of files open them then return the number of characters as the value and the file name as the key. > def fileLengths(files): d = {} files = [] for file in files: reader = open(file) for line in reader: char = sum(len(line)) d[file] = char reader.close return d > Thank you sorry I don't understand what I am doing wrong. > -Clara The first thing you're doing is wordwrapping your program fragment. It makes the code hard to read, and some aspects impossible, as we can't tell what parts were indented by how much. The second thing is clobbering your input parameter. files=[] will obliterate whatever argument was passed to that function. You will have more problems after that: sum() won't work on an integer, so it's not clear why you're calling len() on the line. You're returning d from the function, but nothing in the function ever inserts anything into it. So it will clearly be empty. print is your friend. A couple of carefully placed print statements would reveal these problems. DaveA From s.charonis at gmail.com Tue May 10 14:16:04 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Tue, 10 May 2011 13:16:04 +0100 Subject: [Tutor] Printing output from Python program to HTML Message-ID: Hello everyone, I have a Python script that extracts some text from a database file and annotates another file, writing the results to a new file. Because the files I am annotating are ASCII, I am very restricted as to how I can annotate the text, and I would like to instead write the results to HTML so that I can annotate my file in more visually effective ways,e.g. by changing text color where appropriate. My program extracts text from a database, reads a file that is to be annotated, and writes those annotations to a newly created (.htm) file I include the following headers at the beginning of my program: print "Content-type:text/html\r\n\r\n" print '' print '' The part of the program that finds the entry I want and produces the annotation is about 80 lines down and goes as follow: file_rmode = open('/myfolder/alignfiles/query1, 'r') file_amode = open('/myfolder/alignfiles/query2, 'a+') file1 = motif_file.readlines() # file has been created in code not shown file2 = file_rmode.readlines() for line in seqalign: for item in finalmotifs: item = item.strip().upper() if item in line: newline = line.replace(item, " item ") # compiler complains here about the word "red" # sys.stdout.write(newline) align_file_amode.write(line) print '' print '' motif_file.close() align_file_rmode.close() align_file_amode.close() The Python compiler complains on the line I try to change the font color, saying "invalid syntax". Perhaps I need to import the cgi module to make this a full CGI program? (I have configured my Apache server). Or alternatively, my HTML code is messed up, but I am pretty sure this is more or less a simple task. I am working in Python 2.6.5. Many thanks in advance Spyros -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy at enkelthed.dk Tue May 10 14:17:40 2011 From: tommy at enkelthed.dk (Tommy Bell) Date: Tue, 10 May 2011 14:17:40 +0200 Subject: [Tutor] folder and file list In-Reply-To: References: Message-ID: <4DC92CE4.4010702@enkelthed.dk> Hey, quite new at python and I have been trying to make a script that will list folders and files, but so far its not working import os, glob def scandir(path): direc = [] file = [] for current in glob.glob(os.path.join(path,'*')): if os.path.isdir(current): direc.append(current) #append to direc list scandir(current) if os.path.isfile(current): #should test if current is a file, but it doesnt, because current is a path file.append(current) #append to file list for i in file: print i for j in direc: print j scandir('c:\tmp') this doesnt work, I know why - but i dont know how to fix it. The reason it doesnt work is because isfile requires a file, but current contains a path. The objective is to get it to append files to the file list, later i wish to figure out how to make it print like so folder: file1 file2 folder2 folder2.1 file1 file2 etc. Any ideas? I dont mind reading if i could justbe pointed in the right direction Regards Tommy From swiftone at swiftone.org Tue May 10 14:31:55 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Tue, 10 May 2011 08:31:55 -0400 Subject: [Tutor] Printing output from Python program to HTML In-Reply-To: References: Message-ID: On Tue, May 10, 2011 at 8:16 AM, Spyros Charonis wrote: > ? ? ? ? ? newline = line.replace(item, " item ... > The Python compiler complains on the line I try to change the font color, > saying "invalid syntax". Your issue here is not importing libraries, but your quotations. When you get to "red", it takes that first double quote as ENDING the string of HTML that starts with " . It doesn't know that you're putting quotes inside your string, as the only way it knows when a string ends is when it reaches the quoting character that matches the beginning. The easiest solution is to use 'red' (using single quotes) as HTML accepts both. newline = line.replace(item, " item ") As alternative you could use a different quoting for your string (note the single quotes on the outside): newline = line.replace(item, ' item ') Alternatively you could escape your string. This tells Python that the quotes are NOT ending the string, and the backslashes will not appear in the resulting output: newline = line.replace(item, " item ") Note that the first option works because HTML accepts single or double quotes for it's attribute values. The second option works because single and double quotes for strings work the saem in Python (this is not true of all languages). The third option is pretty standard across languages, but can be annoying because it becomes harder to cut-and-paste strings to/from other places (for example, template files, raw HTML files, etc). Hope that helps! -- Brett Ritter / SwiftOne swiftone at swiftone.org From steve at pearwood.info Tue May 10 14:31:53 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 10 May 2011 22:31:53 +1000 Subject: [Tutor] Printing output from Python program to HTML In-Reply-To: References: Message-ID: <4DC93039.9020105@pearwood.info> Spyros Charonis wrote: > newline = line.replace(item, " item > ") # compiler complains here about the word "red" You should pay attention when Python tells you where there is an error. If it says there is a syntax error, then your syntax is invalid and you need to fix it. > The Python compiler complains on the line I try to change the font color, > saying "invalid syntax". Perhaps I > need to import the cgi module to make this a full CGI program? And how will that fix your syntax error? The offending line of code looks like this: newline = line.replace(item, " item> ") split into two lines because my mail program doesn't like long lines. The important part is the replacement string: " item> " Only it's not a string, the syntax is broken. Each quote " starts and then stops a string: OPEN QUOTE ... END QUOTE red OPEN QUOTE ... CLOSE QUOTE This is invalid syntax. You can't have the word red sitting outside of a string like that. How to fix it? There are two ways. You can escape the inner quotes like this: " item> " That will stop Python using the escaped quotes \" as string delimiters, and use them as ordinary characters instead. Or, you can take advantage of the fact that Python has two different string delimiters, double and single quotes, and you can safely nest each inside the other: ' item> ' -- Steven From l.leichtnam at gmail.com Tue May 10 14:41:24 2011 From: l.leichtnam at gmail.com (louis leichtnam) Date: Tue, 10 May 2011 08:41:24 -0400 Subject: [Tutor] Graphic interface Message-ID: Hello, I'm trying to build a graphic interface, with button, radiobutton, enter text area etc. Does anyone have an idea or a source code for this? Thank you, Louis -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Tue May 10 14:45:07 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Tue, 10 May 2011 08:45:07 -0400 Subject: [Tutor] folder and file list In-Reply-To: <4DC92CE4.4010702@enkelthed.dk> References: <4DC92CE4.4010702@enkelthed.dk> Message-ID: On Tue, May 10, 2011 at 8:17 AM, Tommy Bell wrote: > scandir('c:\tmp') > this doesnt work, I know why - but i dont know how to fix it. > The reason it doesnt work is because isfile requires a file, but current contains a path. Not quite. Stick a "print path" as the first line in scandir. Notice that it doesn't print out c:\tmp The issue is that Windows (Well, DOS, back in the day) decided to use backslashes as the path separator, where the rest of the world (mostly) used slashes. This meant that most programming languages use backslashes to "escape" characters to have special meaning. Putting "\n" in a string puts in not an "n" but a newline character. \t is a tab. This causes you (and many other windows programmers) a little bit of distress today, in many programming languages. To have your string recognize that your backslash is an actual real backslash you can escape it: scandir('c:\\tmp') After that your code should work fine (it runs on my system, but I'm not on windows). This filepath issue has many details you can look up or ask about, but this should get you started. -- Brett Ritter / SwiftOne swiftone at swiftone.org From swiftone at swiftone.org Tue May 10 15:21:53 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Tue, 10 May 2011 09:21:53 -0400 Subject: [Tutor] Graphic interface In-Reply-To: References: Message-ID: On Tue, May 10, 2011 at 8:41 AM, louis leichtnam wrote: > I'm trying to build a graphic interface, with button, radiobutton, enter > text area etc. > Does anyone have an idea or a source code for this? Assuming that you're talking about a desktop application rather than a web-based application, I'd start by googling TkInter and going from there. There are alternatives, but that's well-supported and widely used. -- Brett Ritter / SwiftOne swiftone at swiftone.org From ranceh at gmail.com Tue May 10 15:24:18 2011 From: ranceh at gmail.com (Rance Hall) Date: Tue, 10 May 2011 08:24:18 -0500 Subject: [Tutor] Graphic interface In-Reply-To: References: Message-ID: On Tue, May 10, 2011 at 7:41 AM, louis leichtnam wrote: > Hello, > I'm trying to build a graphic interface, with button, radiobutton, enter > text area etc. > Does anyone have an idea or a source code for this? > Thank you, > Louis How you do this exactly depends on a number of things you don't specify. When you jump into the world of graphical programming there is such a thing as a window manager. GTK, QT, KDE, TK, and Windows all have different ways of addressing these same issues. Python even has its own builtin thing called Tkinter that uses the TK widget set (the widgets are the buttons, sliderbars, etc) You can use Tkinter, or you can bind python to the GTK or KDE widget set and ask python to create those widgets and explain how to arrange them on the screen and the window manager will handle the heavy lifting for you. Source code won't help you if you don't understand the above and limitations/options available in the widget set you have chosen. Most of the code samples are Object Oriented. If you are not familiar with coding objects then you will likely find the code samples rather daunting -- I know I did. I think I'd recommend that you start with Tkinter since it is cross platform compatible that way it doesn't matter what OS you use your code will still work. May I suggest that you go read about TK and Tkinter and decide if they are appropriate for your project. Then you can ask a specific question that can be answered. HTH Rance From s.charonis at gmail.com Tue May 10 17:48:47 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Tue, 10 May 2011 16:48:47 +0100 Subject: [Tutor] Printing output from Python program to HTML In-Reply-To: References: Message-ID: Thanks, very simple but I missed that because it was supposed be in HTML code! On Tue, May 10, 2011 at 1:16 PM, Spyros Charonis wrote: > Hello everyone, > > I have a Python script that extracts some text from a database file and > annotates another file, > writing the results to a new file. Because the files I am annotating are > ASCII, > I am very restricted as to how I can annotate the text, and I would like to > instead > write the results to HTML so that I can annotate my file in more visually > effective ways,e.g. by changing text color > where appropriate. My program extracts text from a database, reads a file > that is to be annotated, and writes those > annotations to a newly created (.htm) file > I include the following headers at the beginning of my program: > > print "Content-type:text/html\r\n\r\n" > print '' > print '' > > The part of the program that finds the entry I want and produces the > annotation is about > 80 lines down and goes as follow: > > file_rmode = open('/myfolder/alignfiles/query1, 'r') > file_amode = open('/myfolder/alignfiles/query2, 'a+') > > file1 = motif_file.readlines() # file has been created in code not shown > file2 = file_rmode.readlines() > > for line in seqalign: > for item in finalmotifs: > item = item.strip().upper() > if item in line: > newline = line.replace(item, " item > ") # compiler complains here about the word "red" > # sys.stdout.write(newline) > align_file_amode.write(line) > > print '' > print '' > > motif_file.close() > align_file_rmode.close() > align_file_amode.close() > > The Python compiler complains on the line I try to change the font color, > saying "invalid syntax". Perhaps I > need to import the cgi module to make this a full CGI program? (I have > configured my Apache server). Or alternatively, my HTML code is messed up, > but I > am pretty sure this is more or less a simple task. > > I am working in Python 2.6.5. Many thanks in advance > > Spyros > -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.charonis at gmail.com Tue May 10 18:11:08 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Tue, 10 May 2011 17:11:08 +0100 Subject: [Tutor] Problem with printing Python output to HTML Correctly Message-ID: Hello, I know I posted the exact same topic a few hours ago and I do apologize for this, but my script had a careless error, and my real issue is somewhat different. I have a Python script that extracts some text from a database file and annotates another file, writing the results to a new file. Because the files I am annotating are ASCII, I am very restricted as to how I can annotate the text, and I would like to instead write the results to HTML so that I can annotate my file in more visually effective ways,e.g. by changing text color where appropriate. My program extracts text from a database, reads a file that is to be annotated, and writes those annotations to a newly created (.htm) file. finalmotifs = motif_file.readlines() seqalign = align_file_rmode.readlines() # These two files have been created in code that I don't show here because it is not relevant to the issue align_file_appmode.write('') align_file_appmode.write('') align_file_appmode.write (' \'query_\' Multiple Sequence Alignment ') align_file_appmode.write('') align_file_appmode.write('') for line in seqalign: align_file_appmode.write(' \'line\' ') for item in finalmotifs: item = item.strip().upper() if item in line: newline = line.replace (item, ' \'item\' ') align_file_appmode.write(newline) align_file_appmode.write('') align_file_appmode.write('') motif_file.close() align_file_rmode.close() align_file_appmode.close() The .htm file that is created is not what I intend it to be, it has the word "item" printed every couple lines because I assume I'm not passing the string sequence that I want to output correctly. QUESTION Basically, HTML (or the way I wrote my code) does not understand that with the escape character '\item\' I am trying to print a string and not the word "item". Is there someway to correct that or would I have to use something like XML to create a markup system that specifically describes my data? I am aware Python supports multiline strings (using the format ''' text ''') but I do want my HTML ( or XML?) to be correctly rendered before I consider making this into a CGI program. Built in python 2.6.5 -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.charonis at gmail.com Tue May 10 19:14:52 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Tue, 10 May 2011 18:14:52 +0100 Subject: [Tutor] Problem with printing Python output to HTML Correctly In-Reply-To: References: Message-ID: Hi all, No need to post answers, I figured out where my mistake was. Spyros On Tue, May 10, 2011 at 5:11 PM, Spyros Charonis wrote: > Hello, > > I know I posted the exact same topic a few hours ago and I do apologize for > this, but my script had a careless error, and my real issue is somewhat > different. > I have a Python script that extracts some text from a database file and > annotates another file, writing the results to a new file. Because the > files I am annotating are ASCII, > I am very restricted as to how I can annotate the text, and I would like to > instead write the results to HTML so that I can annotate my file in more > visually effective ways,e.g. by changing text color where appropriate. My > program extracts text from a database, reads a file that is to be annotated, > and writes those > annotations to a newly created (.htm) file. > > finalmotifs = motif_file.readlines() > seqalign = align_file_rmode.readlines() > > # These two files have been created in code that I don't show here because > it is not relevant to the issue > > align_file_appmode.write('') > align_file_appmode.write('') > > align_file_appmode.write > (' > \'query_\' Multiple Sequence Alignment > ') > > align_file_appmode.write('') > align_file_appmode.write('') > > for line in seqalign: > align_file_appmode.write(' \'line\' ') > for item in finalmotifs: > item = item.strip().upper() > if item in line: > > newline = line.replace > (item, ' \'item\' ') > > align_file_appmode.write(newline) > > align_file_appmode.write('') > align_file_appmode.write('') > > motif_file.close() > align_file_rmode.close() > align_file_appmode.close() > > The .htm file that is created is not what I intend it to be, it has the > word "item" > printed every couple lines because I assume I'm not passing the string > sequence that I want to output correctly. > > QUESTION > Basically, HTML (or the way I wrote my code) does not understand that with > the > escape character '\item\' I am trying to print a string and not the word > "item". > Is there someway to correct that or would I have to use > something like XML to create a markup system that specifically describes my > data? > > I am aware Python supports multiline strings (using the format ''' text > ''') but I do want my HTML ( or XML?) > to be correctly rendered before I consider making this into a CGI program. > Built in python 2.6.5 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue May 10 19:37:17 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 10 May 2011 19:37:17 +0200 Subject: [Tutor] Problem with printing Python output to HTML Correctly In-Reply-To: References: Message-ID: Spyros Charonis, 10.05.2011 19:14: > On Tue, May 10, 2011 at 5:11 PM, Spyros Charonis wrote: >> I know I posted the exact same topic a few hours ago and I do apologize for >> this, but my script had a careless error, and my real issue is somewhat >> different. I would have preferred an update to the initial thread instead of a complete repost. A single thread makes it easier for others to read up on the answers when they find the thread through a web search later on. Duplicate information requires additional effort to find out what is relevant and what is not. > No need to post answers, I figured out where my mistake was. Given that you received answers that helped you, it would only be fair to write a quick follow-up to let others know where the problem was and how you solved it, in case they encounter a similar problem one day. Stefan From s.charonis at gmail.com Tue May 10 20:06:14 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Tue, 10 May 2011 19:06:14 +0100 Subject: [Tutor] Problem with printing Python output to HTML Correctly In-Reply-To: References: Message-ID: A SOLUTION TO THE PROBLEM I POSTED: align_file_rmode = open('/Users/spyros/folder1/python/printsmotifs/alignfiles/' + query1, 'r') align_file_appmode = open('/Users/spyros/folder1/python/printsmotifs/alignfiles/' + query2, 'a+') finalmotifs = motif_file.readlines() seqalign = align_file_rmode.readlines() for line in seqalign: #align_file_appmode.write(' \'line\' ') for item in finalmotifs: item = item.strip().upper() annotation = ""+item+"" if item in line: newline = line.replace(item, annotation) # sys.stdout.write(newline) align_file_appmode.write(newline) motif_file.close() align_file_rmode.close() align_file_appmode.close() the line annotation = ""+item+"" added a span and set the color in CSS. On Tue, May 10, 2011 at 6:14 PM, Spyros Charonis wrote: > Hi all, > > No need to post answers, I figured out where my mistake was. > > Spyros > > > On Tue, May 10, 2011 at 5:11 PM, Spyros Charonis wrote: > >> Hello, >> >> I know I posted the exact same topic a few hours ago and I do apologize >> for this, but my script had a careless error, and my real issue is somewhat >> different. >> I have a Python script that extracts some text from a database file and >> annotates another file, writing the results to a new file. Because the >> files I am annotating are ASCII, >> I am very restricted as to how I can annotate the text, and I would like >> to instead write the results to HTML so that I can annotate my file in more >> visually effective ways,e.g. by changing text color where appropriate. My >> program extracts text from a database, reads a file that is to be annotated, >> and writes those >> annotations to a newly created (.htm) file. >> >> finalmotifs = motif_file.readlines() >> seqalign = align_file_rmode.readlines() >> >> # These two files have been created in code that I don't show here because >> it is not relevant to the issue >> >> align_file_appmode.write('') >> align_file_appmode.write('') >> >> align_file_appmode.write >> (' >> \'query_\' Multiple Sequence Alignment >> ') >> >> align_file_appmode.write('') >> align_file_appmode.write('') >> >> for line in seqalign: >> align_file_appmode.write(' \'line\' ') >> for item in finalmotifs: >> item = item.strip().upper() >> if item in line: >> >> newline = line.replace >> (item, ' \'item\' ') >> >> align_file_appmode.write(newline) >> >> align_file_appmode.write('') >> align_file_appmode.write('') >> >> motif_file.close() >> align_file_rmode.close() >> align_file_appmode.close() >> >> The .htm file that is created is not what I intend it to be, it has the >> word "item" >> printed every couple lines because I assume I'm not passing the string >> sequence that I want to output correctly. >> >> QUESTION >> Basically, HTML (or the way I wrote my code) does not understand that with >> the >> escape character '\item\' I am trying to print a string and not the word >> "item". >> Is there someway to correct that or would I have to use >> something like XML to create a markup system that specifically describes >> my data? >> >> I am aware Python supports multiline strings (using the format ''' text >> ''') but I do want my HTML ( or XML?) >> to be correctly rendered before I consider making this into a CGI program. >> Built in python 2.6.5 >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 10 20:43:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 May 2011 19:43:21 +0100 Subject: [Tutor] Graphic interface References: Message-ID: "louis leichtnam" wrote > I'm trying to build a graphic interface, with button, radiobutton, > enter > text area etc. > > Does anyone have an idea or a source code for this? You could start with the GUI topic in my tutor and then progress to one of the more detailed tutorials on the web... And as always write lots of code! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jorgeromero178 at gmail.com Wed May 11 00:08:27 2011 From: jorgeromero178 at gmail.com (Jorge Romero) Date: Tue, 10 May 2011 18:08:27 -0400 Subject: [Tutor] folder and file list In-Reply-To: References: <4DC92CE4.4010702@enkelthed.dk> Message-ID: Is there any special reason for deploying that functionality from scratch by yourself? Can't you use os bulit-in module? Perhaps you can find this useful http://docs.python.org/library/os.html#os.listdir. That way you don't deal with OS peculiarities such as the one Brett Ritter pointed. On Tue, May 10, 2011 at 8:45 AM, Brett Ritter wrote: > On Tue, May 10, 2011 at 8:17 AM, Tommy Bell wrote: > > scandir('c:\tmp') > > > this doesnt work, I know why - but i dont know how to fix it. > > The reason it doesnt work is because isfile requires a file, but current > contains a path. > > Not quite. Stick a "print path" as the first line in scandir. > > Notice that it doesn't print out c:\tmp > > The issue is that Windows (Well, DOS, back in the day) decided to use > backslashes as the path separator, where the rest of the world > (mostly) used slashes. This meant that most programming languages use > backslashes to "escape" characters to have special meaning. Putting > "\n" in a string puts in not an "n" but a newline character. \t is a > tab. This causes you (and many other windows programmers) a little > bit of distress today, in many programming languages. > > To have your string recognize that your backslash is an actual real > backslash you can escape it: > scandir('c:\\tmp') > > After that your code should work fine (it runs on my system, but I'm > not on windows). > > This filepath issue has many details you can look up or ask about, but > this should get you started. > > -- > 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 > -- Jorge Romero -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Wed May 11 00:42:11 2011 From: robert.sjoblom at gmail.com (=?utf-8?Q?Robert_Sj=C3=B6blom?=) Date: Wed, 11 May 2011 00:42:11 +0200 Subject: [Tutor] folder and file list (Jorge Romero) In-Reply-To: References: Message-ID: <913E9840-2687-403F-BD8C-A40A72E0F369@gmail.com> >> >> >> >> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >>> >> >> >> > Can't you use os bulit-in module? > > Perhaps you can find this useful > http://docs.python.org/library/os.html#os.listdir. That way you don't deal > with OS peculiarities such as the one Brett Ritter pointed. > > On Tue, May 10, 2011 at 8:45 AM, Brett Ritter wrote: > >> On Tue, May 10, 2011 at 8:17 AM, Tommy Bell wrote: >>> scandir('c:\tmp') >> >>> this doesnt work, I know why - but i dont know how to fix it. >>> The reason it doesnt work is because isfile requires a file, but current >> contains a path. >> >> Not quite. Stick a "print path" as the first line in scandir. >> >> Notice that it doesn't print out c:\tmp >> >> The issue is that Windows (Well, DOS, back in the day) decided to use >> backslashes as the path separator, where the rest of the world >> (mostly) used slashes. This meant that most programming languages use >> backslashes to "escape" characters to have special meaning. Putting >> "\n" in a string puts in not an "n" but a newline character. \t is a >> tab. This causes you (and many other windows programmers) a little >> bit of distress today, in many programming languages. >> >> To have your string recognize that your backslash is an actual real >> backslash you can escape it: >> scandir('c:\\tmp') >> >> After that your code should work fine (it runs on my system, but I'm >> not on windows). >> >> This filepath issue has many details you can look up or ask about, but >> this should get you started. >> >> -- >> 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 >> > > > > -- > Jorge Romero > -------------- next part -------------- Actually, I have had no problems using forward slashes (ie, "C:/User/Data/etc" being a valid path) at all. There's also os.path.normpath() if you feel that there's a need to convert forward slashes to backward slashes, or the raw string literal, r (r"C:\User\Data\etc"). Sorry for not snipping much of the message, smartphone is a bit clunky for that, to say theleast. Best regards, Robert S From lan.rogers.book at gmail.com Wed May 11 01:57:57 2011 From: lan.rogers.book at gmail.com (Lan Rogers) Date: Tue, 10 May 2011 16:57:57 -0700 Subject: [Tutor] Programmatically Post to Pastebin Message-ID: I realize this may not be entirely within the domain of a python mailing list, but I'm having trouble finding anything helpful elsewhere. I want to post files stored on a machine to Pastebin (or any similar service for that matter) using a python script, and then store a link to that post. Also, I would strongly prefer to avoid doing something that requires an API key. Sorry if this isn't really the right place to ask about this, if that's the case can someone show me a more appropriate forum? From prologic at shortcircuit.net.au Wed May 11 02:08:54 2011 From: prologic at shortcircuit.net.au (James Mills) Date: Wed, 11 May 2011 10:08:54 +1000 Subject: [Tutor] Programmatically Post to Pastebin In-Reply-To: References: Message-ID: On Wed, May 11, 2011 at 9:57 AM, Lan Rogers wrote: > I want to post files stored on a machine to Pastebin (or any similar > service for that matter) using a python script, and then store a link > to that post. Also, I would strongly prefer to avoid doing something > that requires an API key. A similar tool I wrote (which pastes to codepad.org) is here: https://bitbucket.org/prologic/tools/src/59d89262e6b1/codepad The approach would be very similar. Feel free to adapt this. cheers James -- -- James Mills -- -- "Problems are solved by method" From james at jamesthornton.com Wed May 11 02:19:11 2011 From: james at jamesthornton.com (James Thornton) Date: Tue, 10 May 2011 19:19:11 -0500 Subject: [Tutor] Programmatically Post to Pastebin In-Reply-To: References: Message-ID: Pocoo (the creators of Flask) have a Python API for a pastebin they developed called LodgeIt. You can use the hosted version, or the download the source code and host your own (http://www.pocoo.org/projects/lodgeit/). http://paste.pocoo.org/ http://paste.pocoo.org/about/ http://paste.pocoo.org/help/api/ - James On Tue, May 10, 2011 at 6:57 PM, Lan Rogers wrote: > I realize this may not be entirely within the domain of a python > mailing list, but I'm having trouble finding anything helpful > elsewhere. > > I want to post files stored on a machine to Pastebin (or any similar > service for that matter) using a python script, and then store a link > to that post. Also, I would strongly prefer to avoid doing something > that requires an API key. > > Sorry if this isn't really the right place to ask about this, if > that's the case can someone show me a more appropriate forum? > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Latest Blog: http://jamesthornton.com/blog/how-to-get-to-genius From taxbotsis at gmail.com Wed May 11 04:57:13 2011 From: taxbotsis at gmail.com (tax botsis) Date: Tue, 10 May 2011 22:57:13 -0400 Subject: [Tutor] create an xls file using data from a txt file Message-ID: I have the following txt file that has 4 fields that are tab separated: the first is the id and the other three show the results per test. 152 TEST1 valid TEST3 good TEST2 bad 158 TEST2 bad TEST1 bad TEST4 valid . . . Based on the above txt I need to create an xls file having as headers ID, TEST1, TEST2, TEST3, TEST4 and the values valid, bad, etc under the corresponding column: ID TEST1 TEST2 TEST3 TEST4 152 valid bad good 158 bad bad valid I tried to work that out with xlwt but couldn't. Actually, I started working on the following script but I couldn't even split the line for further processing: import xlwt wbk = xlwt.Workbook() sheet = wbk.add_sheet('sheet 1') row = 0 f = open('C:/test.txt','r') for line in f: # separate fields by tab L = line.rstrip().split('\t') #actually some code is needed here to create the columns and put the values under the appropriate column ..... # Write the data, using the style defined above. sheet.write(row,0,ID) sheet.write(row,1,TEST1) sheet.write(row,2,TEST2) sheet.write(row,3,TEST3) sheet.write(row,4,TEST4) row += 1 wbk.save('data.xls') Thanks in advance for any help! -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy at enkelthed.dk Wed May 11 08:52:12 2011 From: tommy at enkelthed.dk (Tommy Bell) Date: Wed, 11 May 2011 08:52:12 +0200 Subject: [Tutor] folder and file list In-Reply-To: References: <4DC92CE4.4010702@enkelthed.dk> Message-ID: <4DCA321C.3030000@enkelthed.dk> On 11-05-2011 00:08, Jorge Romero wrote: > Is there any special reason for deploying that functionality from > scratch by yourself? Can't you use os bulit-in module? > > Perhaps you can find this useful > http://docs.python.org/library/os.html#os.listdir. That way you don't > deal with OS peculiarities such as the one Brett Ritter pointed. > > On Tue, May 10, 2011 at 8:45 AM, Brett Ritter > wrote: > > On Tue, May 10, 2011 at 8:17 AM, Tommy Bell > wrote: > > scandir('c:\tmp') > > > this doesnt work, I know why - but i dont know how to fix it. > > The reason it doesnt work is because isfile requires a file, but > current contains a path. > > Not quite. Stick a "print path" as the first line in scandir. > > Notice that it doesn't print out c:\tmp > > The issue is that Windows (Well, DOS, back in the day) decided to use > backslashes as the path separator, where the rest of the world > (mostly) used slashes. This meant that most programming languages use > backslashes to "escape" characters to have special meaning. Putting > "\n" in a string puts in not an "n" but a newline character. \t is a > tab. This causes you (and many other windows programmers) a little > bit of distress today, in many programming languages. > > To have your string recognize that your backslash is an actual real > backslash you can escape it: > scandir('c:\\tmp') > > After that your code should work fine (it runs on my system, but I'm > not on windows). > > This filepath issue has many details you can look up or ask about, but > this should get you started. > > -- > 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 > > > > > -- > Jorge Romero > Thanks for the assistance. I've attempted to use glob, I actually did try with os.listdir, but then I had to combine the basename (as I understand listdir, is only returns a string with basename) with the path, and I have trouble getting that to work with calling it self when I ran into a folder, ie the recursivecalls import os,glob ##use os.walk def scand(path): for current in glob.glob(os.path.join(path,'*')): if os.path.isdir(current) == True: print "Folder: " + os.path.basename(current) scand(current) if os.path.isfile(current) == True: print "file: " + os.path.basename(current) scand('c:\\Users\Tommy\\docs') instead, with an idea of using os.walk whic I havent tried yet, I dont much mind limiting it to a windows system as I will be using this on my own machine, but I see the idea of not being exposed to OS relevant limitations. The reason for attempting to do this manually is because I am looking at making a script that can help me manage my abundent number of articles and reports for my research in a sensible way - and I thought it would be a good way of learning python. Ultimately the idea is to expand it into now only listing the folders and files, but writing this information to a file (or a database) with added info such as notes and comments on the article/report in a .txt file that shares the same name as the pdf, and which contains extra info /Regards Tommy -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed May 11 10:38:40 2011 From: davea at ieee.org (Dave Angel) Date: Wed, 11 May 2011 04:38:40 -0400 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: Message-ID: <4DCA4B10.1000709@ieee.org> On 01/-10/-28163 02:59 PM, tax botsis wrote: > I have the following txt file that has 4 fields that are tab separated: the > first is the id and the other three show the results per test. > > 152 TEST1 valid TEST3 good TEST2 bad > 158 TEST2 bad TEST1 bad TEST4 valid > . > . > . > > Based on the above txt I need to create an xls file having as headers ID, > TEST1, TEST2, TEST3, TEST4 and the values valid, bad, etc under the > corresponding column: > > ID TEST1 TEST2 TEST3 TEST4 > 152 valid bad good > 158 bad bad valid > > I tried to work that out with xlwt but couldn't. Actually, I started working > on the following script but I couldn't even split the line for further > processing: > > import xlwt > wbk = xlwt.Workbook() > sheet = wbk.add_sheet('sheet 1') > > row = 0 > f = open('C:/test.txt','r') > for line in f: > # separate fields by tab > L = line.rstrip().split('\t') Looks to me like you've split a line just fine. This line needs to be indented, however, so that it's inside the for loop. What happens if you simply add a print L and temporarily comment out the rest of the code? Once you're confident about what's in L, how about if you figure out what data you could put into sheet.write() instead of printing it ? Hint: you probably want a for loop to process the list L. DaveA From jamani.sana at hotmail.com Wed May 11 13:44:29 2011 From: jamani.sana at hotmail.com (Clara Mintz) Date: Wed, 11 May 2011 06:44:29 -0500 Subject: [Tutor] Nodes and Queues? Message-ID: Hi all I am sorry I am a beginner at python and I was reading my book and I came across the terms Nodes and Queue. I am sorry but I don't quite understand how they work. Is there anyone who could possibly explain them in simple terms? Thank you so much. Sincerely, Clara -------------- next part -------------- An HTML attachment was scrubbed... URL: From aznjonn at me.com Wed May 11 12:49:12 2011 From: aznjonn at me.com (Johnson Tran) Date: Wed, 11 May 2011 03:49:12 -0700 Subject: [Tutor] Python program with multiple answers Message-ID: <0C9BD738-5162-407F-B583-9060C5434955@me.com> Hi Guys, I've been working on a Python program where I create an 8 ball that will allow you to ask questions and will reply back with 20 possible answers. It will be continuous until the user says quit. My program works fine although I am trying to add something more to it, where when the user quits, it will present all the answers that the user got again and display them in alphabetical order...if anyone could point me in the right direction it'd be really helpful...my program so far is : (which works fine with no errros) import random dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", "Confucious says 'No'", "Better not tell you now","Cannot predict now","Concentrate and ask again","My reply is no","Outlook not so good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I do not understand the question") while True: choice = raw_input("Type 'ask' to ask a question. Type 'quit' to quit.\n") if choice == "ask": raw_input("Please enter your question:\n") roll = random.randint(0, 10) print dice[roll] raw_input() elif choice == "quit": True = 0 raw_input() else: print "Error -- Try again\n" Thanks, JT From patrick.just4fun at gmail.com Wed May 11 14:14:03 2011 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Wed, 11 May 2011 14:14:03 +0200 Subject: [Tutor] Nodes and Queues? In-Reply-To: References: Message-ID: <4DCA7D8B.70209@gmail.com> A queue is a data structure, which keeps track of multiple objects. You can add data to a queue or you can remove it. When you remove an object from a queue you get the element which you have added first. Therefore, it is also called FIFO (First In First Out). A basic implementation could look like this: class Queue: def __init__(self): self.items = [] def add(self, obj): self.items.append(obj) def remove(self): self.items.pop(0) Nodes are used in multiple contexts, but usually refer to objects which have child objects. -- Patrick On 2011-05-11 13:44, Clara Mintz wrote: > > Hi all > I am sorry I am a beginner at python and I was reading my book and I came across the terms Nodes and Queue. I am sorry but I don't quite understand how they work. Is there anyone who could possibly explain them in simple terms? Thank you so much. > Sincerely, > Clara From patrick.just4fun at gmail.com Wed May 11 14:20:46 2011 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Wed, 11 May 2011 14:20:46 +0200 Subject: [Tutor] Python program with multiple answers In-Reply-To: <0C9BD738-5162-407F-B583-9060C5434955@me.com> References: <0C9BD738-5162-407F-B583-9060C5434955@me.com> Message-ID: <4DCA7F1E.30902@gmail.com> * Create a list. * Each time, the user gets an answer add it to the list * At the end of the program: sort the list and print each element of it - Patrick On 2011-05-11 12:49, Johnson Tran wrote: > Hi Guys, > > I've been working on a Python program where I create an 8 ball that will allow you to ask questions and will reply back with 20 possible answers. It will be continuous until the user says quit. My program works fine although I am trying to add something more to it, where when the user quits, it will present all the answers that the user got again and display them in alphabetical order...if anyone could point me in the right direction it'd be really helpful...my program so far is : (which works fine with no errros) > > > > import random > dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", "Confucious says 'No'", "Better not tell you now","Cannot predict now","Concentrate and ask again","My reply is no","Outlook not so good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I do not understand the question") > while True: > choice = raw_input("Type 'ask' to ask a question. Type 'quit' to quit.\n") > if choice == "ask": > raw_input("Please enter your question:\n") > roll = random.randint(0, 10) > print dice[roll] > raw_input() > elif choice == "quit": > True = 0 > raw_input() > else: > print "Error -- Try again\n" > > > > > > Thanks, > > JT > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From swiftone at swiftone.org Wed May 11 14:57:01 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Wed, 11 May 2011 08:57:01 -0400 Subject: [Tutor] Python program with multiple answers In-Reply-To: <0C9BD738-5162-407F-B583-9060C5434955@me.com> References: <0C9BD738-5162-407F-B583-9060C5434955@me.com> Message-ID: On Wed, May 11, 2011 at 6:49 AM, Johnson Tran wrote: > I've been working on a Python program where I create an 8 ball that will allow you to ask questions and will reply back with 20 possible answers. ... > if anyone could point me in the right direction it'd be really helpful Answer cloudy, try again later [couldn't resist] Patrick gave a decent summary. I'd suggest for learning purposes take each step at a time: 1) Save the questions, then once that works: 2) Save the corresponding answers, then 3) Print them, then 4) Sort them That way if you encounter any problem it's limited in scope rather than trying to take it all in at once. -- Brett Ritter / SwiftOne swiftone at swiftone.org From wprins at gmail.com Wed May 11 15:05:12 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 11 May 2011 14:05:12 +0100 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: Message-ID: On 11 May 2011 03:57, tax botsis wrote: > I tried to work that out with xlwt but couldn't. Actually, I started > working on the following script but I couldn't even split the line for > further processing: > > OK, I've thrown together a quick sample demonstrating all the concepts you need (obviously you need to take from this what is relevant to you): import csv import xlwt import os import sys # Look for input file in same location as script file: inputfilename = os.path.join(os.path.dirname(sys.argv[0]), 'tabdelimited.txt') # Strip off the path basefilename = os.path.basename(inputfilename) # Strip off the extension basefilename_noext = os.path.splitext(basefilename)[0] # Get the path of the input file as the target output path targetoutputpath = os.path.dirname(inputfilename) # Generate the output filename outputfilename = os.path.join(targetoutputpath, basefilename_noext+'.xls') # Create a workbook object workbook = xlwt.Workbook() # Add a sheet object worksheet = workbook.add_sheet(basefilename_noext, cell_overwrite_ok=True) # Get a CSV reader object set up for reading the input file with tab delimiters datareader = csv.reader(open(inputfilename, 'rb'), delimiter='\t', quotechar='"') # Process the file and output to Excel sheet for rowno, row in enumerate(datareader): for colno, colitem in enumerate(row): worksheet.write(rowno, colno, colitem) # Write the output file. workbook.save(outputfilename) # Open it via the operating system (will only work on Windows) # On Linux/Unix you would use subprocess.Popen(['xdg-open', filename]) os.startfile(outputfilename) The code is also available at the following URL in case the formatting gets eaten by the mail system: http://pastebin.com/APpM7EPf Regards Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Wed May 11 15:34:09 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 11 May 2011 13:34:09 +0000 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: , Message-ID: hi all, thanks for this sharing. when i copy and run this code, i got this error: Traceback (most recent call last): File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in import csv File "C:/Python25/myscript/excel\csv.py", line 3, in w=csv.writer(open('output.csv','w')) AttributeError: 'module' object has no attribute 'writer' i'm using Python 2.5 and Win XP. pls help advise. thanks tcl Date: Wed, 11 May 2011 14:05:12 +0100 From: wprins at gmail.com To: taxbotsis at gmail.com CC: tutor at python.org Subject: Re: [Tutor] create an xls file using data from a txt file On 11 May 2011 03:57, tax botsis wrote: I tried to work that out with xlwt but couldn't. Actually, I started working on the following script but I couldn't even split the line for further processing: OK, I've thrown together a quick sample demonstrating all the concepts you need (obviously you need to take from this what is relevant to you): import csv import xlwt import os import sys # Look for input file in same location as script file: inputfilename = os.path.join(os.path.dirname(sys.argv[0]), 'tabdelimited.txt') # Strip off the path basefilename = os.path.basename(inputfilename) # Strip off the extension basefilename_noext = os.path.splitext(basefilename)[0] # Get the path of the input file as the target output path targetoutputpath = os.path.dirname(inputfilename) # Generate the output filename outputfilename = os.path.join(targetoutputpath, basefilename_noext+'.xls') # Create a workbook object workbook = xlwt.Workbook() # Add a sheet object worksheet = workbook.add_sheet(basefilename_noext, cell_overwrite_ok=True) # Get a CSV reader object set up for reading the input file with tab delimiters datareader = csv.reader(open(inputfilename, 'rb'), delimiter='\t', quotechar='"') # Process the file and output to Excel sheet for rowno, row in enumerate(datareader): for colno, colitem in enumerate(row): worksheet.write(rowno, colno, colitem) # Write the output file. workbook.save(outputfilename) # Open it via the operating system (will only work on Windows) # On Linux/Unix you would use subprocess.Popen(['xdg-open', filename]) os.startfile(outputfilename) The code is also available at the following URL in case the formatting gets eaten by the mail system: http://pastebin.com/APpM7EPf Regards Walter _______________________________________________ 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 coolankur2006 at gmail.com Wed May 11 15:47:42 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Wed, 11 May 2011 19:17:42 +0530 Subject: [Tutor] 3 Level Snake Game Made using Pygame API Message-ID: Hey Few weeks back I made out the basic of the snake game and released it on the Web under the file name "hungry.py". Now I Upgraded It Into a 3 Level Game. I test it on windows too and its working completely fine over there too. Download the "Game.Zip" file to play all the three levels and "hungry.py" to play the basic version. Releasing this under GPLv3 :):) Try it out and feedback would be gr8. Here's the download link http://code.google.com/p/hungry-snakes/downloads/list Thanks Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed May 11 15:58:39 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 11 May 2011 14:58:39 +0100 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: Message-ID: On 11 May 2011 14:34, tee chwee liong wrote: > hi all, > > thanks for this sharing. when i copy and run this code, i got this error: > > Traceback (most recent call last): > File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in > import csv > File "C:/Python25/myscript/excel\csv.py", line 3, in > w=csv.writer(open('output.csv','w')) > AttributeError: 'module' object has no attribute 'writer' > > Well, reading the error message, it's saying that module "csv", coming from file "C:/Python25/myscript/excel\ csv.py" has no member "writer". So, it seems you've called your test script (module) "csv" which effecitvely hid the standard python "csv" module. Try renaming your script file to something else ('testcsv.py' maybe) so its name doesn't conflict with the standard "csv" module and try again. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From aznjonn at me.com Wed May 11 15:23:57 2011 From: aznjonn at me.com (Johnson Tran) Date: Wed, 11 May 2011 06:23:57 -0700 Subject: [Tutor] Python program with multiple answers In-Reply-To: References: <0C9BD738-5162-407F-B583-9060C5434955@me.com> Message-ID: <469B06AC-5B7E-4092-9668-F1465D468002@me.com> Thanks for all the replies. But, sorry I am getting a little confused. I have never created a list before and am not really sure where to start. If I put a "answer_list=[]" before the while True: line...is this correct? Or to go by Brett's method, how would I go about saving the questions and answers? If I am only trying to make a list of the answers, I probably do not need to save the questions ? This is probably completely off but tried: import random dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", "Confucious says 'No'", "Better not tell you now","Cannot predict now","Concentrate and ask again","My reply is no","Outlook not so good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I do not understand the question") answer_list=[] while True: choice = raw_input("Type 'ask' to ask a question. Type 'quit' to quit.\n") if choice == "ask": raw_input("Please enter your question:\n") roll = random.randint(0, len(dice)) print dice[roll] raw_input() elif choice == "quit": True = 0 raw_input() else: print "Error -- Try again\n" answer_list=??? <--not sure answer_list.sort() print "Your answer's sorted:", answer_list On May 11, 2011, at 5:57 AM, Brett Ritter wrote: * Create a list. * Each time, the user gets an answer add it to the list * At the end of the program: sort the list and print each element of it - Patrick > On Wed, May 11, 2011 at 6:49 AM, Johnson Tran wrote: >> I've been working on a Python program where I create an 8 ball that will allow you to ask questions and will reply back with 20 possible answers. > ... >> if anyone could point me in the right direction it'd be really helpful > > Answer cloudy, try again later [couldn't resist] > > Patrick gave a decent summary. I'd suggest for learning purposes take > each step at a time: > 1) Save the questions, then once that works: > 2) Save the corresponding answers, then > 3) Print them, then > 4) Sort them > > That way if you encounter any problem it's limited in scope rather > than trying to take it all in at once. > -- > Brett Ritter / SwiftOne > swiftone at swiftone.org From taserian at gmail.com Wed May 11 16:41:59 2011 From: taserian at gmail.com (taserian) Date: Wed, 11 May 2011 10:41:59 -0400 Subject: [Tutor] Python program with multiple answers In-Reply-To: <0C9BD738-5162-407F-B583-9060C5434955@me.com> References: <0C9BD738-5162-407F-B583-9060C5434955@me.com> Message-ID: In addition to the wise counsel you've already received, I noticed that your randint goes from 0 to 10, but you have 20 possible outcomes in dice(). If I'm counting correctly, it should be roll=random.randint(0, 19). Tony R. On Wed, May 11, 2011 at 6:49 AM, Johnson Tran wrote: > Hi Guys, > > I've been working on a Python program where I create an 8 ball that will > allow you to ask questions and will reply back with 20 possible answers. It > will be continuous until the user says quit. My program works fine although > I am trying to add something more to it, where when the user quits, it will > present all the answers that the user got again and display them in > alphabetical order...if anyone could point me in the right direction it'd be > really helpful...my program so far is : (which works fine with no errros) > > > > import random > dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", > "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try > again", "Confucious says 'No'", "Better not tell you now","Cannot predict > now","Concentrate and ask again","My reply is no","Outlook not so > good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I > do not understand the question") > while True: > choice = raw_input("Type 'ask' to ask a question. Type 'quit' to > quit.\n") > if choice == "ask": > raw_input("Please enter your question:\n") > roll = random.randint(0, 10) > print dice[roll] > raw_input() > elif choice == "quit": > True = 0 > raw_input() > else: > print "Error -- Try again\n" > > > > > > Thanks, > > JT > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Wed May 11 16:53:50 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 11 May 2011 10:53:50 -0400 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: Message-ID: Slow day at work, so I tried something a little different mostly as a learning exercise for myself, let me know what you all think. I thought it would be useful to have a writer that scales and that organizes the data. For example, you might have 20 tests one day, and 5 the next. I broke up the data into dictionaries where the IDs were keys, and everything that follows is a tuple of testX and result. Instead of iterating through each column, it only writes to the columns where data is present. Disclaimer: I am copying and pasting into Gmail, which sometimes screws up indents. I also put it into pastebin, which was pretty exciting considering I have never used it before: http://pastebin.com/2Dke5FtX import xlwt class Parser: ''' classdocs ''' def __init__(self, test, result): ''' Constructor ''' self.result = result self.test = test self.id = int(self.test[4:]) x = open('test.txt') id_dict = {} for all in x: y = all.split(" ") y[-1] = y[-1].strip() id_dict[y[0]] = y[1:] max_test = 0 for key, lists in id_dict.items(): length = len(lists)/2 a = 0 parser_list = [] for items in range(length): t = (lists[a], lists[a+1]) p = Parser(*t) parser_list.append(p) if max_test < p.id: max_test = p.id a +=2 id_dict[key] = parser_list workbook = xlwt.Workbook() worksheet = workbook.add_sheet("testruns", cell_overwrite_ok=True) header = 'TEST{0}' headers = ['ID'] range_id = range(max_test +1) for all in range_id[1:]: headers.append(header.format(all)) for i, colno in enumerate(headers): print i, type(i) worksheet.write(0, i, colno) rowno = 1 for keys, values in id_dict.items(): worksheet.write(rowno, 0, keys) for object_lists in values: worksheet.write(rowno, object_lists.id , object_lists.result) rowno +=1 workbook.save("test.xls") On Wed, May 11, 2011 at 9:58 AM, Walter Prins wrote: > > > On 11 May 2011 14:34, tee chwee liong wrote: > >> hi all, >> >> thanks for this sharing. when i copy and run this code, i got this error: >> >> Traceback (most recent call last): >> File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in >> import csv >> File "C:/Python25/myscript/excel\csv.py", line 3, in >> w=csv.writer(open('output.csv','w')) >> AttributeError: 'module' object has no attribute 'writer' >> >> > Well, reading the error message, it's saying that module "csv", coming from > file "C:/Python25/myscript/excel\ > csv.py" has no member "writer". So, it seems you've called your test > script (module) "csv" which effecitvely hid the standard python "csv" > module. > > Try renaming your script file to something else ('testcsv.py' maybe) so its > name doesn't conflict with the standard "csv" module and try again. > > Walter > > _______________________________________________ > 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 bodsda at googlemail.com Wed May 11 14:17:13 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Wed, 11 May 2011 12:17:13 +0000 Subject: [Tutor] Python program with multiple answers In-Reply-To: <0C9BD738-5162-407F-B583-9060C5434955@me.com> References: <0C9BD738-5162-407F-B583-9060C5434955@me.com> Message-ID: <872198230-1305116223-cardhu_decombobulator_blackberry.rim.net-62976605-@b16.c12.bise7.blackberry> Hi, I would suggest appending the dice[roll] to a new list just after the print statement, then in the quit block order the list and then loop over it and print each entry. Hope this helps, Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Johnson Tran Sender: tutor-bounces+bodsda=ubuntu.com at python.org Date: Wed, 11 May 2011 03:49:12 To: Subject: [Tutor] Python program with multiple answers Hi Guys, I've been working on a Python program where I create an 8 ball that will allow you to ask questions and will reply back with 20 possible answers. It will be continuous until the user says quit. My program works fine although I am trying to add something more to it, where when the user quits, it will present all the answers that the user got again and display them in alphabetical order...if anyone could point me in the right direction it'd be really helpful...my program so far is : (which works fine with no errros) import random dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", "Confucious says 'No'", "Better not tell you now","Cannot predict now","Concentrate and ask again","My reply is no","Outlook not so good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I do not understand the question") while True: choice = raw_input("Type 'ask' to ask a question. Type 'quit' to quit.\n") if choice == "ask": raw_input("Please enter your question:\n") roll = random.randint(0, 10) print dice[roll] raw_input() elif choice == "quit": True = 0 raw_input() else: print "Error -- Try again\n" Thanks, JT _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Wed May 11 17:17:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 May 2011 16:17:17 +0100 Subject: [Tutor] Python program with multiple answers References: <0C9BD738-5162-407F-B583-9060C5434955@me.com> Message-ID: "Johnson Tran" wrote > import random > dice = ... > while True: > ... > elif choice == "quit": > True = 0 > raw_input() Do not do this! True is supposed to be a fixed, constant boolean value. In fact in Python v3 you will get an error if you try it. Instead use break to exit from the loop. > else: > print "Error -- Try again\n" HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From forums at zhub.co.uk Wed May 11 17:24:02 2011 From: forums at zhub.co.uk (Robert .) Date: Wed, 11 May 2011 16:24:02 +0100 Subject: [Tutor] Python Hard_way 40 Message-ID: Hi all, My first post ever! :) I'm following the guide "Learn Python the Hard Way" and have reached a point where I am struggling to understand the code and unfortunately the authors guide hasn't cleared it up for me. (excercise 40 for reference) The main confusion is coming from* 'cities['_find'] = find_city'* I'm not sure what this is really doing. >From my learning, this should add an extra item to the dict with the index name of "_find" and the value which is returned from "find_city" function. run I add "print cities" after the above function to try and look at how the dict is now populated, I am still confused. (PasteBin version to see highlighting and indents -> http://pastebin.com/gmngh6sc Not sure how it will look in email) ------------------ cities = {'ca': 'San Fran','MI':'detroit','FL':'Jacksonville'} cities['NY']= 'New York' cities['OR']= 'Portland' def find_city(themap, state): if state in themap: return themap[state] else: return "Not found" cities['_find'] = find_city while True: print "State? (Enter to quit)", state = raw_input("> ") if not state: break city_found = cities['_find'](cities,state) print city_found ---------------------- Grateful for any help in explaining how this program is working and each step it is taking. kindest regards Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 11 17:24:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 May 2011 16:24:28 +0100 Subject: [Tutor] Python program with multiple answers References: <0C9BD738-5162-407F-B583-9060C5434955@me.com> <469B06AC-5B7E-4092-9668-F1465D468002@me.com> Message-ID: "Johnson Tran" wrote > If I put a "answer_list=[]" before the while True: line...is this > correct? Yes that creates an empty list. > only trying to make a list of the answers, I probably > do not need to save the questions ? Correct, but.... > import random > .... > answer_list=[] > while True: > choice = raw_input("Type 'ask' to ask a question. Type > 'quit' to quit.\n") > if choice == "ask": > raw_input("Please enter your question:\n") You are not storing the users input so how do you know which question was input? I'd expect to see: question = raw_input("Please enter your question:\n") Or is this really just a print statement? You seem to ignore this value and just print a random question... > roll = random.randint(0, len(dice)) > print dice[roll] > raw_input() Again this does not store the answer. I'd expect: answer_list.append( raw_input() ) This will add the answer to the list > elif choice == "quit": break > else: > print "Error -- Try again\n" > answer_list.sort() > print "Your answer's sorted:", answer_list That will print the list ijncluding brackets etc, you probably want: print "your answers sorted:" for answer in answer_list: print answer HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed May 11 17:31:09 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 May 2011 16:31:09 +0100 Subject: [Tutor] Nodes and Queues? References: Message-ID: "Clara Mintz" wrote > I am sorry I am a beginner at python and I was reading > my book and I came across the terms Nodes and Queue. > I am sorry but I don't quite understand how they work. Its a bit of Comp Science terminology. A Queue is a particular type of data structure somewhat like a Python list but usually implemented in other languages using a series of Node objects each of which holds a value and a link to the next Node. You then add values to the queue by creating a new Node and linking it to the existing queue. In Python you would usually implement a queue using the standard list and use its pop/push methods and indexing to simulate the behaviour without the hassle of creating Node classes etc. It suggests your book is a comp science oriented book that happens to use Python rather than a dedicated Python tutorial. (That is not necessarily a bad thing, it will better prepare you for learning other languages in the future) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmchase.com Wed May 11 17:33:33 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 11 May 2011 11:33:33 -0400 Subject: [Tutor] Python program with multiple answers In-Reply-To: <469B06AC-5B7E-4092-9668-F1465D468002@me.com> References: <0C9BD738-5162-407F-B583-9060C5434955@me.com> <469B06AC-5B7E-4092-9668-F1465D468002@me.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3A2160A@EMARC112VS01.exchad.jpmchase.net> I think it should be: import random dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", "Confucious says 'No'", "Better not tell you now","Cannot predict now","Concentrate and ask again","My reply is no","Outlook not so good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I do not understand the question") answer_set=set([]) # Use set because there is no need to return an answer twice if you are sorting alphabetically # otherwise use answer_list = [] while True: choice = raw_input("Type 'ask' to ask a question. Type 'quit' to quit.\n") if choice == "ask": raw_input("Please enter your question:\n") roll = random.randint(0, len(dice) -1 ) #-1 because dice[20] will return an IndexError answer = dice[roll] answer_set.add(answer) print answer raw_input() elif choice == "quit": true = 0 # use LOWERCASE as to not attempt redefining True (yes, you can define True to equal False) raw_input() else: print "Error -- Try again\n" # I think print automatically adds \n #answer_list.sort() #this works for a list but not a set sorted_list = sorted(answer_set) print "Your answer's sorted:", sorted_list # looks ugly #try the following for a prettier output print "Your answer's sorted: ", ','.join(sorted_list) Hope that helps, Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Johnson Tran Sent: Wednesday, May 11, 2011 8:24 AM To: tutor at python.org Subject: Re: [Tutor] Python program with multiple answers Thanks for all the replies. But, sorry I am getting a little confused. I have never created a list before and am not really sure where to start. If I put a "answer_list=[]" before the while True: line...is this correct? Or to go by Brett's method, how would I go about saving the questions and answers? If I am only trying to make a list of the answers, I probably do not need to save the questions ? This is probably completely off but tried: import random dice = ("Without a doubt", "It is certain", "It is decidedly so","Yes", "For Sure", "No", "Dont count on it", "Try asking again","Reply hazy, try again", "Confucious says 'No'", "Better not tell you now","Cannot predict now","Concentrate and ask again","My reply is no","Outlook not so good","Very doubtful","Outlook is good","Most likely","As I see it, yes","I do not understand the question") answer_list=[] while True: choice = raw_input("Type 'ask' to ask a question. Type 'quit' to quit.\n") if choice == "ask": raw_input("Please enter your question:\n") roll = random.randint(0, len(dice)) print dice[roll] raw_input() elif choice == "quit": True = 0 raw_input() else: print "Error -- Try again\n" answer_list=??? <--not sure answer_list.sort() print "Your answer's sorted:", answer_list On May 11, 2011, at 5:57 AM, Brett Ritter wrote: * Create a list. * Each time, the user gets an answer add it to the list * At the end of the program: sort the list and print each element of it - Patrick > On Wed, May 11, 2011 at 6:49 AM, Johnson Tran wrote: >> I've been working on a Python program where I create an 8 ball that will allow you to ask questions and will reply back with 20 possible answers. > ... >> if anyone could point me in the right direction it'd be really helpful > > Answer cloudy, try again later [couldn't resist] > > Patrick gave a decent summary. I'd suggest for learning purposes take > each step at a time: > 1) Save the questions, then once that works: > 2) Save the corresponding answers, then > 3) Print them, then > 4) Sort them > > That way if you encounter any problem it's limited in scope rather > than trying to take it all in at once. > -- > 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 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From bgailer at gmail.com Wed May 11 17:39:14 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 11 May 2011 11:39:14 -0400 Subject: [Tutor] Python Hard_way 40 In-Reply-To: References: Message-ID: <4DCAADA2.9090005@gmail.com> On 5/11/2011 11:24 AM, Robert . wrote: > Hi all, > > My first post ever! :) > I'm following the guide "Learn Python the Hard Way" and have reached a > point where I am struggling to understand the code and unfortunately > the authors guide hasn't cleared it up for me. (excercise 40 for > reference) > > The main confusion is coming from*'cities['_find'] = find_city'* I'm > not sure what this is really doing. > > From my learning, this should add an extra item to the dict with the > index name of "_find" and the value which is returned from "find_city" > function. This stores a reference to the function. The following line is the call to the function. city_found = cities['_find'](cities,state) [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Wed May 11 17:44:48 2011 From: andreengels at gmail.com (Andre Engels) Date: Wed, 11 May 2011 17:44:48 +0200 Subject: [Tutor] Python Hard_way 40 In-Reply-To: References: Message-ID: On Wed, May 11, 2011 at 5:24 PM, Robert . wrote: > Hi all, > > My first post ever! :) > I'm following the guide "Learn Python the Hard Way" and have reached a point > where I am struggling to understand the code and unfortunately the authors > guide hasn't cleared it up for me. (excercise 40 for reference) > > The main confusion is coming from 'cities['_find'] = find_city' I'm not sure > what this is really doing. > > From my learning, this should add an extra item to the dict with the index > name of "_find" and the value which is returned from "find_city" function. No, that would be cities['_find'] = find_city() When you use cities['_find'] = find_city the value of the extra item is _the function find_city itself_. And thus later city_found = cities['_find'](cities,state) will be equivalent to city_found = find_city(cities,state) -- Andr? Engels, andreengels at gmail.com From ramit.prasad at jpmchase.com Wed May 11 17:54:11 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 11 May 2011 11:54:11 -0400 Subject: [Tutor] Python Hard_way 40 In-Reply-To: <4DCAADA2.9090005@gmail.com> References: <4DCAADA2.9090005@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B33239@EMARC112VS01.exchad.jpmchase.net> >>This stores a reference to the function. The following line is the call to the function. Just to expand. In Python, you can pass functions like you would anything else. So, the first line before stores the function reference find_city inside the dictionary cities with the key '_find'. It then looks up the value for the key '_find' which returns a function and then calls the returned function with the arguments cities and state. cities['_find'] = find_city city_found = cities['_find'](cities,state) The previous line is equivalent to function_name = cities['_find'] # function_name is the equivalent of find_city now city_found = function_name(cities, state) And that is equivalent to: city_found = find_city(cities, state) Hope that helps, Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of bob gailer Sent: Wednesday, May 11, 2011 10:39 AM To: Robert . Cc: Tutor at python.org Subject: Re: [Tutor] Python Hard_way 40 On 5/11/2011 11:24 AM, Robert . wrote: Hi all, My first post ever! :) I'm following the guide "Learn Python the Hard Way" and have reached a point where I am struggling to understand the code and unfortunately the authors guide hasn't cleared it up for me. (excercise 40 for reference) The main confusion is coming from 'cities['_find'] = find_city' I'm not sure what this is really doing. >From my learning, this should add an extra item to the dict with the index name of "_find" and the value which is returned from "find_city" function. This stores a reference to the function. The following line is the call to the function. city_found = cities['_find'](cities,state) [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Wed May 11 19:26:13 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 11 May 2011 13:26:13 -0400 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: Message-ID: your "\" is a "/" when writing out a string, such as 'C:\test.xls', the "/" is an escape in python. So you have two choices, You can either write out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path = r'C:\test.xls' the "r" bit tells python that the following is a regular expression. or regex. You can also use Walter's method above. On Wed, May 11, 2011 at 1:10 PM, tax botsis wrote: > James, > how would you save the workbook into a specific directory? I tried to run > that: > > workbook.save('C:/test.xls') > > but I get the following error: > > > Traceback (most recent call last): > File "", line 1, in > wbk.save("C:/test.xls") > File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 634, in save > doc.save(filename, self.get_biff_data()) > File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 615, in > get_biff_data > self.__worksheets[self.__active_sheet].selected = True > IndexError: list index out of range > > Thanks > Tax > > > 2011/5/11 James Reynolds > >> Slow day at work, so I tried something a little different mostly as a >> learning exercise for myself, let me know what you all think. >> >> I thought it would be useful to have a writer that scales and that >> organizes the data. For example, you might have 20 tests one day, and 5 the >> next. >> >> I broke up the data into dictionaries where the IDs were keys, and >> everything that follows is a tuple of testX and result. >> >> Instead of iterating through each column, it only writes to the columns >> where data is present. >> >> Disclaimer: I am copying and pasting into Gmail, which sometimes screws up >> indents. >> >> I also put it into pastebin, which was pretty exciting considering I have >> never used it before: >> >> http://pastebin.com/2Dke5FtX >> >> import xlwt >> >> >> class Parser: >> ''' >> classdocs >> ''' >> >> >> def __init__(self, test, result): >> ''' >> Constructor >> ''' >> self.result = result >> self.test = test >> self.id = int(self.test[4:]) >> >> x = open('test.txt') >> >> id_dict = {} >> >> for all in x: >> y = all.split(" ") >> y[-1] = y[-1].strip() >> id_dict[y[0]] = y[1:] >> >> max_test = 0 >> for key, lists in id_dict.items(): >> length = len(lists)/2 >> a = 0 >> parser_list = [] >> for items in range(length): >> t = (lists[a], lists[a+1]) >> p = Parser(*t) >> parser_list.append(p) >> if max_test < p.id: >> max_test = p.id >> a +=2 >> id_dict[key] = parser_list >> >> >> workbook = xlwt.Workbook() >> worksheet = workbook.add_sheet("testruns", cell_overwrite_ok=True) >> header = 'TEST{0}' >> headers = ['ID'] >> range_id = range(max_test +1) >> for all in range_id[1:]: >> headers.append(header.format(all)) >> >> for i, colno in enumerate(headers): >> print i, type(i) >> worksheet.write(0, i, colno) >> rowno = 1 >> for keys, values in id_dict.items(): >> worksheet.write(rowno, 0, keys) >> for object_lists in values: >> worksheet.write(rowno, object_lists.id , object_lists.result) >> rowno +=1 >> >> >> workbook.save("test.xls") >> >> >> >> >> On Wed, May 11, 2011 at 9:58 AM, Walter Prins wrote: >> >>> >>> >>> On 11 May 2011 14:34, tee chwee liong wrote: >>> >>>> hi all, >>>> >>>> thanks for this sharing. when i copy and run this code, i got this >>>> error: >>>> >>>> Traceback (most recent call last): >>>> File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in >>>> import csv >>>> File "C:/Python25/myscript/excel\csv.py", line 3, in >>>> w=csv.writer(open('output.csv','w')) >>>> AttributeError: 'module' object has no attribute 'writer' >>>> >>>> >>> Well, reading the error message, it's saying that module "csv", coming >>> from file "C:/Python25/myscript/excel\ >>> csv.py" has no member "writer". So, it seems you've called your test >>> script (module) "csv" which effecitvely hid the standard python "csv" >>> module. >>> >>> Try renaming your script file to something else ('testcsv.py' maybe) so >>> its name doesn't conflict with the standard "csv" module and try again. >>> >>> Walter >>> >>> _______________________________________________ >>> >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed May 11 19:40:58 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 11 May 2011 13:40:58 -0400 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: Message-ID: On Wed, May 11, 2011 at 1:26 PM, James Reynolds wrote: > your "\" is a "/" > > when writing out a string, such as 'C:\test.xls', the "/" is an escape in > python. So you have two choices, You can either write out path > = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path = > r'C:\test.xls' the "r" bit tells python that the following is a regular > expression. or regex. > r means this is 'raw data'. Take each character literally. Raw data does not use \ as a prefix to an escape code. It is just another character > > You can also use Walter's method above. > > On Wed, May 11, 2011 at 1:10 PM, tax botsis wrote: > >> James, >> how would you save the workbook into a specific directory? I tried to run >> that: >> >> workbook.save('C:/test.xls') >> >> but I get the following error: >> >> >> Traceback (most recent call last): >> File "", line 1, in >> wbk.save("C:/test.xls") >> File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 634, in save >> doc.save(filename, self.get_biff_data()) >> File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 615, in >> get_biff_data >> self.__worksheets[self.__active_sheet].selected = True >> IndexError: list index out of range >> >> Thanks >> Tax >> >> >> 2011/5/11 James Reynolds >> >>> Slow day at work, so I tried something a little different mostly as a >>> learning exercise for myself, let me know what you all think. >>> >>> I thought it would be useful to have a writer that scales and that >>> organizes the data. For example, you might have 20 tests one day, and 5 the >>> next. >>> >>> I broke up the data into dictionaries where the IDs were keys, and >>> everything that follows is a tuple of testX and result. >>> >>> Instead of iterating through each column, it only writes to the columns >>> where data is present. >>> >>> Disclaimer: I am copying and pasting into Gmail, which sometimes screws >>> up indents. >>> >>> I also put it into pastebin, which was pretty exciting considering I have >>> never used it before: >>> >>> http://pastebin.com/2Dke5FtX >>> >>> import xlwt >>> >>> >>> class Parser: >>> ''' >>> classdocs >>> ''' >>> >>> >>> def __init__(self, test, result): >>> ''' >>> Constructor >>> ''' >>> self.result = result >>> self.test = test >>> self.id = int(self.test[4:]) >>> >>> x = open('test.txt') >>> >>> id_dict = {} >>> >>> for all in x: >>> y = all.split(" ") >>> y[-1] = y[-1].strip() >>> id_dict[y[0]] = y[1:] >>> >>> max_test = 0 >>> for key, lists in id_dict.items(): >>> length = len(lists)/2 >>> a = 0 >>> parser_list = [] >>> for items in range(length): >>> t = (lists[a], lists[a+1]) >>> p = Parser(*t) >>> parser_list.append(p) >>> if max_test < p.id: >>> max_test = p.id >>> a +=2 >>> id_dict[key] = parser_list >>> >>> >>> workbook = xlwt.Workbook() >>> worksheet = workbook.add_sheet("testruns", cell_overwrite_ok=True) >>> header = 'TEST{0}' >>> headers = ['ID'] >>> range_id = range(max_test +1) >>> for all in range_id[1:]: >>> headers.append(header.format(all)) >>> >>> for i, colno in enumerate(headers): >>> print i, type(i) >>> worksheet.write(0, i, colno) >>> rowno = 1 >>> for keys, values in id_dict.items(): >>> worksheet.write(rowno, 0, keys) >>> for object_lists in values: >>> worksheet.write(rowno, object_lists.id , object_lists.result) >>> rowno +=1 >>> >>> >>> workbook.save("test.xls") >>> >>> >>> >>> >>> On Wed, May 11, 2011 at 9:58 AM, Walter Prins wrote: >>> >>>> >>>> >>>> On 11 May 2011 14:34, tee chwee liong wrote: >>>> >>>>> hi all, >>>>> >>>>> thanks for this sharing. when i copy and run this code, i got this >>>>> error: >>>>> >>>>> Traceback (most recent call last): >>>>> File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in >>>>> import csv >>>>> File "C:/Python25/myscript/excel\csv.py", line 3, in >>>>> w=csv.writer(open('output.csv','w')) >>>>> AttributeError: 'module' object has no attribute 'writer' >>>>> >>>>> >>>> Well, reading the error message, it's saying that module "csv", coming >>>> from file "C:/Python25/myscript/excel\ >>>> csv.py" has no member "writer". So, it seems you've called your test >>>> script (module) "csv" which effecitvely hid the standard python "csv" >>>> module. >>>> >>>> Try renaming your script file to something else ('testcsv.py' maybe) so >>>> its name doesn't conflict with the standard "csv" module and try again. >>>> >>>> Walter >>>> >>>> _______________________________________________ >>>> >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Wed May 11 20:39:11 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 11 May 2011 14:39:11 -0400 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> >your "\" is a "/" >when writing out a string, such as 'C:\test.xls', the "/" is an escape in python. So you have two choices, You can either write out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out path = r'C:\test.xls' the "r" bit tells python that the following is a regular expression. or regex. '/' is perfectly valid Windows separator. See the tested examples below. It works just fine pretty much anywhere I have ever tried it, including the command line. (except apparently for an MSOffice file save dialog that I tried just now) >>> import xlwt >>> workbook = xlwt.Workbook() >>> sheet = workbook.add_sheet('test') >>> sheet.write(0,0,'test') >>> workbook.save('C:/test') >>> workbook.save('C:/test.xls') >>> workbook.save('C:\\test2.xls') >>> workbook.save(r'C:\test3.xls') >>> The error he is getting may be unrelated to actually saving. I am not very familiar with the xlwt, but I know it does not write everything to file on the sheet.write() command. Save() actually does some writing and then saves the file. This can lead to misleading errors. I have had a similar error when writing non-ASCII data (and not changing the default ASCII encoding type). Furthermore, the escape character is '\' not '/', And r'string' means raw string not regular expression. "String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences." ~ http://docs.python.org/reference/lexical_analysis.html Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Wed May 11 21:14:53 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 11 May 2011 15:14:53 -0400 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> Message-ID: Yes, thank you. Actually, I never knew that about the windows separators, since I've just always used the '\' out of habit. On Wed, May 11, 2011 at 2:39 PM, Prasad, Ramit wrote: > > > >your "\" is a "/" > > > > >when writing out a string, such as 'C:\test.xls', the "/" is an escape in > python. So you have two choices, You can either write > > out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can write out > path = r'C:\test.xls' the "r" bit tells python that the following is a > regular expression. or regex. > > > > > > ?/? is perfectly valid Windows separator. See the *tested* examples below. > It works just fine pretty much anywhere I have ever tried it, including the > command line. (except apparently for an MSOffice file save dialog that I > tried just now) > > > > >>> import xlwt > > >>> workbook = xlwt.Workbook() > > >>> sheet = workbook.add_sheet('test') > > >>> sheet.write(0,0,'test') > > >>> workbook.save('C:/test') > > >>> workbook.save('C:/test.xls') > > >>> workbook.save('C:\\test2.xls') > > >>> workbook.save(r'C:\test3.xls') > > >>> > > > > > > The error he is getting may be unrelated to actually saving. I am not very > familiar with the xlwt, but I know it does not write everything to file on > the sheet.write() command. Save() actually does some writing and then saves > the file. This can lead to misleading errors. I have had a similar error > when writing non-ASCII data (and not changing the default ASCII encoding > type). > > > > > > Furthermore, the escape character is ?\? not ?/?, > > > > And r?string? means raw string not* *regular expression. > > ?String literals may optionally be prefixed with a letter 'r' or 'R'; such > strings are called *raw strings* and use different rules for interpreting > backslash escape sequences.? ~ > http://docs.python.org/reference/lexical_analysis.html > > > > > > Ramit > > > > > > > > *Ramit Prasad **| JPMorgan Chase Investment Bank | Currencies Technology* > > *712 Main Street **| Houston, TX 77002* > > *work phone: 713 - 216 - 5423* > > > > This communication is for informational purposes only. It is not intended > as an offer or solicitation for the purchase or sale of any financial > instrument or as an official confirmation of any transaction. All market > prices, data and other information are not warranted as to completeness or > accuracy and are subject to change without notice. Any comments or > statements made herein do not necessarily reflect those of JPMorgan Chase & > Co., its subsidiaries and affiliates. This transmission may contain > information that is privileged, confidential, legally privileged, and/or > exempt from disclosure under applicable law. If you are not the intended > recipient, you are hereby notified that any disclosure, copying, > distribution, or use of the information contained herein (including any > reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any > attachments are believed to be free of any virus or other defect that might > affect any computer system into which it is received and opened, it is the > responsibility of the recipient to ensure that it is virus free and no > responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and > affiliates, as applicable, for any loss or damage arising in any way from > its use. If you received this transmission in error, please immediately > contact the sender and destroy the material in its entirety, whether in > electronic or hard copy format. Thank you. Please refer to > http://www.jpmorgan.com/pages/disclosures for disclosures relating to > European legal entities. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Wed May 11 21:48:05 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 11 May 2011 12:48:05 -0700 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4DCAE7F5.2020304@alchemy.com> On 11-May-11 12:14, James Reynolds wrote: > Actually, I never knew that about the windows separators, since I've > just always used the '\' out of habit. If you want your code to run everywhere, you should use the functions in os.path to manipulate and build paths. Otherwise, using \ all the time means your code will ONLY ever work on Windows. Using / all the time means your code will work fine on Mac OS X, Linux, or other POSIX systems, and PROBABLY ok on Windows most of the time, but not on other systems. > out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can > write out path = r'C:\test.xls' the "r" bit tells python that the > following is a regular expression. or regex. Not to be too pedantic, but since this is a tutorial list, I'll point out the more accurate answer so new programmers don't get a mistaken impression. The 'r' string prefix does not actually mean regular expressions. It means "raw string" where (almost) no backslash codes are recognized in the string constant, so you could say r'C:\test.xls' instead of 'c:\\test.xls'. Raw strings are, however, really useful for strings which hold regular expressions, so you see them in that context a lot. ... ah... and I just noticed that this was pointed out later in the thread. Sorry for the repeat there. > ?/? is perfectly valid Windows separator. See the *tested* examples > below. It works just fine pretty much anywhere I have ever tried it, > including the command line. (except apparently for an MSOffice file > save dialog that I tried just now) Not... quite. / is accepted by a number of programs, including the Python interpreter, which came from Unix-like systems where / is the directory separator. Very old versions of MSDOS could be configured to use / on the command line for pretty much everything, but that has been deprecated for a long time now (they originally wanted / for command-line switches instead, so used \ for directory separators). Core windows commands don't generally accept it, including native Windows applications (although sometimes they're lenient in what they accept). It'll work for command-line Python script usage because it's *python* that allows them, not *windows*. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From davidheiserca at gmail.com Wed May 11 22:04:34 2011 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Wed, 11 May 2011 13:04:34 -0700 Subject: [Tutor] create an xls file using data from a txt file References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> <4DCAE7F5.2020304@alchemy.com> Message-ID: I'm not contradicting anyone, just relating my experience. I have a large suite of Python programs that run routinely on both Windows and Linux systems. Some of the programs build large directory tree structures. I cast all directory delimiters to the forward slash "/". No problems. ----- Original Message ----- From: "Steve Willoughby" To: Sent: Wednesday, May 11, 2011 12:48 PM Subject: Re: [Tutor] create an xls file using data from a txt file On 11-May-11 12:14, James Reynolds wrote: > Actually, I never knew that about the windows separators, since I've > just always used the '\' out of habit. If you want your code to run everywhere, you should use the functions in os.path to manipulate and build paths. Otherwise, using \ all the time means your code will ONLY ever work on Windows. Using / all the time means your code will work fine on Mac OS X, Linux, or other POSIX systems, and PROBABLY ok on Windows most of the time, but not on other systems. > out path = 'C:\\test.xls', which will be 'C:\test.xls' or you can > write out path = r'C:\test.xls' the "r" bit tells python that the > following is a regular expression. or regex. Not to be too pedantic, but since this is a tutorial list, I'll point out the more accurate answer so new programmers don't get a mistaken impression. The 'r' string prefix does not actually mean regular expressions. It means "raw string" where (almost) no backslash codes are recognized in the string constant, so you could say r'C:\test.xls' instead of 'c:\\test.xls'. Raw strings are, however, really useful for strings which hold regular expressions, so you see them in that context a lot. ... ah... and I just noticed that this was pointed out later in the thread. Sorry for the repeat there. > ?/? is perfectly valid Windows separator. See the *tested* examples > below. It works just fine pretty much anywhere I have ever tried it, > including the command line. (except apparently for an MSOffice file > save dialog that I tried just now) Not... quite. / is accepted by a number of programs, including the Python interpreter, which came from Unix-like systems where / is the directory separator. Very old versions of MSDOS could be configured to use / on the command line for pretty much everything, but that has been deprecated for a long time now (they originally wanted / for command-line switches instead, so used \ for directory separators). Core windows commands don't generally accept it, including native Windows applications (although sometimes they're lenient in what they accept). It'll work for command-line Python script usage because it's *python* that allows them, not *windows*. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From ramit.prasad at jpmchase.com Thu May 12 00:54:41 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 11 May 2011 18:54:41 -0400 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: <4DCAE7F5.2020304@alchemy.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> <4DCAE7F5.2020304@alchemy.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B33CDB@EMARC112VS01.exchad.jpmchase.net> >Core windows commands don't generally accept it, including native >Windows applications (although sometimes they're lenient in what they >accept). It'll work for command-line Python script usage because it's >*python* that allows them, not *windows*. They work in *Windows* command prompt natively. Some apps do not work well that is true, but the reason that they work like this with Python is NOT because Python allows it but because Windows does. I highly doubt Python checks for "/" and converts it to "\\" (or does any complicated checking of file strings). YMMV for apps, but I have never had a problem with '/' on the command prompt. It is an important caveat to note that this behavior is not Guaranteed. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From steve at alchemy.com Thu May 12 01:24:27 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 11 May 2011 16:24:27 -0700 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B33CDB@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> <4DCAE7F5.2020304@alchemy.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B33CDB@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4DCB1AAB.4050904@alchemy.com> On 11-May-11 15:54, Prasad, Ramit wrote: >> Core windows commands don't generally accept it, including native >> Windows applications (although sometimes they're lenient in what they >> accept). It'll work for command-line Python script usage because it's >> *python* that allows them, not *windows*. > > They work in *Windows* command prompt natively. Respectfully, I think you aren't clear on how command line execution works. Hopefully I can help a little (yes, there are enough cases where it'll bite you that it's good to know this). > Some apps do not work well that is true, but the reason that theywork like this with Python is NOT because Python allows it but because Windows does. I highly doubt Python checks for "/" and converts it to "\\" (or does any complicated checking of file strings). YMMV for apps, but I have never had a problem with '/' on the command prompt. It is an important caveat to note that this behavior is not Guaranteed. Actually, yes, that's exactly what Python (or actually the underlying file handling libraries it's built with) is doing on Windows. There is a decades-long tradition of C compilers (et al) doing this conversion for the sake of all the ported Unix C programs that people wanted to run on Windows (or, at the time, MSDOS). If Windows natively supported it, then you could do this: C:\> DIR /users/fred/desktop C:\> DEL /temp/myfile Or try running your Python program like C:\> /python27/python.exe scriptname.py That doesn't work either, because Windows is NOT in any way at all interpreting the / characters. So why does this work: C:\> myscript.py /temp/myfile /users/fred/desktop or even C:\> \python27\python.exe myscript.py /temp/myfile That works because Windows hands ALL of the argument strings, as-is, with NO interpretation, to the application to deal with. In this case, the application is Python, and Python is going to the extra work to interpret the / characters as \ characters when you try to use them in open() calls and the like. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From tcl76 at hotmail.com Thu May 12 04:51:11 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 12 May 2011 02:51:11 +0000 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: , , , Message-ID: excellent it works. tq Date: Wed, 11 May 2011 14:58:39 +0100 Subject: Re: [Tutor] create an xls file using data from a txt file From: wprins at gmail.com To: tcl76 at hotmail.com CC: taxbotsis at gmail.com; tutor at python.org On 11 May 2011 14:34, tee chwee liong wrote: hi all, thanks for this sharing. when i copy and run this code, i got this error: Traceback (most recent call last): File "C:/Python25/myscript/excel/sampleexcel.py", line 1, in import csv File "C:/Python25/myscript/excel\csv.py", line 3, in w=csv.writer(open('output.csv','w')) AttributeError: 'module' object has no attribute 'writer' Well, reading the error message, it's saying that module "csv", coming from file "C:/Python25/myscript/excel\ csv.py" has no member "writer". So, it seems you've called your test script (module) "csv" which effecitvely hid the standard python "csv" module. Try renaming your script file to something else ('testcsv.py' maybe) so its name doesn't conflict with the standard "csv" module and try again. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu May 12 11:25:56 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 May 2011 11:25:56 +0200 Subject: [Tutor] create an xls file using data from a txt file References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> <4DCAE7F5.2020304@alchemy.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B33CDB@EMARC112VS01.exchad.jpmchase.net> <4DCB1AAB.4050904@alchemy.com> Message-ID: Steve Willoughby wrote: > On 11-May-11 15:54, Prasad, Ramit wrote: >>> Core windows commands don't generally accept it, including native >>> Windows applications (although sometimes they're lenient in what they >>> accept). It'll work for command-line Python script usage because it's >>> *python* that allows them, not *windows*. >> >> They work in *Windows* command prompt natively. > > Respectfully, I think you aren't clear on how command line execution > works. Hopefully I can help a little (yes, there are enough cases where > it'll bite you that it's good to know this). > >> Some apps do not work well that is true, but the reason that theywork >> like this with Python is NOT because Python allows it but because > Windows does. I highly doubt Python checks for "/" and converts it to > "\\" (or does any complicated checking of file strings). YMMV for apps, > but I have never had a problem with '/' on the command prompt. It is an > important caveat to note that this behavior is not Guaranteed. > > Actually, yes, that's exactly what Python (or actually the underlying > file handling libraries it's built with) is doing on Windows. There is > a decades-long tradition of C compilers (et al) doing this conversion > for the sake of all the ported Unix C programs that people wanted to run > on Windows (or, at the time, MSDOS). > > If Windows natively supported it, then you could do this: > > C:\> DIR /users/fred/desktop > C:\> DEL /temp/myfile > > Or try running your Python program like > > C:\> /python27/python.exe scriptname.py > > That doesn't work either, because Windows is NOT in any way at all > interpreting the / characters. > > So why does this work: > > C:\> myscript.py /temp/myfile /users/fred/desktop > > or even > > C:\> \python27\python.exe myscript.py /temp/myfile > > That works because Windows hands ALL of the argument strings, as-is, > with NO interpretation, to the application to deal with. In this case, > the application is Python, and Python is going to the extra work to > interpret the / characters as \ characters when you try to use them in > open() calls and the like. > The following suggests otherwise: """ Note File I/O functions in the Windows API convert "/" to "\" as part of converting the name to an NT-style name, except when using the "\\?\" prefix as detailed in the following sections. """ (Found at http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx ) From mail at timgolden.me.uk Thu May 12 11:40:17 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 12 May 2011 10:40:17 +0100 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> <4DCAE7F5.2020304@alchemy.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B33CDB@EMARC112VS01.exchad.jpmchase.net> <4DCB1AAB.4050904@alchemy.com> Message-ID: <4DCBAB01.9000309@timgolden.me.uk> To confirm: Python does *nothing* to convert automatically from one form of path separator to another. Windows from very early on, has accepted /-slashes as path separators to API calls. Where they don't work is: at the command shell itself presumably since slashes are commonly used to introduce options; and, sometimes, the Windows Shell API although I can't lay my hands on an example at the moment. If you were to write something in C to call CreateFile and pass a path such as "c:/temp/temp.txt" it would work without a problem because the Windows API accepts those kinds of paths. TJG From alexsmith24871 at yahoo.com Thu May 12 13:34:52 2011 From: alexsmith24871 at yahoo.com (Alex Smith) Date: Thu, 12 May 2011 12:34:52 +0100 (BST) Subject: [Tutor] Just Joined! Message-ID: <474818.35829.qm@web132305.mail.ird.yahoo.com> Hi All, I just joined this list and am really new to python. I have an assignment to create a function with (a_string, width) which returns the a_string with all the lower case characters changed to upper case characters and vice versa and centered; was wondering if someone could point me in the right direction. I am not just asking for the answer but just need a few tips to get started. So far I do know I should use the dir(str) and do not quite understand what the "width" option is used for.... >>> help(dir) Help on built-in function dir in module __builtin__: dir(...) ?? ?dir([object]) -> list of strings ?? ? ?? ?Return an alphabetized list of names comprising (some of) the attributes ?? ?of the given object, and of attributes reachable from it: ?? ? ?? ?No argument: ?the names in the current scope. ?? ?Module object: ?the module attributes. ?? ?Type or class object: ?its attributes, and recursively the attributes of ?? ? ? ?its bases. ?? ?Otherwise: ?its attributes, its class's attributes, and recursively the ?? ? ? ?attributes of its class's base classes. def SwapcaseAndCenter(dir,??) Thanks for any advice! -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu May 12 14:02:33 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 12 May 2011 13:02:33 +0100 Subject: [Tutor] Just Joined! In-Reply-To: <474818.35829.qm@web132305.mail.ird.yahoo.com> References: <474818.35829.qm@web132305.mail.ird.yahoo.com> Message-ID: On 12 May 2011 12:34, Alex Smith wrote: > Hi All, > > I just joined this list and am really new to python. I have an assignment > to create a function with (a_string, width) which returns the a_string with > all the lower case characters changed to upper case characters and vice > versa and centered; was wondering if someone could point me in the right > direction. I am not just asking for the answer but just need a few tips to > get started. So far I do know I should use the dir(str) > and do not quite understand what the "width" option is used for.... > > I think you're missing the point about the suggestion to use dir() -- as per the help you yourself retrieved, dir returns "an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it..." The suggestion to do dir(str) was intended as a way to learn about how string objects work in Python, not that it should be used directly in the source code of your solution. For example, "dir(str)" lists an interesting attribute (in this case a method) called "swapcase"... now investigating this by doing "help(str.swapcase)" you get: >>> help(str.swapcase) Help on method_descriptor: swapcase(...) S.swapcase() -> string Return a copy of the string S with uppercase characters converted to lowercase and vice versa. Sounds relevant to your goals. ;) As for the "width" question, think about the requirement to "center" the string. Centered with reference to what? How are you going to center something if you don't know how wide the thing you're centering on, is? Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu May 12 14:05:32 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 12 May 2011 07:05:32 -0500 Subject: [Tutor] Just Joined! In-Reply-To: <474818.35829.qm@web132305.mail.ird.yahoo.com> References: <474818.35829.qm@web132305.mail.ird.yahoo.com> Message-ID: On Thu, May 12, 2011 at 6:34 AM, Alex Smith wrote: > Hi All, > > I just joined this list and am really new to python. > Hi! Welcome to the Python tutor list, and Python! > I have an assignment to create a function with (a_string, width) which > returns the a_string with all the lower case characters changed to upper > case characters and vice versa and centered; was wondering if someone could > point me in the right direction. I am not just asking for the answer but > just need a few tips to get started. > That's good, because that's our policy here ;) > So far I do know I should use the dir(str) > I think you might be a little confused as to what dir actually does, or maybe what your assignment is really asking! > and do not quite understand what the "width" option is used for.... > Since you said the text is supposed to be centered, I suspect it means the final width of the string... > >>> help(dir) > > Return an alphabetized list of names comprising (some of) the attributes > of the given object, and of attributes reachable from it: > So dir gives you the attributes of an object. In this case since you're playing with a string you want to take a look at string objects. What happens when you run dir(str)? What happens when you run dir('this is a string')? > > def SwapcaseAndCenter(dir,??) > The best way to understand what an assignment is asking is usually to have an example - and if you don't have an example, make one up! So I suspect your teacher might want something like this: (I'm replacing spaces with 'x' so you can see them. It's a good thing to do while you're testing) >>> SwapcaseAndCenter('a', 3) 'xAx' >>> SwapcaseAndCenter('hello', 10) 'xxHELLOxxx' >>> SwapcaseAndCenter('WeIrD', 12) 'xxxwEiRdxxxx' I suspect if you look carefully at the output of the dir commands that I mentioned above, you will find some help. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexsmith24871 at yahoo.com Thu May 12 14:57:48 2011 From: alexsmith24871 at yahoo.com (Alex Smith) Date: Thu, 12 May 2011 13:57:48 +0100 (BST) Subject: [Tutor] Just Joined! In-Reply-To: References: <474818.35829.qm@web132305.mail.ird.yahoo.com> Message-ID: <645152.57206.qm@web132309.mail.ird.yahoo.com> Thank you both for the quick replies! So I understand now dir is just used to assist in finding relevant strings.?wapcaseAndCenter('hello', 10) I don't understand how from your example you get an output from :?SwapcaseAndCenter('hello', 10) I get the below error: Traceback (most recent call last): ??File "", line 1, in ?? ?SwapcaseAndCenter('hello', 10) NameError: name 'SwapcaseAndCenter' is not defined So i started thinking the string used is "swapcase" and "center" although I still get an error with that input: >>> swapcase.center('hello',10) Traceback (most recent call last): ??File "", line 1, in ?? ?swapcase.center('hello',10) TypeError: an integer is required ________________________________ From: Wayne Werner To: Alex Smith Cc: "tutor at python.org" Sent: Thursday, 12 May 2011, 5:05 Subject: Re: [Tutor] Just Joined! On Thu, May 12, 2011 at 6:34 AM, Alex Smith wrote: Hi All,? ? I just joined this list and am really new to python. Hi! Welcome to the Python tutor list, and Python! ? I have an assignment to create a function with (a_string, width) which returns the a_string with all the lower case characters changed to upper case characters and vice versa and centered; was wondering if someone could point me in the right direction. I am not just asking for the answer but just need a few tips to get started. That's good, because that's our policy here ;) ? So far I do know I should use the dir(str) I think you might be a little confused as to what dir actually does, or maybe what your assignment is really asking!? ? and do not quite understand what the "width" option is used for.... Since you said the text is supposed to be centered, I suspect it means the final width of the string... ? >>> help(dir) >? ? ?Return an alphabetized list of names comprising (some of) the attributes >?? ?of the given object, and of attributes reachable from it: So dir gives you the attributes of an object. In this case since you're playing with a string you want to take a look at string objects. What happens when you run dir(str)? What happens when you run dir('this is a string')? ? > >def SwapcaseAndCenter(dir,??) The best way to understand what an assignment is asking is usually to have an example - and if you don't have an example, make one up! So I suspect your teacher might want something like this: (I'm replacing spaces with 'x' so you can see them. It's a good thing to do while you're testing) >>> SwapcaseAndCenter('a', 3) 'xAx' >>> SwapcaseAndCenter('hello', 10) 'xxHELLOxxx' >>> SwapcaseAndCenter('WeIrD', 12) 'xxxwEiRdxxxx' I suspect if you look carefully at the output of the dir commands that I mentioned above, you will find some help. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Thu May 12 15:10:18 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 12 May 2011 13:10:18 +0000 Subject: [Tutor] cpython Message-ID: hi all, i just started python but i'm hearing there is cpython. what is it different from python? is there any tutorials i can refer. thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Thu May 12 15:15:19 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 12 May 2011 14:15:19 +0100 Subject: [Tutor] cpython In-Reply-To: References: Message-ID: <4DCBDD67.5050004@timgolden.me.uk> On 12/05/2011 14:10, tee chwee liong wrote: > hi all, > > i just started python but i'm hearing there is cpython. what is it > different from python? is there any tutorials i can refer. CPython is just the most common version of Python, so-called because it's written in C: the one you download from python.org. It's normally only called "Cpython" to distinguish it if needed from other implementations, such as Jython (Java-based), IronPython (.NET-based), PyPy (Python-based) and others. TJG From izzaddin.ruhulessin at gmail.com Thu May 12 15:18:40 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Thu, 12 May 2011 15:18:40 +0200 Subject: [Tutor] cpython In-Reply-To: References: Message-ID: Hi, CPython is the C implementation of Python. You can read the tutorial in the Python docs. It is a rather advanced topic, however. If you nevertheless want to delve into it, it might be a good idea to check out www.cython.org first. 2011/5/12 tee chwee liong > hi all, > > i just started python but i'm hearing there is cpython. what is it > different from python? is there any tutorials i can refer. > > thanks > tcl > > _______________________________________________ > 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 tcl76 at hotmail.com Thu May 12 15:20:35 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 12 May 2011 13:20:35 +0000 Subject: [Tutor] cpython In-Reply-To: References: , Message-ID: thanks for your advice. let me check it out. Date: Thu, 12 May 2011 15:18:40 +0200 Subject: Re: [Tutor] cpython From: izzaddin.ruhulessin at gmail.com To: tcl76 at hotmail.com CC: tutor at python.org Hi, CPython is the C implementation of Python. You can read the tutorial in the Python docs. It is a rather advanced topic, however. If you nevertheless want to delve into it, it might be a good idea to check out www.cython.org first. 2011/5/12 tee chwee liong hi all, i just started python but i'm hearing there is cpython. what is it different from python? is there any tutorials i can refer. thanks tcl _______________________________________________ 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 ramit.prasad at jpmchase.com Thu May 12 15:27:00 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 12 May 2011 09:27:00 -0400 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: <4DCB1AAB.4050904@alchemy.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> <4DCAE7F5.2020304@alchemy.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B33CDB@EMARC112VS01.exchad.jpmchase.net> <4DCB1AAB.4050904@alchemy.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B3405C@EMARC112VS01.exchad.jpmchase.net> >Respectfully, I think you aren't clear on how command line execution >works. Hopefully I can help a little (yes, there are enough cases where >it'll bite you that it's good to know this). True >If Windows natively supported it, then you could do this: >C:\> DIR /users/fred/desktop >C:\> DEL /temp/myfile >Or try running your Python program like >C:\> /python27/python.exe scriptname.py >That doesn't work either, because Windows is NOT in any way at all >interpreting the / characters. > C:\> /python27/python.exe scriptname.py Oh, really? Works for me. C:\>/Python31/python.exe /temp/test.py File "/temp/test.py", line 1 print 'Hello World' ^ SyntaxError: invalid syntax True that does not work for dir and del because both use '/' as the argument passing prefix, but that does not mean that Windows cannot handle it. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: Steve Willoughby [mailto:steve at alchemy.com] Sent: Wednesday, May 11, 2011 6:24 PM To: Prasad, Ramit; tutor at python.org Subject: Re: [Tutor] create an xls file using data from a txt file On 11-May-11 15:54, Prasad, Ramit wrote: >> Core windows commands don't generally accept it, including native >> Windows applications (although sometimes they're lenient in what they >> accept). It'll work for command-line Python script usage because it's >> *python* that allows them, not *windows*. > > They work in *Windows* command prompt natively. > Some apps do not work well that is true, but the reason that theywork like this with Python is NOT because Python allows it but because Windows does. I highly doubt Python checks for "/" and converts it to "\\" (or does any complicated checking of file strings). YMMV for apps, but I have never had a problem with '/' on the command prompt. It is an important caveat to note that this behavior is not Guaranteed. Actually, yes, that's exactly what Python (or actually the underlying file handling libraries it's built with) is doing on Windows. There is a decades-long tradition of C compilers (et al) doing this conversion for the sake of all the ported Unix C programs that people wanted to run on Windows (or, at the time, MSDOS). If Windows natively supported it, then you could do this: C:\> DIR /users/fred/desktop C:\> DEL /temp/myfile Or try running your Python program like C:\> /python27/python.exe scriptname.py That doesn't work either, because Windows is NOT in any way at all interpreting the / characters. So why does this work: C:\> myscript.py /temp/myfile /users/fred/desktop or even C:\> \python27\python.exe myscript.py /temp/myfile That works because Windows hands ALL of the argument strings, as-is, with NO interpretation, to the application to deal with. In this case, the application is Python, and Python is going to the extra work to interpret the / characters as \ characters when you try to use them in open() calls and the like. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From cfuller084 at thinkingplanet.net Thu May 12 15:25:49 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 12 May 2011 08:25:49 -0500 Subject: [Tutor] cpython In-Reply-To: References: Message-ID: <201105120825.51000.cfuller084@thinkingplanet.net> CPython refers to the main implementation, which is written in C. There are a bunch of different implementations, such as IronPython for .NET or Jython for the Java Virtual Machine. There's also Cython (subtle spelling difference), which you can use to combine C and Python code. It isn't quite an implementation in the same sense, but it's close. Most folk use CPython, and it's what we discuss on this list, unless otherwise specified. http://www.python.org/getit/ http://cython.org/ Cheers On Thursday 12 May 2011, tee chwee liong wrote: > hi all, > > i just started python but i'm hearing there is cpython. what is it > different from python? is there any tutorials i can refer. > > thanks > tcl From susana.delgado_s at utzmg.edu.mx Thu May 12 16:34:57 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Thu, 12 May 2011 09:34:57 -0500 Subject: [Tutor] ImportError: Module use of python25.dll conflicts with this version of Python. Message-ID: Hello list! I just started working with a dll fro geospatial data, it uses Python to analyze data, this package is OSGeo4W; when I run the script and got the next error: >>> import mapnik Traceback (most recent call last): File "", line 1, in File "C:\OSGeo4W\apps\Python25\lib\site-packages\mapnik\__init__.py", line 42, in from _mapnik import * ImportError: Module use of python25.dll conflicts with this version of Python. I'm using Python 2.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Thu May 12 17:37:19 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 12 May 2011 08:37:19 -0700 Subject: [Tutor] create an xls file using data from a txt file In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B336E4@EMARC112VS01.exchad.jpmchase.net> <4DCAE7F5.2020304@alchemy.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3B33CDB@EMARC112VS01.exchad.jpmchase.net> <4DCB1AAB.4050904@alchemy.com> Message-ID: <4DCBFEAF.9000501@alchemy.com> Maybe we're splitting hairs over semantics then. I thought there was confusion about what the CLI shell was doing with file separators as opposed to just handing the arguments as-is to the applications (which is true... the CLI doesn't really process them much, it's up to the application. Where in the application, though, this is dealt with is not where I think we disagree. In my original response, I clarified that, although as a short parenthetical note: On 12-May-11 02:25, Peter Otten wrote: > Steve Willoughby wrote: >> Actually, yes, that's exactly what Python (or actually the underlying >> file handling libraries it's built with) is doing on Windows. There is the "underlying file handling libraries" would be the API calls. But that's not the CLI shell's doing. Although maybe that's what you meant all along. There are enough difference between the way the Windows CLI shell and Unix-derived command shells function in the handling of files and option handling that there's often confusion there which I thought was what was happening here too, that the OP was saying the CLI was somehow doing the translation. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From alan.gauld at btinternet.com Thu May 12 19:17:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 May 2011 18:17:28 +0100 Subject: [Tutor] Just Joined! References: <474818.35829.qm@web132305.mail.ird.yahoo.com> <645152.57206.qm@web132309.mail.ird.yahoo.com> Message-ID: "Alex Smith" wrote > SwapcaseAndCenter('hello', 10) I don't understand how from > your example you get an output > ...I get the below error: > > NameError: name 'SwapcaseAndCenter' is not defined Wayne was showing how it should work. As Python says the function is not defined yet. Defining the function so that is does do what Wayne showed is your homework! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 12 19:23:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 May 2011 18:23:40 +0100 Subject: [Tutor] ImportError: Module use of python25.dll conflicts with this version of Python. References: Message-ID: "Susana Iraiis Delgado Rodriguez" wrote > from _mapnik import * > ImportError: Module use of python25.dll conflicts with this version > of > Python. > > I'm using Python 2.6 You will need to find a Python 2.6 version of the DLL or revert your Python version to 2.5. This is always a risk when using third party modules. Ther may not be an updated version to match your Python. If there isn't a 2.6 version you might try asking the maintainer to create a new version, it may well just involve a rebuild for them. But if the maintainer has lost interst, ior its a more complex issue you might be out of luck and have to revert to 2.5. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 12 19:20:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 May 2011 18:20:37 +0100 Subject: [Tutor] cpython References: , Message-ID: "tee chwee liong" wrote > thanks for your advice. let me check it out. If you mean cython I wouldn't bother. Since you are "just starting" in Python reading about cython is more likely to confuse you than help. Cython is great once you really know python (and at least a little C) but I doubt if it will help you get to grips with the basics. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From karim.liateni at free.fr Thu May 12 21:24:37 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 12 May 2011 21:24:37 +0200 Subject: [Tutor] What is the trick ???! Message-ID: <4DCC33F5.1080607@free.fr> Hello See below, I was surprised about finding hidden function in module sys: karim at Requiem4Dream: python2.7 Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.getdefaultencoding() 'ascii' >>> sys.setdefaultencoding() Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'setdefaultencoding' >>> karim at Requiem4Dream:~/build/OpenProcessManager/test python2.7 Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.getdefaultencoding() 'ascii' >>> sys.setdefaultencoding('utf-8') Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'setdefaultencoding' >>> reload(sys) >>> sys.setdefaultencoding('utf-8') >>> sys.getdefaultencoding() 'utf-8' >>> :-\ ??? From karim.liateni at free.fr Thu May 12 21:38:52 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 12 May 2011 21:38:52 +0200 Subject: [Tutor] What is the trick ???! In-Reply-To: <4DCC33F5.1080607@free.fr> References: <4DCC33F5.1080607@free.fr> Message-ID: <4DCC374C.1070801@free.fr> On 05/12/11 21:24, Karim wrote: > > Hello > > See below, I was surprised about finding hidden function in module sys: > > karim at Requiem4Dream: python2.7 > Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> sys.getdefaultencoding() > 'ascii' > >>> sys.setdefaultencoding() > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'setdefaultencoding' > >>> > karim at Requiem4Dream:~/build/OpenProcessManager/test$python2.7 > Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> sys.getdefaultencoding() > 'ascii' > >>> sys.setdefaultencoding('utf-8') > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'setdefaultencoding' > >>> reload(sys) > > >>> sys.setdefaultencoding('utf-8') > >>> sys.getdefaultencoding() > 'utf-8' > >>> > > :-\ ??? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Ok I found the trick at http://docs.python.org/library/sys.html#sys.setdefaultencoding. The function is removed dynamically at startup when reload I get the nominal one (the original). Sorry for the disturb. Cheers Karim From taxbotsis at gmail.com Thu May 12 22:55:25 2011 From: taxbotsis at gmail.com (tax botsis) Date: Thu, 12 May 2011 16:55:25 -0400 Subject: [Tutor] Tkinter progress bar not responding when moved Message-ID: I am trying to use a progress bar for my application and used the following code by Michael Lange ( http://tkinter.unpythonic.net/wiki/ProgressMeter?action=PackagePages). However, the progress bar stops responding when I move it. I haven't modified class declaration and _demo but created my own modified function []: class Meter(Tkinter.Frame): def __init__(self, master, width=300, height=20, bg='white', fillcolor='orchid1',\ value=0.0, text=None, font=None, textcolor='black', *args, **kw): Tkinter.Frame.__init__(self, master, bg=bg, width=width, height=height, *args, **kw) self._value = value self._canv = Tkinter.Canvas(self, bg=self['bg'], width=self['width'], height=self['height'],\ highlightthickness=0, relief='flat', bd=0) self._canv.pack(fill='both', expand=1) self._rect = self._canv.create_rectangle(0, 0, 0, self._canv.winfo_reqheight(), fill=fillcolor,\ width=0) self._text = self._canv.create_text(self._canv.winfo_reqwidth()/2, self._canv.winfo_reqheight()/2,\ text='', fill=textcolor) if font: self._canv.itemconfigure(self._text, font=font) self.set(value, text) self.bind('', self._update_coords) def _update_coords(self, event): '''Updates the position of the text and rectangle inside the canvas when the size of the widget gets changed.''' # looks like we have to call update_idletasks() twice to make sure # to get the results we expect self._canv.update_idletasks() self._canv.coords(self._text, self._canv.winfo_width()/2, self._canv.winfo_height()/2) self._canv.coords(self._rect, 0, 0, self._canv.winfo_width()*self._value, self._canv.winfo_height()) self._canv.update_idletasks() def get(self): return self._value, self._canv.itemcget(self._text, 'text') def set(self, value=0.0, text=None): #make the value failsafe: if value < 0.0: value = 0.0 elif value > 1.0: value = 1.0 self._value = value if text == None: #if no text is specified use the default percentage string: text = str(int(round(100 * value))) + ' %' self._canv.coords(self._rect, 0, 0, self._canv.winfo_width()*value, self._canv.winfo_height()) self._canv.itemconfigure(self._text, text=text) self._canv.update_idletasks() def _demo(meter, value): meter.set(value) if value < 1.0: value = value + 0.005 meter.after(50, lambda: _demo(meter, value)) else: meter.set(value, 'TM completed - Please close this window') # this is where progress bar is loaded and where I have added my own stuff def test(): if __name__ == '__main__': root2 = Tkinter.Tk(className=' Text Mining Progress') m = Meter(root2, relief='ridge', bd=3) m.pack(fill='x') i=0.0 for fileid in reader.fileids(): m.set(i, 'Processing will take a few minutes...') i=i+1.000/len(reader.fileids()) # here I increment the colored bar in each iteration m.after(1000, lambda: _demo(m, i)) print str(fileid)[:-4],document_features(reader.raw(fileid))# I call some other processes here root2.withdraw() Thanks Tax -------------- next part -------------- An HTML attachment was scrubbed... URL: From lan.rogers.book at gmail.com Fri May 13 02:20:40 2011 From: lan.rogers.book at gmail.com (Lan Rogers) Date: Thu, 12 May 2011 17:20:40 -0700 Subject: [Tutor] Automatic updates for a program? Message-ID: So I have a program I want to release, but it's still in early stages without some of its planned functionality. I want to distribute automatic updates. I'm working under the assumption that the easiest way to do this is to just replace the old files with the new ones. My questions is this: How do I replace a script that is running, with a new version? From alan.gauld at btinternet.com Fri May 13 09:38:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 May 2011 08:38:18 +0100 Subject: [Tutor] Automatic updates for a program? References: Message-ID: "Lan Rogers" wrote > So I have a program I want to release, but it's still in early > stages > without some of its planned functionality. I want to distribute > automatic updates. Don't assume this will be easy, and be prepared for it to cramp your style when it comes to designing and developing the app. It will place major restrictions on what you can do. Only do it if its essential. > I'm working under the assumption that the easiest > way to do this is to just replace the old files with the new ones. A lot depends on which OS you are using. If its Windows thre are a bunch of other things you will probably need to do too, like update registry entries and mess about with COM IDs etc. > questions is this: How do I replace a script that is running, with a > new version? Again it depends on the OS. It may not be possible, you may have to force a restart. Thats by far the easiest way. On Windows its common to do it on the next reboot by setting up a RunOnce job in the registry. (But that only works well because Windows tends to need rebooting a lot!) You might also want to consider whwether you need a backout strategy to revert to a previous working version. That will complicate things even more. OTOH If your program architecture is very simple, just a few scripts in a single folder and not using the OS features or a database or networking then many of these complexities can be avoided. (But replacing a running process is still tricky. You need to build the functionality into the existing code to replace itself - typically using spawn() or exec() or fork() assuming Linux/MacOS - and then triggger that functionality from your installer) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From aznjonn at me.com Fri May 13 12:57:00 2011 From: aznjonn at me.com (Johnson Tran) Date: Fri, 13 May 2011 03:57:00 -0700 Subject: [Tutor] Just Joined! In-Reply-To: References: <474818.35829.qm@web132305.mail.ird.yahoo.com> <645152.57206.qm@web132309.mail.ird.yahoo.com> Message-ID: Okay I think I understand now. Is there a module i need to import though when defining ?I did a help("module"), not sure which module is the correct one to make swapcase.center work properly... On May 12, 2011, at 10:17 AM, Alan Gauld wrote: > > "Alex Smith" wrote >> SwapcaseAndCenter('hello', 10) I don't understand how from your example you get an output ...I get the below error: >> NameError: name 'SwapcaseAndCenter' is not defined > > Wayne was showing how it should work. As Python says the function is not defined yet. > > Defining the function so that is does do what Wayne showed is your homework! :-) > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From aznjonn at me.com Fri May 13 13:07:56 2011 From: aznjonn at me.com (Johnson Tran) Date: Fri, 13 May 2011 04:07:56 -0700 Subject: [Tutor] Just Joined! In-Reply-To: References: <474818.35829.qm@web132305.mail.ird.yahoo.com> <645152.57206.qm@web132309.mail.ird.yahoo.com> Message-ID: You can ignore last question, was trying to figure out Alex's issue as well, but I got it now. sorry for the spam! On May 13, 2011, at 3:57 AM, Johnson Tran wrote: > Okay I think I understand now. Is there a module i need to import though when defining ?I did a help("module"), not sure which module is the correct one to make swapcase.center work properly... > > > On May 12, 2011, at 10:17 AM, Alan Gauld wrote: > >> >> "Alex Smith" wrote >>> SwapcaseAndCenter('hello', 10) I don't understand how from your example you get an output ...I get the below error: >>> NameError: name 'SwapcaseAndCenter' is not defined >> >> Wayne was showing how it should work. As Python says the function is not defined yet. >> >> Defining the function so that is does do what Wayne showed is your homework! :-) >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From evosweet at hotmail.com Fri May 13 20:36:07 2011 From: evosweet at hotmail.com (Rayon) Date: Fri, 13 May 2011 14:36:07 -0400 Subject: [Tutor] python file upload Message-ID: Hi all, I need a python script to upload a xml file to a web page using python. I have tried using pycurl but I am still getting errors. import urllib2 import pycurl data=""" gtt_admin Password2011 2001-11-15T13:18:08-08:00 738002000417469 Enterprise B """ headers = ["Content-Type:text/xml"] #data = open("d:\\dump\\activation.xml") c = pycurl.Curl() c.setopt(c.URL, "https://provisioning.etr.blackberry.net/ari/submitXML") c.setopt(pycurl.POST,1) c.setopt(pycurl.SSL_VERIFYPEER, 0) c.setopt(pycurl.SSL_VERIFYHOST, 0) c.setopt(pycurl.HTTPHEADER, headers) c.setopt(pycurl.POSTFIELDS, data) c.setopt(c.VERBOSE, 1) c.perform() c.close() this is the error I am getting. * About to connect() to provisioning.etr.blackberry.net port 443 (#0) * Trying 216.9.243.178... * connected * Connected to provisioning.etr.blackberry.net (216.9.243.178) port 443 (#0) * libcurl is now using a weak random seed! * SSL connection using RC4-MD5 * Server certificate: * subject: C=CA; ST=Ontario; L=Waterloo; O=Research In Motion Limited; OU=IT; CN=provisioning.etr.blackberry.net * start date: 2011-03-28 00:00:00 GMT * expire date: 2012-03-27 23:59:59 GMT * issuer: C=US; O=Thawte, Inc.; CN=Thawte SSL CA * SSL certificate verify result: self signed certificate in certificate chain (19), continuing anyway. > POST /ari/submitXML HTTP/1.1 User-Agent: PycURL/7.19.7 Host: provisioning.etr.blackberry.net Accept: */* Content-Type:text/xml Content-Length: 836 < HTTP/1.1 500 Internal Server Error < Connection: close < Date: Fri, 13 May 2011 18:35:24 GMT < Content-Length: 90 < Content-Type: text/html < X-Powered-By: Servlet/2.5 JSP/2.1 < * Closing connection #0 ERROR_ID=PARSEING_ERROR DESCRIPTION=Request parsing failed: Tag in line:2 Ending column:6 Regards Rayon -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Sat May 14 01:49:34 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Fri, 13 May 2011 16:49:34 -0700 Subject: [Tutor] short url processor Message-ID: <4DCDC38E.4070508@iandouglas.com> Hey folks, I'm rewriting a short url processor for my job. I had originally written it as a multi-threaded Perl script, which works, but has socket problems causing memory leaks. Since I'm rebuilding it to use memcache, and since I was learning Python outside of work anyway, figured I'd rewrite it in Python. I'm using BaseHTTPServer, overriding do_GET and do_POST, and want to set up a custom logging mechanism so I don't have to rewrite a separate log parser, which I'll eventually rewrite in Python as well. The problem I'm having, though, is that the BaseHTTPServer setup is outputting what appears to be an apache-style log to STDOUT, but the logging.debug or logging.info calls I make in the code are also going to STDOUT despite my attempt to use logging.basicConfig() overrides and setting a filename, etc. Here's the basics of what I'm doing. Forgive my code, I've already been told it's "ugly", I'm new to Python and come from a background of Perl/PHP. import struct import string,cgi,time import psycopg import logging import re import memcache from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from time import strftime,localtime class clientThread(BaseHTTPRequestHandler): def log_my_request(self,method,request,short_url,http_code,long_url,cached,notes): logging.debug("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s", self.client_address[0], time.strftime("%Y-%m-%d %H:%M:%S",localtime()), method, # get or post request, # requested entity short_url, # matching short_url based on entity, if any http_code, # 200, 301, 302, 404, etc long_url, # url to redirect to, if there was one cached, # 'hit', 'miss', 'miss-db', 'error' notes # extra notes for the log file only ) return def do_GET(self) # logic goes here for finding a short url form memcache, then writing the appropriate # output data to the socket, then logging happens: self.log_my_request(getpost,orig_short_url,short_url,'302',long_url,'hit','') return def main(): if mc.get('dbcheck'): # memcache already has some data print("memcache already primed with data") else: # nothing in memcache, so load it up from database print('Connecting to PG') cur.execute("SELECT count(*) FROM short_urls") ; mycount = cur.fetchone() ; print("fetching %s entries", mycount) cur.execute("SELECT short_url,long_url FROM short_urls") giant_list = cur.fetchall() # cache a marker that tells us we've already initialized memcache with db data mc.set('dbcheck','databasetest',0) # I'm sure there's a MUCH more efficient way of doing this ... multi-set of some sort? for i in giant_list: if i[0]: if i[1]: mc.set(i[0], i[1]) print("finished retrieving %s entries plus set up a new dictionary with all values" % mycount) #{{ set up the socket, bind to port, and wait for incoming connections try: server = HTTPServer(('',8083), clientThread) print 'short url processing has begun' # this is where I try to tell Python that I only want my message in my log: # no INFO:username prefix, etc., and also to write it to a file logging.basicConfig(level=logging.DEBUG) logging.basicConfig(format='%(message)s', filename='/tmp/ian.txt') server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close() My code runs without any errors, though I have left some code out of this Email that I didn't feel was relevant such as the logic of seeing if a short url exists in memcache, trying to fetch from the db if there was no match, and if the db lookup also fails, force-deleting short urls from memcache based on other instructions, that sort of thing. None of it deals with logging or the BaseHTTPServer code. To recap, the code runs, redirects are working, but ALL output goes to STDOUT. I can understand that print statements would go to STDOUT, but the BaseHTTPServer seems to want to write the Apache-style log to STDOUT, and my logging.info() call also prints to STDOUT instead of my file. I'd love to hear any thoughts from people that have had to deal with this. The logging is the last piece of the puzzle for me. Thanks, Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat May 14 01:54:43 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 14 May 2011 00:54:43 +0100 (BST) Subject: [Tutor] Fw: Automatic updates for a program? In-Reply-To: References: Message-ID: <217907.35210.qm@web86701.mail.ird.yahoo.com> Forwarding to list for wider feedback. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Forwarded Message ---- From: Lan Rogers To: Alan Gauld Sent: Friday, 13 May, 2011 22:46:41 Subject: Re: [Tutor] Automatic updates for a program? On Fri, May 13, 2011 at 12:38 AM, Alan Gauld wrote: >> So I have a program I want to release, but it's still in early stages >> without some of its planned functionality. I want to distribute >> automatic updates. > > Don't assume this will be easy, and be prepared for it to > cramp your style when it comes to designing and > developing the app. It will place major restrictions on > what you can do. Only do it if its essential. I assume there will be some challenges involved, it's not absolutely critical, but it's something I'd like to understand even if I don't incorporate it into my current project. >> I'm working under the assumption that the easiest >> way to do this is to just replace the old files with the new ones. > > A lot depends on which OS you are using. > If its Windows thre are a bunch of other things > you will probably need to do too, like update > registry entries and mess about with COM IDs etc. > >> questions is this: How do I replace a script that is running, with a >> new version? > > Again it depends on the OS. It may not be possible, > you may have to force a restart. Thats by far the easiest way. > On Windows its common to do it on the next reboot > by setting up a RunOnce job in the registry. (But that > only works well because Windows tends to need > rebooting a lot!) > > You might also want to consider whwether you need a > backout strategy to revert to a previous working version. > That will complicate things even more. > > OTOH If your program architecture is very simple, > just a few scripts in a single folder and not using > the OS features or a database or networking then > many of these complexities can be avoided. (But > replacing a running process is still tricky. You > need to build the functionality into the existing > code to replace itself - typically using spawn() > or exec() or fork() assuming Linux/MacOS - and > then triggger that functionality from your installer) I'm working on windows, and I distribute a single executable file, made with py2exe. I'm not sure if that simplifies things or complicates them. I'm thinking of writing batch script that will handle deleting and and replacing the old version of my application (via restart and RunOnce job, like you mentioned), then deleting that script on the first execution of the new version of my application. Does that sound reasonable or am I kidding myself? -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Sat May 14 01:41:06 2011 From: carroll at tjc.com (Terry Carroll) Date: Fri, 13 May 2011 16:41:06 -0700 (PDT) Subject: [Tutor] Overriding a method in a class Message-ID: I have a pretty basic point of confusion that I'm hoping I can have explained to me. I have a class in which I want to override a method, and have my method defined externally to the class definition invoked instead. But when I do so, my external method is invoked with a different argument signature than the method it overrides. (I'll illustrate with a toy example named toy.py that maintains a list of strings; the actual use case is a wxPython drag-and-drop shell that I find I keep re-using over and over, so I decided to try to turn it into a general-purpose module for my own use.) ### example 1 begin class Thing(object): def __init__(self): self.stuff = [] def addstuff(self, text): self.add_the_stuff(text) def add_the_stuff(self, s1): self.stuff.append(s1) A = Thing() A.addstuff("ABCDEFG") print A.stuff ### example 1 end So far, this works as expected. addstuff invokes add_the_stuff; and the line "print A.stuff" prints out as ['ABCDEFG'], as expected. Now, here's where I am getting befuddled, with the following additional lines: ### example, continued def addlower(self, s2): self.stuff.append(s2.lower()) # add it as lower case B = Thing() B.add_the_stuff=addlower B.addstuff("WXYZ") print B.stuff ### end My *intent* here is to patch the Thing object named B so that the B's add_the_stuff method is replaced with this additional addlower method that I define external to the object. My expectation would be that, just as add_the_stuff method was called with two arguments (self and the string), the patched-in addlower would also get called the same way. What I *expect* is to see ['abcdefg'] printed. What I get is: Traceback (most recent call last): File "E:\Personal\py\DragDrop\toy.py", line 22, in B.addstuff("WXYZ") File "E:\Personal\py\DragDrop\toy.py", line 7, in addstuff self.add_the_stuff(text) TypeError: addlower() takes exactly 2 arguments (1 given) I'm assuming I'm missing some fundamental concept. What is it? From alan.gauld at btinternet.com Sat May 14 02:03:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 May 2011 01:03:06 +0100 Subject: [Tutor] short url processor References: <4DCDC38E.4070508@iandouglas.com> Message-ID: "ian douglas" wrote > outputting what appears to be an apache-style log to STDOUT, but the > logging.debug or logging.info calls I make in the code are also > going to > STDOUT despite my attempt to use logging.basicConfig() overrides and > setting a filename, etc. I don;t know anything about BaseHTTPServer and not much about the logging modules however some thoughts are... How do you know they are going to stdout? Are you sure they aren't going to stderr and stderrr is not mapped to stdout (usually the default). Have you tried redirecting stderr to a file for example? As I say, just some thoughts, Alan G. From carroll at tjc.com Sat May 14 02:09:52 2011 From: carroll at tjc.com (Terry Carroll) Date: Fri, 13 May 2011 17:09:52 -0700 (PDT) Subject: [Tutor] Overriding a method in a class In-Reply-To: References: Message-ID: On Fri, 13 May 2011, Terry Carroll wrote: > What I *expect* is to see ['abcdefg'] printed. What I get is: Sorry, mixed multiple examples; What I had expected was ['wxyz']. Still the same question though. BTW, I forgot to mention: Python 2.7.1, under Windows. (Still not used to the Python 2.x/3.x thing) From knupp at well.com Sat May 14 02:36:08 2011 From: knupp at well.com (David Knupp) Date: Fri, 13 May 2011 17:36:08 -0700 (PDT) Subject: [Tutor] Overriding a method in a class In-Reply-To: References: Message-ID: I think the problem is this bit about overriding an object's internal method with one that is defined externally. My gut feeilng is that you'd now have to explicitly pass the object (i.e., self) as well as the string, i.e.: B.addstuff(B, "WXYZ") ...which seems clunky. I'm not familiar with this particular technique. Is it common to do something like this? On Fri, 13 May 2011, Terry Carroll wrote: > I have a pretty basic point of confusion that I'm hoping I can have explained > to me. I have a class in which I want to override a method, and have my > method defined externally to the class definition invoked instead. But when I > do so, my external method is invoked with a different argument signature than > the method it overrides. > > (I'll illustrate with a toy example named toy.py that maintains a list of > strings; the actual use case is a wxPython drag-and-drop shell that I find I > keep re-using over and over, so I decided to try to turn it into a > general-purpose module for my own use.) > > ### example 1 begin > > class Thing(object): > def __init__(self): > self.stuff = [] > def addstuff(self, text): > self.add_the_stuff(text) > def add_the_stuff(self, s1): > self.stuff.append(s1) > > A = Thing() > A.addstuff("ABCDEFG") > print A.stuff > > ### example 1 end > > So far, this works as expected. addstuff invokes add_the_stuff; and the line > "print A.stuff" prints out as ['ABCDEFG'], as expected. > > Now, here's where I am getting befuddled, with the following additional > lines: > > ### example, continued > def addlower(self, s2): > self.stuff.append(s2.lower()) # add it as lower case > > B = Thing() > B.add_the_stuff=addlower > B.addstuff("WXYZ") > print B.stuff > ### end > > My *intent* here is to patch the Thing object named B so that the B's > add_the_stuff method is replaced with this additional addlower method that I > define external to the object. My expectation would be that, just as > add_the_stuff method was called with two arguments (self and the string), the > patched-in addlower would also get called the same way. > > What I *expect* is to see ['abcdefg'] printed. What I get is: > > Traceback (most recent call last): > File "E:\Personal\py\DragDrop\toy.py", line 22, in > B.addstuff("WXYZ") > File "E:\Personal\py\DragDrop\toy.py", line 7, in addstuff > self.add_the_stuff(text) > TypeError: addlower() takes exactly 2 arguments (1 given) > > I'm assuming I'm missing some fundamental concept. What is it? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From ian.douglas at iandouglas.com Sat May 14 02:42:31 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Fri, 13 May 2011 17:42:31 -0700 Subject: [Tutor] short url processor In-Reply-To: References: <4DCDC38E.4070508@iandouglas.com> Message-ID: <4DCDCFF7.5010005@iandouglas.com> On 05/13/2011 05:03 PM, Alan Gauld wrote: > How do you know they are going to stdout? Are you sure > they aren't going to stderr and stderrr is not mapped to stdout > (usually the default). Have you tried redirecting stderr to a > file for example? > > As I say, just some thoughts, > Thanks for your thoughts, Alan. I had done some testing with cmdline redirects and forget which is was, I think my debug log was going to stdout and the apache-style log was going to stderr, or the other way around... After a handful of guys in the #python IRC channel very nearly convinced me that all but 3 stdlib libraries are utter worthless crap, and telling me to download and use third-party frameworks just to fix a simple logging issue, I overrode log_request() and log message() as such: class clientThread(BaseHTTPRequestHandler): #[[[ def log_request(code, size): return def log_message(self, format, *args): open(LOGFILE, "a").write("%s\n" % (format%args)) ... and now the only logging going on is my own, and it's logged to my external file. Overriding log_request means that BaseHTTPServer no longer outputs its apache-style log, and overriding log_message means my other logging.info() and logging.debug() messages go out to my file as expected. -id -------------- next part -------------- An HTML attachment was scrubbed... URL: From lea-parker at bigpond.com Sat May 14 02:48:51 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Sat, 14 May 2011 10:48:51 +1000 Subject: [Tutor] Help with exceptions please Message-ID: <001201cc11d0$b1912150$14b363f0$@bigpond.com> Hello I have another assignment I am trying to fine tune. The idea is to make sure exceptions work. I have come up with a problem when testing my code. When I enter a golf score for a player the program returns the 'error that has occurred'. I only want it to do this if someone doesn't enter an number. Could I have some comments on my code for the first program of my assignment if you have some time please. """Assignment Question: The Springfork Amateur Golf club has a tournament every weekend. The club president has asked you to write two programs: 1. A program that will read each player's name and golf score as keyboard input and then to save these records in a file named golf.txt. (Each record will have a field name for the player's name and a field for the player's score. 2. A program that reads the records from the golf.txt and displays them.""" def main(): try: # Get the number of players golf_scores = int(raw_input('How many players playing this weekend? ')) # Open a file to hold player names and scores player_data = open('golf.txt', 'w') # Get the players name and score and write it to the file for count in range(1, golf_scores + 1): # Get the name name and score for player print 'Enter the name and score for player #' + str(count) name = raw_input('Name: ') score = int(raw_input('Score: ')) # Write the data as a record to the file golf.txt player_data.write(name + '\n') player_data.write(score + '\n') # Display a blank line print # Close the file player_data.close() print 'Players and their score have been written to golf.txt.' except IOError: print 'An error occured trying to write information to file.' except ValueError: print 'A numberic value must be entered.' except: print 'An error occured.' # Call the main function main() Thanks in advance. Lea -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Sat May 14 02:49:29 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Fri, 13 May 2011 17:49:29 -0700 Subject: [Tutor] short url processor In-Reply-To: References: <4DCDC38E.4070508@iandouglas.com> Message-ID: <4DCDD199.6070605@iandouglas.com> On 05/13/2011 05:03 PM, Alan Gauld wrote: > As I say, just some thoughts, > I *am* curious, Alan, whether you or anyone else on the list are able to help me make this a little more efficient: cur.execute("SELECT short_url,long_url FROM short_urls") giant_list = cur.fetchall() for i in giant_list: if i[0]: if i[1]: mc.set(i[0], i[1]) At present, we have about two million short URL's in our database, and I'm guessing there's a much smoother way of iterating through 2M+ rows from a database, and cramming them into memcache. I imagine there's a map function in there that could be much more efficient? v2 of our project will be to join our short_urls table with its 'stats' table counterpart, to where I only fetch the top 10,000 URLs (or some other smaller quantity). Until we get to that point, I need to speed up the restart time if this script ever needs to be restarted. This is partly why v1.5 was to put the database entries into memcache, so we wouldn't need to reload the db into memory on every restart. Thanks, Ian From carroll at tjc.com Sat May 14 04:57:42 2011 From: carroll at tjc.com (Terry Carroll) Date: Fri, 13 May 2011 19:57:42 -0700 (PDT) Subject: [Tutor] Overriding a method in a class In-Reply-To: References: Message-ID: On Fri, 13 May 2011, David Knupp wrote: > I think the problem is this bit about overriding an object's internal > method with one that is defined externally. Yes, that describes the phenomenon. > My gut feeilng is that you'd > now have to explicitly pass the object (i.e., self) as well as the > string, i.e.: > > B.addstuff(B, "WXYZ") > > ...which seems clunky. But worse, it would mean that you couldn't have the default un-overridden method for those cases where you don't need to override it. > I'm not familiar with this particular technique. Is it common to do > something like this? Certainly the problem is common. For my specific case, I'm going to go with a Plan B of using callbacks; and provide default unbound callbacks present in the module, but not defined in the class itself. But I'd still like to have a better understanding of how the call gets transmuted from a two-argument call to a one-argument call based upon the target. I suspect something along these lines is going on: When a bound method is called, Python inserts a reference to self as an additional first argument, before the other arguments. It does not do this with unbound methods. In my first case, when I created object A, the name add_the_stuff references the bound method add_the_stuff as defined in the Thing class. When add_stuff calls add_the_stuff, because add_the_stuff references a bound method, Python does the automagical insertion of the self argument. In my second case, when I created the object B, the name add_the_stuff *initially* references the bound method add_the_stuff; but then, when I override, I make B.add_the_stuff reference the unbound external method. Now, when addstuff calls add_the_stuff, Python sees that it is referencing an unbound method, and does not insert the self reference into the argument list. Now I'll wait for one of the experts to edify me. > On Fri, 13 May 2011, Terry Carroll wrote: > >> I have a pretty basic point of confusion that I'm hoping I can have >> explained to me. I have a class in which I want to override a method, and >> have my method defined externally to the class definition invoked instead. >> But when I do so, my external method is invoked with a different argument >> signature than the method it overrides. >> >> (I'll illustrate with a toy example named toy.py that maintains a list of >> strings; the actual use case is a wxPython drag-and-drop shell that I find >> I keep re-using over and over, so I decided to try to turn it into a >> general-purpose module for my own use.) >> >> ### example 1 begin >> >> class Thing(object): >> def __init__(self): >> self.stuff = [] >> def addstuff(self, text): >> self.add_the_stuff(text) >> def add_the_stuff(self, s1): >> self.stuff.append(s1) >> >> A = Thing() >> A.addstuff("ABCDEFG") >> print A.stuff >> >> ### example 1 end >> >> So far, this works as expected. addstuff invokes add_the_stuff; and the >> line "print A.stuff" prints out as ['ABCDEFG'], as expected. >> >> Now, here's where I am getting befuddled, with the following additional >> lines: >> >> ### example, continued >> def addlower(self, s2): >> self.stuff.append(s2.lower()) # add it as lower case >> >> B = Thing() >> B.add_the_stuff=addlower >> B.addstuff("WXYZ") >> print B.stuff >> ### end >> >> My *intent* here is to patch the Thing object named B so that the B's >> add_the_stuff method is replaced with this additional addlower method that >> I define external to the object. My expectation would be that, just as >> add_the_stuff method was called with two arguments (self and the string), >> the patched-in addlower would also get called the same way. >> >> What I *expect* is to see ['abcdefg'] printed. What I get is: >> >> Traceback (most recent call last): >> File "E:\Personal\py\DragDrop\toy.py", line 22, in >> B.addstuff("WXYZ") >> File "E:\Personal\py\DragDrop\toy.py", line 7, in addstuff >> self.add_the_stuff(text) >> TypeError: addlower() takes exactly 2 arguments (1 given) >> >> I'm assuming I'm missing some fundamental concept. What is it? >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > From waynejwerner at gmail.com Sat May 14 05:05:31 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 13 May 2011 22:05:31 -0500 Subject: [Tutor] Help with exceptions please In-Reply-To: <001201cc11d0$b1912150$14b363f0$@bigpond.com> References: <001201cc11d0$b1912150$14b363f0$@bigpond.com> Message-ID: On Fri, May 13, 2011 at 7:48 PM, Lea Parker wrote: > Hello > > > > I have another assignment I am trying to fine tune. The idea is to make > sure exceptions work. I have come up with a problem when testing my code. > When I enter a golf score for a player the program returns the ?error that > has occurred?. I only want it to do this if someone doesn?t enter an number. > > I don't have a lot of time to look at it right now, but what happens when you remove the final except? Having a catch-all can hide all sorts of exceptions. If you remove that, then python should tell you what kind of error it got. That traceback will be much more helpful than 'error that has occurred'. If that doesn't help you fix the problem, then remember the three things you need: 1. What did I do? 2. What did I expect would happen? 3. What happened instead? For 3, that also means that you should post all the (relevant) output. That means errors, and usually correct output, especially if there's not a whole lot of it. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Sat May 14 05:14:30 2011 From: carroll at tjc.com (Terry Carroll) Date: Fri, 13 May 2011 20:14:30 -0700 (PDT) Subject: [Tutor] Overriding a method in a class In-Reply-To: References: Message-ID: On Fri, 13 May 2011, Terry Carroll wrote: > For my specific case, I'm going to go with a Plan B of using callbacks; and > provide default unbound callbacks present in the module, but not defined in > the class itself. Here's a callback-with-default approach, which works: ### Thing.py ############ def add_the_stuff(obj, s1): obj.stuff.append(s1) class Thing(object): def __init__(self, callback=add_the_stuff): self.stuff = [] self.cb=callback def addstuff(self, text): self.cb(self, text) ######################### ##### toy2.py ########### import Thing A = Thing.Thing() A.addstuff("ABCDEFG") print A.stuff def addlower(obj, s2): obj.stuff.append(s2.lower()) B = Thing.Thing(callback=addlower) B.addstuff("WXYZ") print B.stuff ######################## Which produces, as expected: >toy2.py ['ABCDEFG'] ['wxyz'] But still... > But I'd still like to have a better understanding of how the call gets > transmuted from a two-argument call to a one-argument call based upon the > target. From airscorp at otenet.gr Sat May 14 05:30:18 2011 From: airscorp at otenet.gr (Nick Raptis) Date: Sat, 14 May 2011 06:30:18 +0300 Subject: [Tutor] short url processor In-Reply-To: <4DCDD199.6070605@iandouglas.com> References: <4DCDC38E.4070508@iandouglas.com> <4DCDD199.6070605@iandouglas.com> Message-ID: <4DCDF74A.4050801@otenet.gr> On 05/14/2011 03:49 AM, ian douglas wrote: > for i in giant_list: > if i[0]: > if i[1]: > mc.set(i[0], i[1]) > > Until Alan comes with a more round answer, I'd suggest something along the lines of [mc.set(x, y) for (x, y) in giant_list if x and y] I'm writing this by memory, but check "list comprehension" in the documentation. Anyway, there are map, reduce and such functions in python, but I think that in python 3.x you have to import them. Now, the real question would be, can you use the cursor as an iterator (but without hitting the database for each new record)? Then you can skip the worst part of loading all the values in giant_list. Just an idea for Alan and the others to answer. Nick From lea-parker at bigpond.com Sat May 14 06:49:32 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Sat, 14 May 2011 14:49:32 +1000 Subject: [Tutor] Fixed help with exceptions (Lea Parker) Message-ID: <000801cc11f2$517aec70$f470c550$@bigpond.com> Thank you, Wayne gave me a suggestion which helped me relook at things and correct the problem I presented. This has added other food for thought for me such as not allowing the program to accept negative inputs for the score however, I will have a play to see if I can fix this first and then ask again if I cannot. Thanks again. Lea -----Original Message----- From: tutor-bounces+lea-parker=bigpond.com at python.org [mailto:tutor-bounces+lea-parker=bigpond.com at python.org] On Behalf Of tutor-request at python.org Sent: Saturday, 14 May 2011 12:58 PM To: tutor at python.org Subject: Tutor Digest, Vol 87, Issue 44 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: short url processor (ian douglas) 2. Help with exceptions please (Lea Parker) 3. Re: short url processor (ian douglas) 4. Re: Overriding a method in a class (Terry Carroll) ---------------------------------------------------------------------- Message: 1 Date: Fri, 13 May 2011 17:42:31 -0700 From: ian douglas To: Alan Gauld Cc: tutor at python.org Subject: Re: [Tutor] short url processor Message-ID: <4DCDCFF7.5010005 at iandouglas.com> Content-Type: text/plain; charset="iso-8859-1"; Format="flowed" On 05/13/2011 05:03 PM, Alan Gauld wrote: > How do you know they are going to stdout? Are you sure they aren't > going to stderr and stderrr is not mapped to stdout (usually the > default). Have you tried redirecting stderr to a file for example? > > As I say, just some thoughts, > Thanks for your thoughts, Alan. I had done some testing with cmdline redirects and forget which is was, I think my debug log was going to stdout and the apache-style log was going to stderr, or the other way around... After a handful of guys in the #python IRC channel very nearly convinced me that all but 3 stdlib libraries are utter worthless crap, and telling me to download and use third-party frameworks just to fix a simple logging issue, I overrode log_request() and log message() as such: class clientThread(BaseHTTPRequestHandler): #[[[ def log_request(code, size): return def log_message(self, format, *args): open(LOGFILE, "a").write("%s\n" % (format%args)) ... and now the only logging going on is my own, and it's logged to my external file. Overriding log_request means that BaseHTTPServer no longer outputs its apache-style log, and overriding log_message means my other logging.info() and logging.debug() messages go out to my file as expected. -id -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Sat, 14 May 2011 10:48:51 +1000 From: "Lea Parker" To: Subject: [Tutor] Help with exceptions please Message-ID: <001201cc11d0$b1912150$14b363f0$@bigpond.com> Content-Type: text/plain; charset="us-ascii" Hello I have another assignment I am trying to fine tune. The idea is to make sure exceptions work. I have come up with a problem when testing my code. When I enter a golf score for a player the program returns the 'error that has occurred'. I only want it to do this if someone doesn't enter an number. Could I have some comments on my code for the first program of my assignment if you have some time please. """Assignment Question: The Springfork Amateur Golf club has a tournament every weekend. The club president has asked you to write two programs: 1. A program that will read each player's name and golf score as keyboard input and then to save these records in a file named golf.txt. (Each record will have a field name for the player's name and a field for the player's score. 2. A program that reads the records from the golf.txt and displays them.""" def main(): try: # Get the number of players golf_scores = int(raw_input('How many players playing this weekend? ')) # Open a file to hold player names and scores player_data = open('golf.txt', 'w') # Get the players name and score and write it to the file for count in range(1, golf_scores + 1): # Get the name name and score for player print 'Enter the name and score for player #' + str(count) name = raw_input('Name: ') score = int(raw_input('Score: ')) # Write the data as a record to the file golf.txt player_data.write(name + '\n') player_data.write(score + '\n') # Display a blank line print # Close the file player_data.close() print 'Players and their score have been written to golf.txt.' except IOError: print 'An error occured trying to write information to file.' except ValueError: print 'A numberic value must be entered.' except: print 'An error occured.' # Call the main function main() Thanks in advance. Lea -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 3 Date: Fri, 13 May 2011 17:49:29 -0700 From: ian douglas To: Tutor at python.org Subject: Re: [Tutor] short url processor Message-ID: <4DCDD199.6070605 at iandouglas.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 05/13/2011 05:03 PM, Alan Gauld wrote: > As I say, just some thoughts, > I *am* curious, Alan, whether you or anyone else on the list are able to help me make this a little more efficient: cur.execute("SELECT short_url,long_url FROM short_urls") giant_list = cur.fetchall() for i in giant_list: if i[0]: if i[1]: mc.set(i[0], i[1]) At present, we have about two million short URL's in our database, and I'm guessing there's a much smoother way of iterating through 2M+ rows from a database, and cramming them into memcache. I imagine there's a map function in there that could be much more efficient? v2 of our project will be to join our short_urls table with its 'stats' table counterpart, to where I only fetch the top 10,000 URLs (or some other smaller quantity). Until we get to that point, I need to speed up the restart time if this script ever needs to be restarted. This is partly why v1.5 was to put the database entries into memcache, so we wouldn't need to reload the db into memory on every restart. Thanks, Ian ------------------------------ Message: 4 Date: Fri, 13 May 2011 19:57:42 -0700 (PDT) From: Terry Carroll To: tutor at python.org Subject: Re: [Tutor] Overriding a method in a class Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed On Fri, 13 May 2011, David Knupp wrote: > I think the problem is this bit about overriding an object's internal > method with one that is defined externally. Yes, that describes the phenomenon. > My gut feeilng is that you'd > now have to explicitly pass the object (i.e., self) as well as the > string, i.e.: > > B.addstuff(B, "WXYZ") > > ...which seems clunky. But worse, it would mean that you couldn't have the default un-overridden method for those cases where you don't need to override it. > I'm not familiar with this particular technique. Is it common to do > something like this? Certainly the problem is common. For my specific case, I'm going to go with a Plan B of using callbacks; and provide default unbound callbacks present in the module, but not defined in the class itself. But I'd still like to have a better understanding of how the call gets transmuted from a two-argument call to a one-argument call based upon the target. I suspect something along these lines is going on: When a bound method is called, Python inserts a reference to self as an additional first argument, before the other arguments. It does not do this with unbound methods. In my first case, when I created object A, the name add_the_stuff references the bound method add_the_stuff as defined in the Thing class. When add_stuff calls add_the_stuff, because add_the_stuff references a bound method, Python does the automagical insertion of the self argument. In my second case, when I created the object B, the name add_the_stuff *initially* references the bound method add_the_stuff; but then, when I override, I make B.add_the_stuff reference the unbound external method. Now, when addstuff calls add_the_stuff, Python sees that it is referencing an unbound method, and does not insert the self reference into the argument list. Now I'll wait for one of the experts to edify me. > On Fri, 13 May 2011, Terry Carroll wrote: > >> I have a pretty basic point of confusion that I'm hoping I can have >> explained to me. I have a class in which I want to override a method, and >> have my method defined externally to the class definition invoked instead. >> But when I do so, my external method is invoked with a different argument >> signature than the method it overrides. >> >> (I'll illustrate with a toy example named toy.py that maintains a list of >> strings; the actual use case is a wxPython drag-and-drop shell that I find >> I keep re-using over and over, so I decided to try to turn it into a >> general-purpose module for my own use.) >> >> ### example 1 begin >> >> class Thing(object): >> def __init__(self): >> self.stuff = [] >> def addstuff(self, text): >> self.add_the_stuff(text) >> def add_the_stuff(self, s1): >> self.stuff.append(s1) >> >> A = Thing() >> A.addstuff("ABCDEFG") >> print A.stuff >> >> ### example 1 end >> >> So far, this works as expected. addstuff invokes add_the_stuff; and the >> line "print A.stuff" prints out as ['ABCDEFG'], as expected. >> >> Now, here's where I am getting befuddled, with the following additional >> lines: >> >> ### example, continued >> def addlower(self, s2): >> self.stuff.append(s2.lower()) # add it as lower case >> >> B = Thing() >> B.add_the_stuff=addlower >> B.addstuff("WXYZ") >> print B.stuff >> ### end >> >> My *intent* here is to patch the Thing object named B so that the B's >> add_the_stuff method is replaced with this additional addlower method that >> I define external to the object. My expectation would be that, just as >> add_the_stuff method was called with two arguments (self and the string), >> the patched-in addlower would also get called the same way. >> >> What I *expect* is to see ['abcdefg'] printed. What I get is: >> >> Traceback (most recent call last): >> File "E:\Personal\py\DragDrop\toy.py", line 22, in >> B.addstuff("WXYZ") >> File "E:\Personal\py\DragDrop\toy.py", line 7, in addstuff >> self.add_the_stuff(text) >> TypeError: addlower() takes exactly 2 arguments (1 given) >> >> I'm assuming I'm missing some fundamental concept. What is it? >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 87, Issue 44 ************************************* From __peter__ at web.de Sat May 14 08:20:31 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 May 2011 08:20:31 +0200 Subject: [Tutor] Overriding a method in a class References: Message-ID: Terry Carroll wrote: > I have a pretty basic point of confusion that I'm hoping I can have > explained to me. I have a class in which I want to override a method, and > have my method defined externally to the class definition invoked instead. > But when I do so, my external method is invoked with a different argument > signature than the method it overrides. > > (I'll illustrate with a toy example named toy.py that maintains a list of > strings; the actual use case is a wxPython drag-and-drop shell that I find > I keep re-using over and over, so I decided to try to turn it into a > general-purpose module for my own use.) > > ### example 1 begin > > class Thing(object): > def __init__(self): > self.stuff = [] > def addstuff(self, text): > self.add_the_stuff(text) > def add_the_stuff(self, s1): > self.stuff.append(s1) > > A = Thing() > A.addstuff("ABCDEFG") > print A.stuff > > ### example 1 end > > So far, this works as expected. addstuff invokes add_the_stuff; and the > line "print A.stuff" prints out as ['ABCDEFG'], as expected. > > Now, here's where I am getting befuddled, with the following additional > lines: > > ### example, continued > def addlower(self, s2): > self.stuff.append(s2.lower()) # add it as lower case > > B = Thing() > B.add_the_stuff=addlower > B.addstuff("WXYZ") > print B.stuff > ### end > > My *intent* here is to patch the Thing object named B so that the > B's add_the_stuff method is replaced with this additional addlower method > that I define external to the object. My expectation would be that, just > as add_the_stuff method was called with two arguments (self and the > string), the patched-in addlower would also get called the same way. > > What I *expect* is to see ['abcdefg'] printed. What I get is: > > Traceback (most recent call last): > File "E:\Personal\py\DragDrop\toy.py", line 22, in > B.addstuff("WXYZ") > File "E:\Personal\py\DragDrop\toy.py", line 7, in addstuff > self.add_the_stuff(text) > TypeError: addlower() takes exactly 2 arguments (1 given) > > I'm assuming I'm missing some fundamental concept. What is it? If you define a function in the class body and then instantiate that class class A(object): def method(self, x): print x a = A() an attribute access like a.method will be translated to a.method.__get__(a, A) which returns a bound method object. This is called "descriptor protocol", the same mechanism that allows the implementation of properties. You can find a thorough explanation at http://users.rcn.com/python/download/Descriptor.htm However, if you put a function into an instance the attribute will be returned as is. You have to inform it about self either by explicitly invoking __get__() def f(self, x): print x*x a.method = f.__get__(a, type(a)) or by using partial function application: from functools import partial a.method = partial(method, a) From alan.gauld at btinternet.com Sat May 14 10:12:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 May 2011 09:12:35 +0100 Subject: [Tutor] Overriding a method in a class References: Message-ID: "Terry Carroll" wrote in message >I have a pretty basic point of confusion that I'm hoping I can have >explained to me. I have a class in which I want to override a >method, and have my method defined externally to the class definition >invoked instead. Is there any reason you can'tt override in the uisual way by inheritance? It seems to me you are changing the behaviour of a class which means its now a different kind of thing. So it deserves to be a new class - a LowerThing or whatever. > ### example, continued > def addlower(self, s2): > self.stuff.append(s2.lower()) # add it as lower case > > B = Thing() > B.add_the_stuff=addlower But this doesn't add a method it adds a reference to a function. methods are not simply functions defined inside a class. methods need to be bound to the class for the self "magic" to happen. [There was a good post by Steven a few weeks ago that explained the difference. It might be worth searching out] HTH, Alan G. From timomlists at gmail.com Sat May 14 10:55:33 2011 From: timomlists at gmail.com (Timo) Date: Sat, 14 May 2011 10:55:33 +0200 Subject: [Tutor] Help with exceptions please In-Reply-To: References: <001201cc11d0$b1912150$14b363f0$@bigpond.com> Message-ID: <4DCE4385.4020306@gmail.com> On 14-05-11 05:05, Wayne Werner wrote: > On Fri, May 13, 2011 at 7:48 PM, Lea Parker > wrote: > > Hello > > I have another assignment I am trying to fine tune. The idea is to > make sure exceptions work. I have come up with a problem when > testing my code. When I enter a golf score for a player the > program returns the ?error that has occurred?. I only want it to > do this if someone doesn?t enter an number. > > > I don't have a lot of time to look at it right now, but what happens > when you remove the final except? > > Having a catch-all can hide all sorts of exceptions. If you remove > that, then python should tell you what kind of error it got. That > traceback will be much more helpful than 'error that has occurred'. I agree. Something is throwing an exception you don't expect. If you do want to catch it and exit gracefully, you can replace: except: print 'An error occured.' with: except Exception, exc: print 'An error occured:\n' + exc Cheers, Timo > > If that doesn't help you fix the problem, then remember the three > things you need: > > 1. What did I do? > 2. What did I expect would happen? > 3. What happened instead? > > For 3, that also means that you should post all the (relevant) output. > That means errors, and usually correct output, especially if there's > not a whole lot of it. > > HTH, > Wayne > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From coolankur2006 at gmail.com Sat May 14 20:16:07 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Sat, 14 May 2011 23:46:07 +0530 Subject: [Tutor] Hungry Snake now on Softpedia Message-ID: Hey I got a mail form softpedia today that they have added my game "Hungry Snake" to their site too under 100% free certificate. I am really happy :):) I can feel the power of open source :):) Want to share this with you people because I learned a lot from the python community . Game Links - http://code.google.com/p/hungry-snakes/ , http://mac.softpedia.com/get/Games/Hungry-Snake.shtml Certificate Link - http://mac.softpedia.com/progClean/Hungry-Snake-Clean-98721.html Thanks Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Sat May 14 23:58:29 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Sat, 14 May 2011 17:58:29 -0400 Subject: [Tutor] python file upload In-Reply-To: References: Message-ID: On Friday, May 13, 2011, Rayon wrote: > Hi all, I need a python script to upload a xml file to a web page using python. I have tried using pycurl but I am still getting Fyi, the XML spec allows for no characters or whitespace before the XML declaration, that could be your error, -- Brett Ritter / SwiftOne swiftone at swiftone.org From steve at pearwood.info Sun May 15 08:41:37 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 15 May 2011 16:41:37 +1000 Subject: [Tutor] cpython In-Reply-To: References: Message-ID: <201105151641.38238.steve@pearwood.info> On Thu, 12 May 2011 11:18:40 pm Izz ad-Din Ruhulessin wrote: > Hi, > > CPython is the C implementation of Python. You can read the tutorial > in the Python docs. > > It is a rather advanced topic, however. If you nevertheless want to > delve into it, it might be a good idea to check out www.cython.org > first. cython is a completely different product from CPython. CPython is the C implementation of Python. Most Python users are using that. cython is a add-on that lets you write C extensions using syntax very close to Python. The only connection to CPython is that it runs on top of CPython. -- Steven D'Aprano From lea-parker at bigpond.com Sun May 15 12:19:03 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Sun, 15 May 2011 20:19:03 +1000 Subject: [Tutor] searching data from a list read from a file Message-ID: <000001cc12e9$84470ab0$8cd52010$@bigpond.com> Hello J When you have time I would like some advice on where to go. I have created a program that reads charge account numbers from a file. The user is to enter a charge account number from the list presented and the program should then tell them whether they have entered a valid or invalid number. My problem at this stage (and yes there a probably more than this one), is when I run the program it tells me the charge account number is always invalid even when I put a correct number in. Below is my code because I am thinking that perhaps it is an indent issue maybe. """This program reads the contents of a file into a list. Asks the user to enter a charge account number and will determine the validity of the number entered to return a message of either valid or invalid. Written by: Leonie Parker 11428070 Subject: ITC Principles of programming Assignment: 2b""" def main(): try: # Open file for reading infile = open('charge_accounts.txt', 'r') # Read the contents of the file inot a lsit account_number = infile.readlines() #Convert each element into an int index = 0 while index != len(account_number): account_number[index] = int(account_number[index]) index += 1 # Print the contents of the list print account_number #Get an account number to search for search = raw_input('Enter a charge account number: ') #Determine whether the product number is in thelist if search in account_number: print search, 'charge account number is VALID' else: print search, 'charge account number is INVALID' infile.close() except ValueError: print 'file open error message' #Call the main function main() Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun May 15 13:32:06 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 May 2011 13:32:06 +0200 Subject: [Tutor] searching data from a list read from a file References: <000001cc12e9$84470ab0$8cd52010$@bigpond.com> Message-ID: Lea Parker wrote: [Lea, please reduce the number of empty lines in your posted source code.] > When you have time I would like some advice on where to go. I have created > a program that reads charge account numbers from a file. The user is to > enter a charge account number from the list presented and the program > should then tell them whether they have entered a valid or invalid number. > My problem at this stage (and yes there a probably more than this one), is > when I run the program it tells me the charge account number is always > invalid even when I put a correct number in. Below is my code because I am > thinking that perhaps it is an indent issue maybe. Hint: What is the type of the values in the account_number list? What is the type of the value stored in the search variable? What's the result of a comparison like 42 == "42" in Python? > """This program reads the contents of a file into a list. Asks the user > > to enter a charge account number and will determine the validity of the > > number entered to return a message of either valid or invalid. > > > > Written by: Leonie Parker 11428070 > > Subject: ITC Principles of programming > > Assignment: 2b""" > > > > def main(): > > try: > > # Open file for reading > > infile = open('charge_accounts.txt', 'r') > > > > # Read the contents of the file inot a lsit > > account_number = infile.readlines() > > > > #Convert each element into an int > > index = 0 > > while index != len(account_number): > > account_number[index] = int(account_number[index]) > > index += 1 > > > > # Print the contents of the list > > print account_number > > > > #Get an account number to search for > > search = raw_input('Enter a charge account number: ') > > > > #Determine whether the product number is in thelist > > if search in account_number: > > print search, 'charge account number is VALID' > > else: > > print search, 'charge account number is INVALID' > > > > infile.close() > > > > except ValueError: > > print 'file open error message' > > > > #Call the main function > > main() > > > > > > > > Thanks in advance From alan.gauld at btinternet.com Sun May 15 21:29:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 May 2011 20:29:57 +0100 Subject: [Tutor] searching data from a list read from a file References: <000001cc12e9$84470ab0$8cd52010$@bigpond.com> Message-ID: "Lea Parker" wrote in Peter has pointred you to the answer, here are some general comments: > def main(): > > try: SDee the recent posts re the scope of try/except handling. This is probably a bit too much for a single exception type! > # Open file for reading > infile = open('charge_accounts.txt', 'r') > > # Read the contents of the file inot a lsit > account_number = infile.readlines() As a point of style if a variabl;e holds a collection of things use the plural form so this would be batter named account_numbers > #Convert each element into an int > index = 0 > while index != len(account_number): > account_number[index] = int(account_number[index]) > index += 1 This could be done using map(): account_number = map(int,account_number) or using a list comprehension: account_number = [int(num) for num in account_number] or even using a 'for' loop: for index, num in enumerate(account_number): account_number[index] = int(num) Any of which would be better than the while style. Use 'while' for cases where you don't know in advance how many items you need to proccess. > # Print the contents of the list > print account_number > #Get an account number to search for > search = raw_input('Enter a charge account number: ') > > #Determine whether the product number is in thelist > if search in account_number: As Peter says, check the types here... > print search, 'charge account number is VALID' > else: > print search, 'charge account number is INVALID' > infile.close() > except ValueError: > print 'file open error message' HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From carroll at tjc.com Mon May 16 01:07:29 2011 From: carroll at tjc.com (Terry Carroll) Date: Sun, 15 May 2011 16:07:29 -0700 (PDT) Subject: [Tutor] Overriding a method in a class In-Reply-To: References: Message-ID: On Sat, 14 May 2011, Alan Gauld wrote: > Is there any reason you can'tt override in the uisual way by inheritance? Doh! Of course I should. I've written plenty of classes before, but never one intended to be inherited, and now that you point it out, it's obvious that that's what I should be doing here. Thanks. On Sat, 14 May 2011, Peter Otten wrote: > If you define a function in the class body and then instantiate that > class.... [snip] > You can find a thorough explanation at > http://users.rcn.com/python/download/Descriptor.htm Thanks, Peter; that's very helpful. I'll read that page in detail. From idooba at gmail.com Mon May 16 12:38:47 2011 From: idooba at gmail.com (I. Dooba) Date: Mon, 16 May 2011 18:38:47 +0800 Subject: [Tutor] Academic publications Message-ID: I'm submitting a paper to a conference. However, I'm wondering if it's appropriate to include the codes for my application in the paper. If it's OK to do that, how much of the code should I include? Thanks. Dooba -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon May 16 13:24:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 16 May 2011 21:24:38 +1000 Subject: [Tutor] Academic publications In-Reply-To: References: Message-ID: <201105162124.39107.steve@pearwood.info> On Mon, 16 May 2011 08:38:47 pm I. Dooba wrote: > I'm submitting a paper to a conference. > However, I'm wondering if it's appropriate to include the codes for > my application in the paper. > If it's OK to do that, how much of the code should I include? Why are you asking us? Surely you should be asking the conference organizers as to what they want, expect and allow. I imagine their answer will depend on what the conference is for, what your talk is about, and how long the code is. Unless you are specifically talking about the code, you should probably just give a link to where people can download it. But I'm just guessing. -- Steven D'Aprano From s.charonis at gmail.com Mon May 16 15:51:15 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Mon, 16 May 2011 14:51:15 +0100 Subject: [Tutor] String Processing Query Message-ID: I have a file with the following contents: >from header1 abcdefghijkl mnopqrs tuvwxyz * >from header2 poiuytrewq lkjhgfdsa mnbvcxz * My string processing code goes as follows: file1=open('/myfolder/testfile.txt') scan = file1.readlines() string1 = ' ' for line in scan: if line.startswith('>from'): continue if line.startswith('*'): continue string1.join(line.rstrip('\n')) This code produces the following output: 'abcdefghijkl' 'mnopqrs' 'tuvwxyz' 'poiuytrewq' 'lkjhgfdsa' 'mnbvcxz' I would like to know if there is a way to get the following output instead: 'abcdefghijklmnopqrstuvwxyz' 'poiuytrewqlkjhgfdsamnbvcxz' I'm basically trying to concatenate the strings in order to produce 2 separate lines -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Mon May 16 16:05:06 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 16 May 2011 10:05:06 -0400 Subject: [Tutor] String Processing Query In-Reply-To: References: Message-ID: concatenate the entire thing together, including the "*". Once you have that as a single string, use string.split('*') and you will have your two strings. On Mon, May 16, 2011 at 9:51 AM, Spyros Charonis wrote: > I have a file with the following contents: > > >from header1 > abcdefghijkl > mnopqrs > tuvwxyz > * > >from header2 > poiuytrewq > lkjhgfdsa > mnbvcxz > * > > My string processing code goes as follows: > > file1=open('/myfolder/testfile.txt') > scan = file1.readlines() > > string1 = ' ' > for line in scan: > if line.startswith('>from'): > continue > if line.startswith('*'): > continue > string1.join(line.rstrip('\n')) > > This code produces the following output: > > 'abcdefghijkl' > 'mnopqrs' > 'tuvwxyz' > 'poiuytrewq' > 'lkjhgfdsa' > 'mnbvcxz' > > I would like to know if there is a way to get the following > output instead: > > 'abcdefghijklmnopqrstuvwxyz' > > 'poiuytrewqlkjhgfdsamnbvcxz' > > I'm basically trying to concatenate the strings > in order to produce 2 separate lines > > > > _______________________________________________ > 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 evosweet at hotmail.com Mon May 16 20:00:49 2011 From: evosweet at hotmail.com (Rayon) Date: Mon, 16 May 2011 14:00:49 -0400 Subject: [Tutor] upload xml file via pycurl Message-ID: I am trying to upload a xml file via pycurl, I really need some help here. url = "https://192.168.0.68/fileupload/upload_file.php" binaryptr = open('activation.xml','rb').read() head = ['Content-type:text/xml'] c.setopt(c.SSL_VERIFYPEER, 0) c.setopt(c.SSL_VERIFYHOST, 0) c.setopt(c.POSTFIELDS,binaryptr) c.setopt(c.POSTFIELDSIZE,23L) c.setopt(c.HTTPHEADER,head) c.setopt(c.URL, url) c.setopt(c.VERBOSE, 1) c.perform() Regards Rayon -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Mon May 16 20:25:17 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Mon, 16 May 2011 14:25:17 -0400 Subject: [Tutor] upload xml file via pycurl In-Reply-To: References: Message-ID: On Mon, May 16, 2011 at 2:00 PM, Rayon wrote: > I am trying to upload a xml file via pycurl, I really need some help here. What is the error your are receiving? Did you fix the fact that you had starting whitespace as I mentioned to your last email? -- Brett Ritter / SwiftOne swiftone at swiftone.org From alan.gauld at btinternet.com Tue May 17 00:02:09 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 May 2011 23:02:09 +0100 Subject: [Tutor] upload xml file via pycurl References: Message-ID: "Rayon" wrote >I am trying to upload a xml file via pycurl, I really need some help >here. So give us a clue. What is wrong with your code? And what does the real code look like, the fragment you have posted doesn't tell us too much - what is c? what have you imported, and how did you do it? Are you getting an error - if so what does it say? Are you getting bad data out? If so what did you get? What did you expect? "I really need some help" doesn't tell us much. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ > url = "https://192.168.0.68/fileupload/upload_file.php" > binaryptr = open('activation.xml','rb').read() > head = ['Content-type:text/xml'] > > c.setopt(c.SSL_VERIFYPEER, 0) > c.setopt(c.SSL_VERIFYHOST, 0) > c.setopt(c.POSTFIELDS,binaryptr) > c.setopt(c.POSTFIELDSIZE,23L) > c.setopt(c.HTTPHEADER,head) > c.setopt(c.URL, url) > c.setopt(c.VERBOSE, 1) > c.perform() From spawgi at gmail.com Tue May 17 10:54:52 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Tue, 17 May 2011 14:24:52 +0530 Subject: [Tutor] String Processing Query In-Reply-To: References: Message-ID: This snipped also works - may be there is a better solution - ', '*'] >>> s = '' >>> for line in lines: line = line.rstrip('\n') if line.startswith('>from header'): continue elif line.startswith('*'): s = s + '\n' else: s = s + line >>> s 'abcdefghijklmnopqrstuvwxyz\npoiuytrewqlkjhgfdsamnbvcxz\n' >>> print s abcdefghijklmnopqrstuvwxyz poiuytrewqlkjhgfdsamnbvcxz Thanks and Regards, Sumod On Mon, May 16, 2011 at 7:35 PM, James Reynolds wrote: > concatenate the entire thing together, including the "*". > > Once you have that as a single string, use string.split('*') and you will > have your two strings. > > On Mon, May 16, 2011 at 9:51 AM, Spyros Charonis wrote: > >> I have a file with the following contents: >> >> >from header1 >> abcdefghijkl >> mnopqrs >> tuvwxyz >> * >> >from header2 >> poiuytrewq >> lkjhgfdsa >> mnbvcxz >> * >> >> My string processing code goes as follows: >> >> file1=open('/myfolder/testfile.txt') >> scan = file1.readlines() >> >> string1 = ' ' >> for line in scan: >> if line.startswith('>from'): >> continue >> if line.startswith('*'): >> continue >> string1.join(line.rstrip('\n')) >> >> This code produces the following output: >> >> 'abcdefghijkl' >> 'mnopqrs' >> 'tuvwxyz' >> 'poiuytrewq' >> 'lkjhgfdsa' >> 'mnbvcxz' >> >> I would like to know if there is a way to get the following >> output instead: >> >> 'abcdefghijklmnopqrstuvwxyz' >> >> 'poiuytrewqlkjhgfdsamnbvcxz' >> >> I'm basically trying to concatenate the strings >> in order to produce 2 separate lines >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 17 12:55:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 May 2011 11:55:58 +0100 Subject: [Tutor] String Processing Query References: Message-ID: "Spyros Charonis" wrote >I have a file with the following contents: > >>from header1 > abcdefghijkl > mnopqrs > tuvwxyz > * >>from header2 > poiuytrewq > lkjhgfdsa > mnbvcxz > * > > My string processing code goes as follows: > > file1=open('/myfolder/testfile.txt') > scan = file1.readlines() > > string1 = ' ' > for line in scan: > if line.startswith('>from'): > continue > if line.startswith('*'): > continue > string1.join(line.rstrip('\n')) string1 = ''.join(scan[1:-1]).replace('\n','') Does that do it? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Tue May 17 15:42:33 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 17 May 2011 21:42:33 +0800 Subject: [Tutor] how to read two files and substitute Message-ID: Hi, For file1: 5007 O28 CHO 173 35.300 99.430 65.810 1.00 0.0 5008 H29 CHO 173 35.680 100.290 66.150 1.00 0.00 5009 C1 CHO 174 59.060 12.440 58.680 1.00 0.00 5010 C2 CHO 174 59.460 12.480 60.160 1.00 0.00 5011 C3 CHO 174 59.590 11.120 60.830 1.00 0.00 5012 C4 CHO 174 60.780 10.430 60.160 1.00 0.00 For file2: 5008 5010 5011 I want to get the $4(column 4) value which has the$1 value. for values in file2 such as the results is 173 174 174 Thanks for any suggestions, From andreengels at gmail.com Tue May 17 16:09:00 2011 From: andreengels at gmail.com (Andre Engels) Date: Tue, 17 May 2011 16:09:00 +0200 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: First read file1, and keep the result in a useful data structure (for this simple case it can be nothing more than a dictionary with the value in column 1 as key and the value in column 4 as value, but perhaps it's better to find something else if you want to do more with the data). Then go through file2, check your data structure for every value, and ready. Andr? On Tue, May 17, 2011 at 3:42 PM, lina wrote: > Hi, > > For file1: > > ?5007 ?O28 CHO ? 173 ? ? ?35.300 ?99.430 ?65.810 ?1.00 ?0.0 > ?5008 ?H29 CHO ? 173 ? ? ?35.680 100.290 ?66.150 ?1.00 ?0.00 > ?5009 ?C1 ?CHO ? 174 ? ? ?59.060 ?12.440 ?58.680 ?1.00 ?0.00 > ?5010 ?C2 ?CHO ? 174 ? ? ?59.460 ?12.480 ?60.160 ?1.00 ?0.00 > ?5011 ?C3 ?CHO ? 174 ? ? ?59.590 ?11.120 ?60.830 ?1.00 ?0.00 > ?5012 ?C4 ?CHO ? 174 ? ? ?60.780 ?10.430 ?60.160 ?1.00 ?0.00 > > For file2: > > 5008 5010 5011 > > I want to get the $4(column 4) value which has ?the$1 value. for > values in file2 > > such as the results is 173 174 174 > > Thanks for any suggestions, > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Andr? Engels, andreengels at gmail.com From motoom at xs4all.nl Tue May 17 16:02:57 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 17 May 2011 16:02:57 +0200 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: <4DD28011.3060002@xs4all.nl> On 2011-05-17 15:42, lina wrote: > I want to get the $4(column 4) value which has the$1 value. for > values in file2 Have you tried to write some code yourself already? Please show it. Anyway, I'd proceed with something like this: mapping={} for line in open("file1").readlines(): parts=line.strip().split() mapping[parts[0]]=parts[3] origs=open("file2").read().split() print " ".join([mapping[orig] for orig in origs]) The output is "173 174 174". Since you provide no column names I can't use meaningful variable names. Are these very big files? In that case another approach is maybe better. Greetings, -- "Good programming is not learned from generalities, but by seeing how significant programs can be made clean, easy to read, easy to maintain and modify, human-engineered, efficient, and reliable, by the application of common sense and good programming practices. Careful study and imitation of good programs leads to better writing." - Kernighan and Plauger, motto of 'Software Tools' From emile at fenx.com Tue May 17 16:19:39 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 17 May 2011 07:19:39 -0700 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: On 5/17/2011 6:42 AM lina said... > Hi, > > For file1: > > 5007 O28 CHO 173 35.300 99.430 65.810 1.00 0.0 > 5008 H29 CHO 173 35.680 100.290 66.150 1.00 0.00 > 5009 C1 CHO 174 59.060 12.440 58.680 1.00 0.00 > 5010 C2 CHO 174 59.460 12.480 60.160 1.00 0.00 > 5011 C3 CHO 174 59.590 11.120 60.830 1.00 0.00 > 5012 C4 CHO 174 60.780 10.430 60.160 1.00 0.00 > > For file2: > > 5008 5010 5011 > > I want to get the $4(column 4) value which has the$1 value. for > values in file2 > > such as the results is 173 174 174 > > Thanks for any suggestions, > It'll help us help you if you show how far along you've come. Otherwise, most of us will presume this is a homework assignment, and we'd rather help you learn python than do your homework for you. In short, you'll read the lines from the file, test each line to see if it starts with one of the targets, then spilt the fields from the line and select the fourth field. Accumulate those and return the result. Post your code when you follow up please. Emile From taxbotsis at gmail.com Tue May 17 16:29:24 2011 From: taxbotsis at gmail.com (tax botsis) Date: Tue, 17 May 2011 10:29:24 -0400 Subject: [Tutor] multiprocessing for nested function Message-ID: Part of my code includes the following script, which both shows a progress bar (for as long as 'categorize_reports()' is executed) and prints the fileid and the output of the 'document' function; the latter is the one increasing the calculation time (please see my comment). Any ideas on how to use all the cores of my CPU here? ... def categorize_reports(): if __name__ == '__main__': root2 = Tkinter.Tk(className=' Processing Progress') m = Meter(root2, relief='ridge', bd=3) m.pack(fill='x') i=0.0 for fileid in fileids(): m.set(i, 'Processing will take a few minutes...') i=i+1.000/len(fileids()) m.after(1000, lambda: _demo(m, i)) print str(fileid), document(fileid) #this slows down the process root2.withdraw() ... Thanks Tax -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue May 17 17:19:41 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 17 May 2011 23:19:41 +0800 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: $python atomToResidues.py Traceback (most recent call last): File "atomToResidues.py", line 6, in mapping[parts[1]]=parts[4] IndexError: list index out of range Following Michiel's code (a little adjustment was done): #!/bin/python mapping={} for line in open("confout.pdb").readlines(): parts=line.strip().split() mapping[parts[1]]=parts[4] origs=open("dummy.atomID").read().split() print " ".join([mapping[orig] for orig in origs]) On Tue, May 17, 2011 at 11:12 PM, lina wrote: > Thanks all first, > > I wrote a .bash, but not work. > > for python one, I am not confident in writing one. I will try Michiel one now. > > > > On Tue, May 17, 2011 at 10:19 PM, Emile van Sebille wrote: >> On 5/17/2011 6:42 AM lina said... >>> >>> Hi, >>> >>> For file1: >>> >>> ? 5007 ?O28 CHO ? 173 ? ? ?35.300 ?99.430 ?65.810 ?1.00 ?0.0 >>> ? 5008 ?H29 CHO ? 173 ? ? ?35.680 100.290 ?66.150 ?1.00 ?0.00 >>> ? 5009 ?C1 ?CHO ? 174 ? ? ?59.060 ?12.440 ?58.680 ?1.00 ?0.00 >>> ? 5010 ?C2 ?CHO ? 174 ? ? ?59.460 ?12.480 ?60.160 ?1.00 ?0.00 >>> ? 5011 ?C3 ?CHO ? 174 ? ? ?59.590 ?11.120 ?60.830 ?1.00 ?0.00 >>> ? 5012 ?C4 ?CHO ? 174 ? ? ?60.780 ?10.430 ?60.160 ?1.00 ?0.00 >>> >>> For file2: >>> >>> 5008 5010 5011 >>> >>> I want to get the$4(column 4) value which has ?the $1 value. for >>> values in file2 >>> >>> such as the results is 173 174 174 >>> >>> Thanks for any suggestions, >>> >> >> >> It'll help us help you if you show how far along you've come. Otherwise, >> most of us will presume this is a homework assignment, and we'd rather help >> you learn python than do your homework for you. >> >> In short, you'll read the lines from the file, test each line to see if it >> starts with one of the targets, then spilt the fields from the line and >> select the fourth field. ?Accumulate those and return the result. >> >> Post your code when you follow up please. >> >> Emile >> >> _______________________________________________ >> 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 idooba at gmail.com Tue May 17 17:20:43 2011 From: idooba at gmail.com (I. Dooba) Date: Tue, 17 May 2011 23:20:43 +0800 Subject: [Tutor] Please help, the program is not behaving as I want Message-ID: I'm new to programming and have decided to start with Python following the advice of experts including Eric S. Raymond. So far I've learnt quite a lot from this list. However, I've the following problem. The program was designed (as part of my practice with Head First Programming) to check whether an ingredient is Halal or Haram. I've a simple table online where some ingredients are either halal or haram. For example, if the user enters "water" the program is supposed to tell him that it's halal; but it's returning ">" and other characters I don't want to see. What am I doing wrong? import urllib.request page = urllib.request.urlopen("http://halalingredients.theparleyonline.com/ ") text = page.read().decode("utf8") halal_haram_status = text.find(input("Enter the ingredient: ")) begin_final_status = halal_haram_status + 3 end_final_status = begin_final_status + 5 status = text[begin_final_status:end_final_status] print(status) -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue May 17 17:31:48 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 17 May 2011 23:31:48 +0800 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: I learn python on and off, tried some examples, I mean tutorial, step by step writing around 80 ones, but seems not a good way of learning. Those tutorials are good, just I am not good at learning. so what I learned can't handle the problem I met. On Tue, May 17, 2011 at 11:19 PM, lina wrote: >$ python atomToResidues.py > Traceback (most recent call last): > ?File "atomToResidues.py", line 6, in > ? ?mapping[parts[1]]=parts[4] > IndexError: list index out of range > > Following Michiel's code (a little adjustment was done): > > #!/bin/python > > mapping={} > for line in open("confout.pdb").readlines(): > ? parts=line.strip().split() > ? mapping[parts[1]]=parts[4] > origs=open("dummy.atomID").read().split() > print " ".join([mapping[orig] for orig in origs]) > > > > On Tue, May 17, 2011 at 11:12 PM, lina wrote: >> Thanks all first, >> >> I wrote a .bash, but not work. >> >> for python one, I am not confident in writing one. I will try Michiel one now. >> >> >> >> On Tue, May 17, 2011 at 10:19 PM, Emile van Sebille wrote: >>> On 5/17/2011 6:42 AM lina said... >>>> >>>> Hi, >>>> >>>> For file1: >>>> >>>> ? 5007 ?O28 CHO ? 173 ? ? ?35.300 ?99.430 ?65.810 ?1.00 ?0.0 >>>> ? 5008 ?H29 CHO ? 173 ? ? ?35.680 100.290 ?66.150 ?1.00 ?0.00 >>>> ? 5009 ?C1 ?CHO ? 174 ? ? ?59.060 ?12.440 ?58.680 ?1.00 ?0.00 >>>> ? 5010 ?C2 ?CHO ? 174 ? ? ?59.460 ?12.480 ?60.160 ?1.00 ?0.00 >>>> ? 5011 ?C3 ?CHO ? 174 ? ? ?59.590 ?11.120 ?60.830 ?1.00 ?0.00 >>>> ? 5012 ?C4 ?CHO ? 174 ? ? ?60.780 ?10.430 ?60.160 ?1.00 ?0.00 >>>> >>>> For file2: >>>> >>>> 5008 5010 5011 >>>> >>>> I want to get the $4(column 4) value which has ?the$1 value. for >>>> values in file2 >>>> >>>> such as the results is 173 174 174 >>>> >>>> Thanks for any suggestions, >>>> >>> >>> >>> It'll help us help you if you show how far along you've come. Otherwise, >>> most of us will presume this is a homework assignment, and we'd rather help >>> you learn python than do your homework for you. >>> >>> In short, you'll read the lines from the file, test each line to see if it >>> starts with one of the targets, then spilt the fields from the line and >>> select the fourth field. ?Accumulate those and return the result. >>> >>> Post your code when you follow up please. >>> >>> Emile >>> >>> _______________________________________________ >>> 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 > -- Best Regards, lina From joel.goldstick at gmail.com Tue May 17 17:38:39 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 17 May 2011 11:38:39 -0400 Subject: [Tutor] Please help, the program is not behaving as I want In-Reply-To: References: Message-ID: On Tue, May 17, 2011 at 11:20 AM, I. Dooba wrote: > I'm new to programming and have decided to start with Python following the > advice of experts including Eric S. Raymond. > So far I've learnt quite a lot from this list. > > However, I've the following problem. > > The program was designed (as part of my practice with Head First > Programming) to check whether an ingredient is Halal or Haram. > I've a simple table online where some ingredients are either halal or > haram. > > For example, if the user enters "water" the program is supposed to tell him > that it's halal; > but it's returning ">" and other characters I don't want to see. > > What am I doing wrong? > > import urllib.request > > page = urllib.request.urlopen(" > http://halalingredients.theparleyonline.com/") > text = page.read().decode("utf8") > > halal_haram_status = text.find(input("Enter the ingredient: ")) > begin_final_status = halal_haram_status + 3 > end_final_status = begin_final_status + 5 > status = text[begin_final_status:end_final_status] > print(status) > > > ______________ Can you copy and paste the error message traceback that you get? > _________________________________ > 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 emile at fenx.com Tue May 17 17:53:47 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 17 May 2011 08:53:47 -0700 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: On 5/17/2011 8:31 AM lina said... > Following Michiel's code (a little adjustment was done): > Well. you're almost there. The error you're getting is likely due to splitting an empty line, then referencing the [1] and [4] elements. After you split the line into parts, test to confirm that the fields you need are there: > #!/bin/python > > mapping={} > for line in open("confout.pdb").readlines(): > parts=line.strip().split() if len(parts)>3: > mapping[parts[1]]=parts[4] also, note that python indexes from zero, so this should be mapping[parts[0]]=parts[3] > origs=open("dummy.atomID").read().split() > print " ".join([mapping[orig] for orig in origs]) Emile From brad.hudson at gmail.com Tue May 17 17:58:38 2011 From: brad.hudson at gmail.com (Brad Hudson) Date: Tue, 17 May 2011 10:58:38 -0500 Subject: [Tutor] how to convert list of lists to dict Message-ID: I'm new to python and have a need to convert a 'list of lists' to a dictionary object. Can someone help me to convert data similar to the following using two different examples of a list comprehension and a for loop? Data is similar to the following: [['name=server1', 'state=active', 'ncpu=8', 'mem=8589934592', 'uptime=5784399'], ['name=server2', 'state=active', 'ncpu=32', 'mem=34359738368', 'uptime=5416796'], ['name=server3', 'state=inactive', 'ncpu=8', 'mem=8589934592', 'uptime=']] I'd like to convert the list data into a dictionary similar to the following: node['server1'] = {'state' : 'active', 'ncpu' : 8, 'mem' : 8589934592, 'uptime' : 5784399} node['server2'] = {'state' : 'active', 'ncpu' : 32, 'mem' : 34359738368, 'uptime' : 5416796} node['server3'] = {'state' : 'inactive', 'ncpu' : 8, 'mem' : 8589934592, 'uptime' : None} This would allow me to access information like: node['server1']['mem'] Thanks in advance, Brad -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue May 17 18:01:11 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 17 May 2011 09:01:11 -0700 Subject: [Tutor] multiprocessing for nested function In-Reply-To: References: Message-ID: On 5/17/2011 7:29 AM tax botsis said... > Part of my code includes the following script, which both shows a > progress bar (for as long as 'categorize_reports()' is executed) and > prints the fileid and the output of the 'document' function; the latter > is the one increasing the calculation time (please see my comment). Any > ideas on how to use all the cores of my CPU here? A python instance lives it life on a single processor. Accessing multiple cores requires you start multiple python instances. You'd need to restructure to provide some form of cooperative independent processing. Pyro, stackless, and twisted come to mind. It looks like the info at http://wiki.python.org/moin/ParallelProcessing is more up to date than my memory... Emile > > ... > def categorize_reports(): > if __name__ == '__main__': > root2 = Tkinter.Tk(className=' Processing Progress') > m = Meter(root2, relief='ridge', bd=3) > m.pack(fill='x') > i=0.0 > for fileid in fileids(): > m.set(i, 'Processing will take a few minutes...') > i=i+1.000/len(fileids()) > m.after(1000, lambda: _demo(m, i)) > print str(fileid), document(fileid) #this slows down the > process > root2.withdraw() > ... > > Thanks > Tax > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From andreengels at gmail.com Tue May 17 18:03:03 2011 From: andreengels at gmail.com (Andre Engels) Date: Tue, 17 May 2011 18:03:03 +0200 Subject: [Tutor] Please help, the program is not behaving as I want In-Reply-To: References: Message-ID: I am not able to check your code (I get an error message about the usage of urllib, but that might be a difference in Python installations); however, my first guess is that you neglected to take case into account: The page contains the text "Water", not "water", so if you input "water", halal_haram_status will be -1. As another remark, find() will give the value of the _beginning_ of the match, thus when all goes right, what is returned will contain part of the text sought rather than "Halal" or "Haram" - you will get "er Ha" for water, "anol " for ethanol and "k cho" for pork chops (also, ethanol is the same as alcohol, so I guess it should be haram). On Tue, May 17, 2011 at 5:20 PM, I. Dooba wrote: > I'm new to programming and have decided to start with Python following the > advice of experts including Eric S. Raymond. > So far I've learnt quite a lot from this list. > However, I've the following problem. > The program was designed (as part of my practice with Head First > Programming) to check whether an ingredient is Halal or Haram. > I've a simple table online where some ingredients are either halal or > ?haram. > For example, if the user enters "water" the program is supposed to tell him > that it's halal; > but it's returning ">" and other characters I don't want to see. > What am I doing wrong? > import urllib.request > page = > urllib.request.urlopen("http://halalingredients.theparleyonline.com/") > text = page.read().decode("utf8") > > halal_haram_status = text.find(input("Enter the ingredient: ?")) > begin_final_status = halal_haram_status + 3 > end_final_status = begin_final_status + 5 > status = text[begin_final_status:end_final_status] > print(status) > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Andr? Engels, andreengels at gmail.com From joel.goldstick at gmail.com Tue May 17 18:13:51 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 17 May 2011 12:13:51 -0400 Subject: [Tutor] Please help, the program is not behaving as I want In-Reply-To: References: Message-ID: On Tue, May 17, 2011 at 11:20 AM, I. Dooba wrote: > I'm new to programming and have decided to start with Python following the > advice of experts including Eric S. Raymond. > So far I've learnt quite a lot from this list. > > However, I've the following problem. > > The program was designed (as part of my practice with Head First > Programming) to check whether an ingredient is Halal or Haram. > I've a simple table online where some ingredients are either halal or > haram. > You don't have a simple table in this webpage. You should use 'View Source" from your browser to actually see what your program is reading. What you do have quite far down are words like this between

tags:

Water Halal

Ethanol Halal

Blood Haram

Alcohol Haram

Benzoic Acid Halal

> > For example, if the user enters "water" the program is supposed to tell him > that it's halal; > but it's returning ">" and other characters I don't want to see. > > What am I doing wrong? > > import urllib.request > > this gets access to the webpage > page = urllib.request.urlopen(" > http://halalingredients.theparleyonline.com/") > this reads the whole page into your text variable > text = page.read().decode("utf8") > > this lets you type in a word, and uses that word to see if it can find it in the text. If it does, it returns the index where it finds the start of the word > halal_haram_status = text.find(input("Enter the ingredient: ")) > if it can't find a match it will return -1 This is strange. I believe you want to add the length of the word you input plus 1 (for the space) to the index you found above. > begin_final_status = halal_haram_status + 3 > This is ok since halal and haram are both 5 characters long > end_final_status = begin_final_status + 5 > status = text[begin_final_status:end_final_status] > print(status) > > > Be careful to type the word exactly as printed. If you the a word that is not in your list, you might get what looks like nonsense since it will just look to the 5 characters after the word you give it to find > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Since I'm on my lunch break I thought I'd dig into this -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue May 17 18:30:25 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 17 May 2011 09:30:25 -0700 Subject: [Tutor] how to convert list of lists to dict In-Reply-To: References: Message-ID: On 5/17/2011 8:58 AM Brad Hudson said... > I'm new to python and have a need to convert a 'list of lists' to a > dictionary object. Can someone help me to convert data similar to the > following using two different examples of a list comprehension and a for > loop? > > Data is similar to the following: > [['name=server1', 'state=active', 'ncpu=8', 'mem=8589934592', > 'uptime=5784399'], ['name=server2', 'state=active', 'ncpu=32', > 'mem=34359738368', 'uptime=5416796'], ['name=server3', 'state=inactive', > 'ncpu=8', 'mem=8589934592', 'uptime=']] > > I'd like to convert the list data into a dictionary similar to the > following: > node['server1'] = {'state' : 'active', 'ncpu' : 8, 'mem' : 8589934592, > 'uptime' : 5784399} > node['server2'] = {'state' : 'active', 'ncpu' : 32, 'mem' : 34359738368, > 'uptime' : 5416796} > node['server3'] = {'state' : 'inactive', 'ncpu' : 8, 'mem' : 8589934592, > 'uptime' : None} > > This would allow me to access information like: > node['server1']['mem'] > You'll want to use dict, dict([jj[0].split("=")[1],jj[1:]] for jj in LofL) Emile From lina.lastname at gmail.com Tue May 17 18:36:07 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 18 May 2011 00:36:07 +0800 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: Thanks, it works. On Tue, May 17, 2011 at 11:53 PM, Emile van Sebille wrote: > On 5/17/2011 8:31 AM lina said... >> >> Following Michiel's code (a little adjustment was done): >> > > Well. you're almost there. ?The error you're getting > is likely due to splitting an empty line, then referencing > the [1] and [4] elements. > > After you split the line into parts, test to confirm > that the fields you need are there: > >> #!/bin/python >> >> mapping={} >> for line in open("confout.pdb").readlines(): >> ? parts=line.strip().split() > > ? ? if len(parts)>3: > >> ? mapping[parts[1]]=parts[4] > > also, note that python indexes from zero, so this should be > ? ? mapping[parts[0]]=parts[3] > >> origs=open("dummy.atomID").read().split() >> print " ".join([mapping[orig] for orig in origs]) > > > Emile > > _______________________________________________ > 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 Tue May 17 18:47:17 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 18 May 2011 00:47:17 +0800 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: A further question: I don't know how can I get the final output is unique? #!/bin/python mapping={} for line in open("confout.pdb").readlines(): parts=line.strip().split() if len(parts)>6: mapping[parts[1]]=parts[4]+parts[3] origs=open("dummy.atomID").read().split() print " ".join([mapping[orig] for orig in origs]) Thanks again, On Wed, May 18, 2011 at 12:36 AM, lina wrote: > Thanks, it works. > > On Tue, May 17, 2011 at 11:53 PM, Emile van Sebille wrote: >> On 5/17/2011 8:31 AM lina said... >>> >>> Following Michiel's code (a little adjustment was done): >>> >> >> Well. you're almost there. ?The error you're getting >> is likely due to splitting an empty line, then referencing >> the [1] and [4] elements. >> >> After you split the line into parts, test to confirm >> that the fields you need are there: >> >>> #!/bin/python >>> >>> mapping={} >>> for line in open("confout.pdb").readlines(): >>> ? parts=line.strip().split() >> >> ? ? if len(parts)>3: >> >>> ? mapping[parts[1]]=parts[4] >> >> also, note that python indexes from zero, so this should be >> ? ? mapping[parts[0]]=parts[3] >> >>> origs=open("dummy.atomID").read().split() >>> print " ".join([mapping[orig] for orig in origs]) >> >> >> Emile >> >> _______________________________________________ >> 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 idooba at gmail.com Tue May 17 18:54:08 2011 From: idooba at gmail.com (I. Dooba) Date: Wed, 18 May 2011 00:54:08 +0800 Subject: [Tutor] Please help, the program is not behaving as I want Message-ID: Thanks, Joel Goldstick There is no error message. But the program is returning incomplete or too many characters. For example, instead of "Halal" it will return "l Hala" or "nol" depending on the length of the word the user inputs. Since I can't predict the words the user will search for, I'm finding it difficult to tackle the problem. ___________ I. Dooba Hybrid Intelligence & Digital Infrastructure Research Group Universiti Teknologi PETRONAS +6014 644 5086 ibraheem_g01318 at utp.edu.my -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Tue May 17 19:10:04 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 17 May 2011 12:10:04 -0500 Subject: [Tutor] RuntimeError: file does not exist Message-ID: Hello list!! I'm using a python dll to create images out from shapefiles. I import a python module and its functions, when I want to use this library, I get a message which tells me the file I want to work with doesn't exist, but it does. I'm running the script from Windows. This is the code: import mapnik import os,fnmatc file_list = [] folders = None for root, folders, files in os.walk( "C:\\" ): for filename in fnmatch.filter(files, '*.shp'): file_list.append(os.path.join(root, filename)) for row, filepath in enumerate(file_list, start=1): (ruta, filename) = os.path.split(filepath) i = archivo[0]+'.png' m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") m.background = mapnik.Color('#f2eff9') s = mapnik.Style() r=mapnik.Rule() r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('steelblue'))) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,i, 'png') print "Listo" I get the next error: Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import imagen_shp Traceback (most recent call last): File "", line 1, in File "imagen_shp.py", line 32, in lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) File "C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py", line 282, in Shapefile return CreateDatasource(keywords) RuntimeError: C:\?ndice.shp/C:\?ndice does not exist >>> I also reviewed the line which causes the error, it's a script from the mapnik library: def Shapefile(**keywords): """Create a Shapefile Datasource. Required keyword arguments: file -- path to shapefile without extension Optional keyword arguments: base -- path prefix (default None) encoding -- file encoding (default 'utf-8') >>> from mapnik import Shapefile, Layer >>> shp = Shapefile(base='/home/mapnik/data',file='world_borders') >>> lyr = Layer('Shapefile Layer') >>> lyr.datasource = shp """ keywords['type'] = 'shape' return CreateDatasource(keywords) Does anyone could help me? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 17 19:10:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 May 2011 18:10:10 +0100 Subject: [Tutor] how to convert list of lists to dict References: Message-ID: "Brad Hudson" wrote > dictionary object. Can someone help me to convert data similar to > the > following using two different examples of a list comprehension and a > for > loop? Given that you want more than one method I assume this is a homwework assignment rather than a practical problem? If so we would prefer that you showed us what you tried and we can then help you fix it rather than just offer you solutions from which you will learn little. > Data is similar to the following: > [['name=server1', 'state=active', 'ncpu=8', 'mem=8589934592', > 'uptime=5784399'], ['name=server2', 'state=active', 'ncpu=32', > 'mem=34359738368', 'uptime=5416796'], ['name=server3', > 'state=inactive', > 'ncpu=8', 'mem=8589934592', 'uptime=']] > > I'd like to convert the list data into a dictionary similar to the > following: > node['server1'] = {'state' : 'active', 'ncpu' : 8, 'mem' : > 8589934592, > 'uptime' : 5784399} > node['server2'] = {'state' : 'active', 'ncpu' : 32, 'mem' : > 34359738368, > 'uptime' : 5416796} > node['server3'] = {'state' : 'inactive', 'ncpu' : 8, 'mem' : > 8589934592, > 'uptime' : None} How did you think it should be done? Maybe if we start from there? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From brad.hudson at gmail.com Tue May 17 19:19:57 2011 From: brad.hudson at gmail.com (Brad Hudson) Date: Tue, 17 May 2011 12:19:57 -0500 Subject: [Tutor] how to convert list of lists to dict In-Reply-To: References: Message-ID: On Tue, May 17, 2011 at 11:30 AM, Emile van Sebille wrote: > On 5/17/2011 8:58 AM Brad Hudson said... > > I'm new to python and have a need to convert a 'list of lists' to a >> dictionary object. Can someone help me to convert data similar to the >> following using two different examples of a list comprehension and a for >> loop? >> >> Data is similar to the following: >> [['name=server1', 'state=active', 'ncpu=8', 'mem=8589934592', >> 'uptime=5784399'], ['name=server2', 'state=active', 'ncpu=32', >> 'mem=34359738368', 'uptime=5416796'], ['name=server3', 'state=inactive', >> 'ncpu=8', 'mem=8589934592', 'uptime=']] >> >> I'd like to convert the list data into a dictionary similar to the >> following: >> node['server1'] = {'state' : 'active', 'ncpu' : 8, 'mem' : 8589934592, >> 'uptime' : 5784399} >> node['server2'] = {'state' : 'active', 'ncpu' : 32, 'mem' : 34359738368, >> 'uptime' : 5416796} >> node['server3'] = {'state' : 'inactive', 'ncpu' : 8, 'mem' : 8589934592, >> 'uptime' : None} >> >> This would allow me to access information like: >> node['server1']['mem'] >> >> > You'll want to use dict, > > dict([jj[0].split("=")[1],jj[1:]] for jj in LofL) > > Emile > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks for the quick response Emile! However, this only seems to solve part of the problem. It seems to set up a single key value dictionary (e.g. {'server1' : ['state=active', 'ncpu=8']}, etc.)I'm looking for more of a multi-way dictionary to be able to access down different paths such as: mymem = node['server1']['mem'] myncpu = node['server1']['ncpu'] I want to be able to change the list part of the example you provided into a sub-dictionary similar to (preferably done directly from the original data): { 'server1' : { 'state' : 'active', 'ncpu' : 8}, 'server2' : {'state' : 'active', 'ncpu' : 32}} -------------- next part -------------- An HTML attachment was scrubbed... URL: From kpguy1975 at gmail.com Tue May 17 19:20:42 2011 From: kpguy1975 at gmail.com (Vikram K) Date: Tue, 17 May 2011 13:20:42 -0400 Subject: [Tutor] reading very large files Message-ID: I wish to read a large data file (file size is around 1.8 MB) and manipulate the data in this file. Just reading and writing the first 500 lines of this file is causing a problem. I wrote: fin = open('gene-GS00471-DNA_B01_ 1101_37-ASM.tsv') count = 0 for i in fin.readlines(): print i count += 1 if count >= 500: break and got this error msg: Traceback (most recent call last): File "H:\genome_4_omics_study\GS000003696-DID\GS00471-DNA_B01_1101_37-ASM\GS00471-DNA_B01\ASM\gene-GS00471-DNA_B01_1101_37-ASM.tsv\test.py", line 3, in for i in fin.readlines(): MemoryError ------- is there a way to stop python from slurping all the file contents at once? -------------- next part -------------- An HTML attachment was scrubbed... URL: From brad.hudson at gmail.com Tue May 17 19:47:56 2011 From: brad.hudson at gmail.com (Brad Hudson) Date: Tue, 17 May 2011 12:47:56 -0500 Subject: [Tutor] how to convert list of lists to dict In-Reply-To: References: Message-ID: On Tue, May 17, 2011 at 12:10 PM, Alan Gauld wrote: > > Given that you want more than one method I assume > this is a homwework assignment rather than a practical > problem? If so we would prefer that you showed us what > you tried and we can then help you fix it rather than > just offer you solutions from which you will learn little. > It's really more that I'm a newbie to python. Trying to translate from perl to python in my head... How did you think it should be done? > Maybe if we start from there? > This is where I started (not elegant at all, but learning): def get_vms(): import subprocess p = subprocess.Popen(['/usr/sbin/ldm', 'ls', '-p'], stdout=subprocess.PIPE).communicate()[0] p = p.split('\n') [p.remove(item) for item in p if not item.startswith('DOMAIN')] p = [item.replace('DOMAIN|', '') for item in p] p = [i.split('|') for i in p] print p The results are as follows: Python 2.4.6 (#1, Dec 13 2009, 23:45:11) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import subprocess >>> p = subprocess.Popen(['/usr/sbin/ldm', 'ls', '-p'], stdout=subprocess.PIPE).communicate()[0] >>> p 'VERSION 1.5\nDOMAIN|name=primary|state=active|flags=-n-cv-|cons=UART|ncpu=8|mem=8589934592|util=1.0|uptime=5790996\nDOMAIN|name=ilhsf002v001|state=active|flags=-n----|cons=5000|ncpu=32|mem=34359738368|util=0.0|uptime=5423393\nDOMAIN|name=ilhsf002v002|state=inactive|flags=------|cons=|ncpu=8|mem=8589934592|util=|uptime=\n' >>> p = p.split('\n') >>> p ['VERSION 1.5', 'DOMAIN|name=primary|state=active|flags=-n-cv-|cons=UART|ncpu=8|mem=8589934592|util=1.0|uptime=5790996', 'DOMAIN|name=ilhsf002v001|state=active|flags=-n----|cons=5000|ncpu=32|mem=34359738368|util=0.0|uptime=5423393', 'DOMAIN|name=ilhsf002v002|state=inactive|flags=------|cons=|ncpu=8|mem=8589934592|util=|uptime=', ''] >>> [p.remove(item) for item in p if not item.startswith('DOMAIN')] [None, None] >>> p ['DOMAIN|name=primary|state=active|flags=-n-cv-|cons=UART|ncpu=8|mem=8589934592|util=1.0|uptime=5790996', 'DOMAIN|name=ilhsf002v001|state=active|flags=-n----|cons=5000|ncpu=32|mem=34359738368|util=0.0|uptime=5423393', 'DOMAIN|name=ilhsf002v002|state=inactive|flags=------|cons=|ncpu=8|mem=8589934592|util=|uptime='] >>> p = [item.replace('DOMAIN|', '') for item in p] >>> p ['name=primary|state=active|flags=-n-cv-|cons=UART|ncpu=8|mem=8589934592|util=1.0|uptime=5790996', 'name=ilhsf002v001|state=active|flags=-n----|cons=5000|ncpu=32|mem=34359738368|util=0.0|uptime=5423393', 'name=ilhsf002v002|state=inactive|flags=------|cons=|ncpu=8|mem=8589934592|util=|uptime='] >>> p = [i.split('|') for i in p] >>> >>> p [['name=primary', 'state=active', 'flags=-n-cv-', 'cons=UART', 'ncpu=8', 'mem=8589934592', 'util=1.0', 'uptime=5790996'], ['name=ilhsf002v001', 'state=active', 'flags=-n----', 'cons=5000', 'ncpu=32', 'mem=34359738368', 'util=0.0', 'uptime=5423393'], ['name=ilhsf002v002', 'state=inactive', 'flags=------', 'cons=', 'ncpu=8', 'mem=8589934592', 'util=', 'uptime=']] >>> Goal: To take the results from a process, parse the data into a dictionary object that can be returned from the function for use in a script. The dictionary object needs to be able to access sub-data (e.g. state, memory, cpus, etc.) from the key (server names). -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Tue May 17 19:49:13 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 17 May 2011 19:49:13 +0200 Subject: [Tutor] reading very large files In-Reply-To: References: Message-ID: <1305654553.1899.11.camel@Nokia-N900> On Tue, 17 May 2011, 19:20:42 CEST, Vikram K wrote: > I wish to read a large data file (file size is around 1.8 MB) and > manipulate the data in this file. Just reading and writing the first 500 > lines of this file is causing a problem. I wrote: Unless you are very constrained memory wise 1.8 Mb is not that much. Maybe you meant Gb instead of Mb? > fin = open('gene-GS00471-DNA_B01_ > 1101_37-ASM.tsv') > count = 0 > for i in fin.readlines(): readlines() will read the whole file and store it in memory. If the file is 1.8 Gb then I can understand this will cause you to run out of memory. Normally for file like objects python you iterate over it directly which means python will only read the lines it needs instead of the whole file at once. So my suggestion is to remove .readlines() and see how it goes. Greets Sander >? ? ? ? print i >? ? ? ? count += 1 >? ? ? ? if count >= 500: >? ? ? ? ? ? ? ? break > > and got this error msg: > > Traceback (most recent call last): >? ? File > "H:\genome_4_omics_study\GS000003696-DID\GS00471-DNA_B01_1101_37-ASM\GS00471-DNA_B01\ASM\gene-GS00471-DNA_B01_1101_37-ASM.tsv\test.py", > line 3, in >? ? ? ? for i in fin.readlines(): > MemoryError -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue May 17 19:51:50 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 17 May 2011 10:51:50 -0700 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: On 5/17/2011 9:47 AM lina said... > A further question: I don't know how can I get the final output is unique? That'll require some rework. The mapping container replaces mapping[parts[0]] each time it encounters another parts[0]. You can test if you are about to add a new entry or replace an existing one with "if parts[0] in mapping:" if that helps. Emile > > #!/bin/python > > mapping={} > for line in open("confout.pdb").readlines(): > parts=line.strip().split() > if len(parts)>6: > mapping[parts[1]]=parts[4]+parts[3] > origs=open("dummy.atomID").read().split() > print " ".join([mapping[orig] for orig in origs]) > > Thanks again, > > > > On Wed, May 18, 2011 at 12:36 AM, lina wrote: >> Thanks, it works. >> >> On Tue, May 17, 2011 at 11:53 PM, Emile van Sebille wrote: >>> On 5/17/2011 8:31 AM lina said... >>>> >>>> Following Michiel's code (a little adjustment was done): >>>> >>> >>> Well. you're almost there. The error you're getting >>> is likely due to splitting an empty line, then referencing >>> the [1] and [4] elements. >>> >>> After you split the line into parts, test to confirm >>> that the fields you need are there: >>> >>>> #!/bin/python >>>> >>>> mapping={} >>>> for line in open("confout.pdb").readlines(): >>>> parts=line.strip().split() >>> >>> if len(parts)>3: >>> >>>> mapping[parts[1]]=parts[4] >>> >>> also, note that python indexes from zero, so this should be >>> mapping[parts[0]]=parts[3] >>> >>>> origs=open("dummy.atomID").read().split() >>>> print " ".join([mapping[orig] for orig in origs]) >>> >>> >>> Emile >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> >> -- >> Best Regards, >> >> lina >> > > > From malaclypse2 at gmail.com Tue May 17 19:54:53 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 17 May 2011 13:54:53 -0400 Subject: [Tutor] reading very large files In-Reply-To: References: Message-ID: On Tue, May 17, 2011 at 1:20 PM, Vikram K wrote: > I wish to read a large data file (file size is around 1.8 MB) and manipulate > the data in this file. Just reading and writing the first 500 lines of this > file is causing a problem. I wrote: ... > > Traceback (most recent call last): > ? File > "H:\genome_4_omics_study\GS000003696-DID\GS00471-DNA_B01_1101_37-ASM\GS00471-DNA_B01\ASM\gene-GS00471-DNA_B01_1101_37-ASM.tsv\test.py", > line 3, in > ??? for i in fin.readlines(): > MemoryError > > ------- > is there a way to stop python from slurping all the ?file contents at once? Well, readlines() does read in a whole file at once, splitting it into a list with one item in the list per line in the file. I'm surprised that a 1.8 MB file is causing you to hit a MemoryError though -- that isn't a very big file. If you're really just trying to process one line at a time, you should just use "for i in fin:", which will read one line at a time into memory. No need to read the whole thing at once. -- Jerry From emile at fenx.com Tue May 17 19:56:15 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 17 May 2011 10:56:15 -0700 Subject: [Tutor] how to convert list of lists to dict In-Reply-To: References: Message-ID: On 5/17/2011 10:19 AM Brad Hudson said... > Thanks for the quick response Emile! However, this only seems to solve > part of the problem. Yes -- I figured that by understanding the one-liner I replied with you'd be able to construct the missing part. And then by restructuring to a loop you'd get the second half. I thought that pointing you to dict() by itself probably wouldn't have gotten you far. Where are you on this now? Emile From emile at fenx.com Tue May 17 19:58:26 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 17 May 2011 10:58:26 -0700 Subject: [Tutor] reading very large files In-Reply-To: References: Message-ID: On 5/17/2011 10:20 AM Vikram K said... > I wish to read a large data file (file size is around 1.8 MB) and > manipulate the data in this file. Just reading and writing the first 500 > lines of this file is causing a problem. I wrote: > > fin = open('gene-GS00471-DNA_B01_ > 1101_37-ASM.tsv') > count = 0 > for i in fin.readlines(): > print i > count += 1 > if count >= 500: > break > > and got this error msg: > > Traceback (most recent call last): > File > "H:\genome_4_omics_study\GS000003696-DID\GS00471-DNA_B01_1101_37-ASM\GS00471-DNA_B01\ASM\gene-GS00471-DNA_B01_1101_37-ASM.tsv\test.py", > line 3, in > for i in fin.readlines(): > MemoryError > > ------- > is there a way to stop python from slurping all the file contents at once? > > Yes -- look at the optional parameters for open: ActivePython 2.6.1.1 (ActiveState Software Inc.) based on Python 2.6.1 (r261:67515, Dec 5 2008, 13:58:38) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(open) Help on built-in function open in module __builtin__: open(...) open(name[, mode[, buffering]]) -> file object Open a file using the file() type, returns a file object. This is the preferred way to open a file. >>> Emile From emile at fenx.com Tue May 17 20:00:24 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 17 May 2011 11:00:24 -0700 Subject: [Tutor] RuntimeError: file does not exist In-Reply-To: References: Message-ID: On 5/17/2011 10:10 AM Susana Iraiis Delgado Rodriguez said... > Hello list!! > > I'm using a python dll to create images out from shapefiles. I import a > python module and its functions, when I want to use this library, I get > a message which tells me the file I want to work with doesn't exist, but > it does. I'm running the script from Windows. This is the code: > import mapnik > import os,fnmatc > file_list = [] > folders = None > for root, folders, files in os.walk( "C:\\" ): > for filename in fnmatch.filter(files, '*.shp'): > file_list.append(os.path.join(root, filename)) > for row, filepath in enumerate(file_list, start=1): > (ruta, filename) = os.path.split(filepath) > i = archivo[0]+'.png' > m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") > m.background = mapnik.Color('#f2eff9') > s = mapnik.Style() > r=mapnik.Rule() > r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('steelblue'))) > > r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1)) > s.rules.append(r) > m.append_style('My Style',s) > lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") > lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) > lyr.styles.append('My Style') > m.layers.append(lyr) > m.zoom_to_box(lyr.envelope()) > mapnik.render_to_file(m,i, 'png') > print "Listo" > I get the next error: > Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import imagen_shp > Traceback (most recent call last): > File "", line 1, in > File "imagen_shp.py", line 32, in > lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) Without having actually dug into this, should base and file have the same value? Emile > File "C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py", > line 282, > in Shapefile > return CreateDatasource(keywords) > RuntimeError: C:\?ndice.shp/C:\?ndice does not exist > >>> > I also reviewed the line which causes the error, it's a script from the > mapnik library: > def Shapefile(**keywords): > """Create a Shapefile Datasource. > Required keyword arguments: > file -- path to shapefile without extension > Optional keyword arguments: > base -- path prefix (default None) > encoding -- file encoding (default 'utf-8') > >>> from mapnik import Shapefile, Layer > >>> shp = Shapefile(base='/home/mapnik/data',file='world_borders') > >>> lyr = Layer('Shapefile Layer') > >>> lyr.datasource = shp > """ > keywords['type'] = 'shape' > return CreateDatasource(keywords) > Does anyone could help me? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From susana.delgado_s at utzmg.edu.mx Tue May 17 20:28:53 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 17 May 2011 13:28:53 -0500 Subject: [Tutor] RuntimeError: file does not exist In-Reply-To: References: Message-ID: Hello Emile! Well, I changed the values because if I assigned different values, anyways I got the next error: Traceback (most recent call last): File "", line 1, in File "imagen_shp.py", line 32, in lyr.datasource = mapnik.Shapefile(base=raiz, file=archivo[0]) File "C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py", line 282, in Shapefile return CreateDatasource(keywords) RuntimeError: ?ndice does not exist 2011/5/17 Emile van Sebille > On 5/17/2011 10:10 AM Susana Iraiis Delgado Rodriguez said... > > Hello list!! >> >> I'm using a python dll to create images out from shapefiles. I import a >> python module and its functions, when I want to use this library, I get >> a message which tells me the file I want to work with doesn't exist, but >> it does. I'm running the script from Windows. This is the code: >> import mapnik >> import os,fnmatc >> file_list = [] >> folders = None >> for root, folders, files in os.walk( "C:\\" ): >> for filename in fnmatch.filter(files, '*.shp'): >> file_list.append(os.path.join(root, filename)) >> for row, filepath in enumerate(file_list, start=1): >> (ruta, filename) = os.path.split(filepath) >> i = archivo[0]+'.png' >> m = mapnik.Map(800,500,"+proj=latlong +datum=WGS84") >> m.background = mapnik.Color('#f2eff9') >> s = mapnik.Style() >> r=mapnik.Rule() >> r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('steelblue'))) >> >> >> r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1)) >> s.rules.append(r) >> m.append_style('My Style',s) >> lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") >> lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) >> lyr.styles.append('My Style') >> m.layers.append(lyr) >> m.zoom_to_box(lyr.envelope()) >> mapnik.render_to_file(m,i, 'png') >> print "Listo" >> I get the next error: >> Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit >> (Intel)] on >> win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import imagen_shp >> Traceback (most recent call last): >> File "", line 1, in >> File "imagen_shp.py", line 32, in >> lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) >> > > > Without having actually dug into this, should base and file have the same > value? > > Emile > > > File "C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py", >> line 282, >> in Shapefile >> return CreateDatasource(keywords) >> RuntimeError: C:\?ndice.shp/C:\?ndice does not exist >> >>> >> I also reviewed the line which causes the error, it's a script from the >> mapnik library: >> def Shapefile(**keywords): >> """Create a Shapefile Datasource. >> Required keyword arguments: >> file -- path to shapefile without extension >> Optional keyword arguments: >> base -- path prefix (default None) >> encoding -- file encoding (default 'utf-8') >> >>> from mapnik import Shapefile, Layer >> >>> shp = Shapefile(base='/home/mapnik/data',file='world_borders') >> >>> lyr = Layer('Shapefile Layer') >> >>> lyr.datasource = shp >> """ >> keywords['type'] = 'shape' >> return CreateDatasource(keywords) >> Does anyone could help me? >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From motoom at xs4all.nl Tue May 17 20:30:36 2011 From: motoom at xs4all.nl (Michiel Overtoom) Date: Tue, 17 May 2011 20:30:36 +0200 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: <4DD2BECC.5020801@xs4all.nl> On 2011-05-17 18:47, lina wrote: > A further question: I don't know how can I get the final output is unique? Unique in what way? You mean that in file1 (confout.pdb?) there could be more values for the same key? or should duplicate lines in the output be condensed to one line? Maybe if you were more descriptive with what your goal and your source data is, your programming problem is easier to solve. [It could be that you're not comfortable discussing this on a public mailing list, but then, this is python-tutor. If you require hands-on help with complex programming problems in your work field, or even just working solutions, it might be more advantageous to hire me as a remote consultant (?120 per hour) which will enable you to offload difficult programming problems on me, and if you want, I'll throw in some online Python lessons via Skype in as well ;-) ] Greetings, -- "Good programming is not learned from generalities, but by seeing how significant programs can be made clean, easy to read, easy to maintain and modify, human-engineered, efficient, and reliable, by the application of common sense and good programming practices. Careful study and imitation of good programs leads to better writing." - Kernighan and Plauger, motto of 'Software Tools' From joel.goldstick at gmail.com Tue May 17 20:34:39 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 17 May 2011 14:34:39 -0400 Subject: [Tutor] Please help, the program is not behaving as I want In-Reply-To: References: Message-ID: On Tue, May 17, 2011 at 12:54 PM, I. Dooba wrote: > Thanks, Joel Goldstick > > There is no error message. > But the program is returning incomplete or too many characters. For > example, instead of "Halal" it will return "l Hala" > or "nol" depending on the length of the word the user inputs. > > Since I can't predict the words the user will search for, I'm finding it > difficult to tackle the problem. > ___________ > I. Dooba > Hybrid Intelligence & Digital Infrastructure Research Group > Universiti Teknologi PETRONAS > +6014 644 5086 > ibraheem_g01318 at utp.edu.my > > > I haven't read the book you are using, so I don't know what lessons they are trying to teach in this example. However, you should be aware that if you read the input into a variable first, then do the .find() method separately on the next line, you can later find out how long the word your user typed (google python length of string if you don't know how). Use this length value to add to the start of your index so that you can start your result at the beginning of Halal or Haram. Then at least, if the word is in your list you will get the answer you expect. > _______________________________________________ > 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 ramit.prasad at jpmchase.com Tue May 17 20:56:00 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Tue, 17 May 2011 14:56:00 -0400 Subject: [Tutor] Please help, the program is not behaving as I want In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3F18FE0@EMARC112VS01.exchad.jpmchase.net> Start solving the problem by viewing the text around what is being returned. Look at the +- 10-100 characters from what is being returned. Where exactly on the page is the return coming from? Is this centered near where you expected it? If not, what could be causing that? If it is actually close (and not just an error that is returning something that looks close but is actually not related) to what you want then why are the boundaries for the slice not what you expect? Play around with the boundaries and see if you can get it closer. Goldstein's second email has narrowed down some of your problems, if you cannot find it. Since you are doing text matches, be careful of case. What if WAter is typed instead of Water or water (as Andre noted) is typed? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of I. Dooba Sent: Tuesday, May 17, 2011 11:54 AM To: tutor at python.org Subject: Re: [Tutor] Please help, the program is not behaving as I want Thanks, Joel Goldstick There is no error message. But the program is returning incomplete or too many characters. For example, instead of "Halal" it will return "l Hala" or "nol" depending on the length of the word the user inputs. Since I can't predict the words the user will search for, I'm finding it difficult to tackle the problem. ___________ I. Dooba Hybrid Intelligence & Digital Infrastructure Research Group Universiti Teknologi PETRONAS +6014 644 5086 ibraheem_g01318 at utp.edu.my This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From taxbotsis at gmail.com Tue May 17 21:40:53 2011 From: taxbotsis at gmail.com (tax botsis) Date: Tue, 17 May 2011 15:40:53 -0400 Subject: [Tutor] multiprocessing for nested function In-Reply-To: References: Message-ID: I am trying to start multiple instances using a for statement but this is not working. Has anyone tried affinity module? Tax 2011/5/17 Emile van Sebille > On 5/17/2011 7:29 AM tax botsis said... > > Part of my code includes the following script, which both shows a >> progress bar (for as long as 'categorize_reports()' is executed) and >> prints the fileid and the output of the 'document' function; the latter >> is the one increasing the calculation time (please see my comment). Any >> ideas on how to use all the cores of my CPU here? >> > > A python instance lives it life on a single processor. Accessing multiple > cores requires you start multiple python instances. You'd need to > restructure to provide some form of cooperative independent processing. > Pyro, stackless, and twisted come to mind. It looks like > the info at http://wiki.python.org/moin/ParallelProcessing is more up to > date than my memory... > > Emile > > > > >> ... >> def categorize_reports(): >> if __name__ == '__main__': >> root2 = Tkinter.Tk(className=' Processing Progress') >> m = Meter(root2, relief='ridge', bd=3) >> m.pack(fill='x') >> i=0.0 >> for fileid in fileids(): >> m.set(i, 'Processing will take a few minutes...') >> i=i+1.000/len(fileids()) >> m.after(1000, lambda: _demo(m, i)) >> print str(fileid), document(fileid) #this slows down the >> process >> root2.withdraw() >> ... >> >> Thanks >> Tax >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From glenuk at gmail.com Tue May 17 22:45:35 2011 From: glenuk at gmail.com (Glen Clark) Date: Tue, 17 May 2011 21:45:35 +0100 Subject: [Tutor] Looking for feedback on improving my code. Message-ID: Hello tutors, Have not posted in a while. Started learning python a while back but had to stop after a couple of weeks due to lack of time. Anyway pretty much forgotten most things but if anyone has time I would love some feedback on my application. My main aim to to learn python, as a hobby, and participate in some open source projects for fun. The code is in two files, one for functions and the main file: http://paste.pound-python.org/show/6770/ (pyDSFunctions.py) http://paste.pound-python.org/show/6773/ (main file) So yeah, I doubt I can write code like this with others so I would like to get feedback on how to make this team friendly I guess. Any newbie stuff I am doing that other coders might laugh at :P I like this program though, so I plan to work on it for a while. Stuff I will add later is, being able to store data collected so a user can dive into a sub-directory with out refreshing each time (takes a while) and also build a GUI (shouldnt be too hard as I am trying to make functions to make the transition easier.) Well thank you very much for readying my post! Core -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 17 22:51:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 May 2011 21:51:37 +0100 Subject: [Tutor] how to convert list of lists to dict References: Message-ID: "Brad Hudson" wrote > > Given that you want more than one method I assume > > this is a homwework assignment > It's really more that I'm a newbie to python. Trying to translate > from perl > to python in my head... OK, Thats fine, it just seemed odd that you asked for 3 solutions to the problem rather than one! > This is where I started (not elegant at all, but learning): > def get_vms(): > import subprocess Its best (and conventional) to do imports at the top of your modules outside function definition. > p = subprocess.Popen(['/usr/sbin/ldm', 'ls', '-p'], > stdout=subprocess.PIPE).communicate()[0] > p = p.split('\n') A more meaningful name than p might be helpful! :-) > [p.remove(item) for item in p if not > item.startswith('DOMAIN')] List comprehensions are intended for building lists. Don't use them as a loop to generate side-effects. This would be better with the explicit: for item in p: if not item.startswith('DOMAIN'): p.remove(item) > p = [item.replace('DOMAIN|', '') for item in p] > p = [i.split('|') for i in p] And while these are valid comprehensions you are looping over the same list many times so its probably better to fully process each line as yyou go using an explicit loop, So it becomes: items = [] for item in p: if not item.startswith('DOMAIN'): p.remove(item) else: items.append(item.replace('DOMAIN|', '').split('|')) print items That should leave you with a list of lists. You can now iterate over items to extract your dictionary keys and create the dictionary values associated with it. Or, instead of appending you could do the dictionary addition in the loop. But I'd suggest doing it via a second helper function that takes an item list and returns a dictionary. So it looks like: else: item = item.replace('DOMAIN|', '').split('|') mydict[item[n]] = buildItemDict(item) where n is whatever index yields your key... and buidItemDict is your helper function. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue May 17 23:01:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 May 2011 22:01:31 +0100 Subject: [Tutor] RuntimeError: file does not exist References: Message-ID: "Susana Iraiis Delgado Rodriguez" wrote > message which tells me the file I want to work with > doesn't exist, but it does. I don't believe you! :-) > Traceback (most recent call last):... > lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) > return CreateDatasource(keywords) > RuntimeError: C:\?ndice.shp/C:\?ndice does not exist That "file name" has two C: in it which I am pretty sure is an illegal path in Windows. Therfore the file cannot exist. You just need to build your path correctly I suspect. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From eire1130 at gmail.com Wed May 18 00:33:35 2011 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Tue, 17 May 2011 22:33:35 +0000 Subject: [Tutor] Looking for feedback on improving my code. In-Reply-To: References: Message-ID: <327657318-1305671616-cardhu_decombobulator_blackberry.rim.net-1466876317-@b3.c28.bise6.blackberry> Pretty cool how that site makes code formating wotk on my bb. The big thing I've noticed is, and I'm a total newbie btw, mind cap conventions. Use camel case and upper case and whatnot for class definitions. I think its a wothwhile habit to pick up. I keep thinking you're instantiating a class when you just calling a func. Instead of going string equals string plus cloud, you can go string plusequals cloud. I would toss the entire thing in a class. And make the funcs methods of your class. Sent from my Verizon Wireless BlackBerry -----Original Message----- From: Glen Clark Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Tue, 17 May 2011 21:45:35 To: tutor at python.org Subject: [Tutor] Looking for feedback on improving my code. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From s.charonis at gmail.com Wed May 18 02:10:47 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Wed, 18 May 2011 01:10:47 +0100 Subject: [Tutor] Indexing a List of Strings Message-ID: Greetings Python List, I have a motif sequence (a list of characters e.g. 'EAWLGHEYLHAMKGLLC') whose index I would like to return. The list contains 20 strings, each of which is close to 1000 characters long making it far too cumbersome to display an example. I would like to know if there is a way to return a pair of indices, one index where my sequence begins (at 'E' in the above case) and one index where my sequence ends (at 'C' in the above case). In short, if 'EAWLGHEYLHAMKGLLC' spans 17 characters is it possible to get something like 100 117, assuming it begins at 100th position and goes up until 117th character of my string. My loop goes as follows: for item in finalmotifs: for line in my_list: if item in line: print line.index(item) But this only returns a single number (e.g 119), which is the index at which my sequence begins. Is it possible to get a pair of indices that indicate beginning and end of substring? Many thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 18 02:27:32 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 May 2011 01:27:32 +0100 Subject: [Tutor] Indexing a List of Strings References: Message-ID: "Spyros Charonis" wrote > for item in finalmotifs: > for line in my_list: > if item in line: > print line.index(item) > > But this only returns a single number (e.g 119), which is the index > at which > my sequence begins. > > Is it possible to get a pair of indices that indicate beginning and > end of > substring? print line.index(item)+len(item) Presumably since its matching item the end index will be len(item) characters later? Or am I missing something? Alan G. From lina.lastname at gmail.com Wed May 18 05:22:50 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 18 May 2011 11:22:50 +0800 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: May I ask another question: where I can get some advanced, terse and powerful python tutorials. short but powerful and a bit hard to understand at first. Thanks again, On Wed, May 18, 2011 at 1:51 AM, Emile van Sebille wrote: > On 5/17/2011 9:47 AM lina said... >> >> A further question: ?I don't know how can I get the final output is >> unique? > > That'll require some rework. ?The mapping container replaces > mapping[parts[0]] each time it encounters another parts[0]. > You can test if you are about to add a new entry or replace > an existing one with "if parts[0] in mapping:" if that helps. > > Emile > > > > >> >> #!/bin/python >> >> mapping={} >> for line in open("confout.pdb").readlines(): >> ? ? parts=line.strip().split() >> ? ? if len(parts)>6: >> ? ? ? ? mapping[parts[1]]=parts[4]+parts[3] >> origs=open("dummy.atomID").read().split() >> print " ".join([mapping[orig] for orig in origs]) >> >> Thanks again, >> >> >> >> On Wed, May 18, 2011 at 12:36 AM, lina ?wrote: >>> >>> Thanks, it works. >>> >>> On Tue, May 17, 2011 at 11:53 PM, Emile van Sebille >>> ?wrote: >>>> >>>> On 5/17/2011 8:31 AM lina said... >>>>> >>>>> Following Michiel's code (a little adjustment was done): >>>>> >>>> >>>> Well. you're almost there. ?The error you're getting >>>> is likely due to splitting an empty line, then referencing >>>> the [1] and [4] elements. >>>> >>>> After you split the line into parts, test to confirm >>>> that the fields you need are there: >>>> >>>>> #!/bin/python >>>>> >>>>> mapping={} >>>>> for line in open("confout.pdb").readlines(): >>>>> ? parts=line.strip().split() >>>> >>>> ? ? if len(parts)>3: >>>> >>>>> ? mapping[parts[1]]=parts[4] >>>> >>>> also, note that python indexes from zero, so this should be >>>> ? ? mapping[parts[0]]=parts[3] >>>> >>>>> origs=open("dummy.atomID").read().split() >>>>> print " ".join([mapping[orig] for orig in origs]) >>>> >>>> >>>> Emile >>>> >>>> _______________________________________________ >>>> Tutor maillist ?- ?Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>> >>> >>> >>> -- >>> 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 lina.lastname at gmail.com Wed May 18 05:26:05 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 18 May 2011 11:26:05 +0800 Subject: [Tutor] how to read two files and substitute In-Reply-To: <4DD2BECC.5020801@xs4all.nl> References: <4DD2BECC.5020801@xs4all.nl> Message-ID: On Wed, May 18, 2011 at 2:30 AM, Michiel Overtoom wrote: > On 2011-05-17 18:47, lina wrote: > >> A further question: ?I don't know how can I get the final output is >> unique? > > Unique in what way? You mean that in file1 (confout.pdb?) there could be > more values for the same key? or should duplicate lines in the output be > condensed to one line? Maybe if you were more descriptive with what your > goal and your source data is, your programming problem is easier to solve. I tried using unique in command, for the final output it works. > > [It could be that you're not comfortable discussing this on a public mailing > list, but then, this is python-tutor. ?If you require hands-on help with > complex programming problems in your work field, or even just working Thank you very much for your offering. > solutions, it might be more advantageous to hire me as a remote consultant > (?120 per hour) which will enable you to offload difficult programming > problems on me, and if you want, I'll throw in some online Python lessons > via Skype in as well ;-) ] > > Greetings, > > > -- > "Good programming is not learned from generalities, but by seeing how > significant programs can be made clean, easy to read, easy to maintain > and modify, human-engineered, efficient, and reliable, by the application > of common sense and good programming practices. Careful study and > imitation of good programs leads to better writing." > ? ?- Kernighan and Plauger, motto of 'Software Tools' > > -- Best Regards, lina From jadesaturn at gmail.com Wed May 18 05:51:00 2011 From: jadesaturn at gmail.com (Adam Westrum) Date: Tue, 17 May 2011 20:51:00 -0700 Subject: [Tutor] Beginner needs help with tkinter and images Message-ID: I've got a basic program going right now, with 4 buttons. Forward backward right and left. Each button goes to an image of a colored circle. Problem i'm having is that when you click a button, the picture appears. When you click another button, a different picture appears, but the first picture remains. How do I get rid of the first picture when the second button is clicked? Additionally, I cant seem to import any pictures at all into tkinter. I get a tclerror saying that there is an error in the bitmap. Any help will be greatly appreciated. Here is a copy of my code/ import Tkinter from Tkinter import * import tkMessageBox root=Tk() frame=Frame(root) frame.pack() def forward(): forward=Tkinter.Canvas(root, bg="white", height=250, width=300) coord=10, 50, 240, 210 oval=forward.create_oval(coord, fill="blue") label=Label(root, text="This is the going forward image") label.pack forward.pack() def backward(): backward=Tkinter.Canvas(root, bg="white", height=250, width=300) coord=10, 50, 240, 210 oval=backward.create_oval(coord, fill="red") backward.pack() def left(): left=Tkinter.Canvas(root, bg="white", height=250, width=300) coord=10, 50, 240, 210 oval=left.create_oval(coord, fill="yellow") left.pack() def right(): right=Tkinter.Canvas(root, bg="white", height=250, width=300) coord=10, 50, 240, 210 oval=right.create_oval(coord, fill="green") right.pack() bottomframe=Frame(root) bottomframe.pack(side=BOTTOM) forwardbutton=Button(frame, command=forward, text="Forward", fg="blue") forwardbutton.pack(side=TOP) turnrightbutton=Button(frame, command=right, text="Turn Right", fg="blue") turnrightbutton.pack(side=RIGHT) turnleftbutton=Button(frame, command=left, text="Turn Left", fg="blue") turnleftbutton.pack(side=LEFT) backwardbutton=Button(frame, command=backward, text="Backward", fg="blue") backwardbutton.pack(side=BOTTOM) root.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Wed May 18 10:03:19 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 18 May 2011 13:33:19 +0530 Subject: [Tutor] Indexing a List of Strings In-Reply-To: References: Message-ID: Agreed that your original sequences are 1000 char long. But it helps to understand the problem better if you can give examples with smaller strings. Please can you post smaller examples? This will also help you test your code on your own inputs. On Wed, May 18, 2011 at 5:40 AM, Spyros Charonis wrote: > Greetings Python List, > > I have a motif sequence (a list of characters e.g. 'EAWLGHEYLHAMKGLLC') > whose index I would like to return. > The list contains 20 strings, each of which is close to 1000 characters > long making it far too cumbersome to display an example. > I would like to know if there is a way to return a pair of indices, one > index where my sequence begins (at 'E' in the above case) and > one index where my sequence ends (at 'C' in the above case). In short, if > 'EAWLGHEYLHAMKGLLC' spans 17 characters is it possible > to get something like 100 117, assuming it begins at 100th position and > goes up until 117th character of my string. My loop goes as > follows: > > for item in finalmotifs: > for line in my_list: > if item in line: > print line.index(item) > > But this only returns a single number (e.g 119), which is the index at > which my sequence begins. > > Is it possible to get a pair of indices that indicate beginning and end of > substring? > > Many thanks > > > > _______________________________________________ > 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 alan.gauld at btinternet.com Wed May 18 10:34:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 May 2011 09:34:01 +0100 Subject: [Tutor] Beginner needs help with tkinter and images References: Message-ID: "Adam Westrum" wrote > I've got a basic program going right now, with 4 buttons. Forward > backward > right and left. Each button goes to an image of a colored circle. > Problem > i'm having is that when you click a button, the picture appears. > When you > click another button, a different picture appears, but the first > picture > remains. You would need to clear the original Canvas (or unpack it). In fact you should only need a single Canvas and draw all the circles on that rather than creating a new Canvas per image... > Additionally, I cant seem to import any pictures at all into > tkinter. I get > a tclerror saying that there is an error in the bitmap. Look at the PhotoImage widget. You load one of those into your parent widget (Text or Canvas) and then change the associated file to change the image. It does only have a limited set of image types though so you may need to transform the images to match... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed May 18 10:41:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 May 2011 09:41:54 +0100 Subject: [Tutor] how to read two files and substitute References: Message-ID: "lina" wrote > where I can get some advanced, terse and powerful python tutorials. > short but powerful and a bit hard to understand at first. The Python web site has many tutorials listed: http://wiki.python.org/moin/BeginnersGuide/Programmers Your definition of advanced, terse and powerful may be different from ours so just take a look and pick one thatnlooks suitable. For very advanced topics you may bneed to go to many tutorials, one per subject area (for networking, GUI, database etc) And of course you could opt for dead-tree books and get "Python in a Nutshell" from O'Reilly. Or Essential Python by Dave Beasley. They both cover a lot of ground in a very terse format. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Wed May 18 11:06:07 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 18 May 2011 02:06:07 -0700 (PDT) Subject: [Tutor] can I walk or glob a website? Message-ID: <504485.54591.qm@web110716.mail.gq1.yahoo.com> Hello, How can I walk (as in os.walk) or glob a website? I want to download all the pdfs from a website (using urllib.urlretrieve), extract certain figures (using pypdf- is this flexible enough?) and make some statistics/graphs from those figures (using rpy and R). I forgot what the process of 'automatically downloading' is called again, something that sounds like 'whacking' (??) 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? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 18 11:18:20 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 May 2011 10:18:20 +0100 Subject: [Tutor] can I walk or glob a website? References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> Message-ID: "Albert-Jan Roskam" wrote > How can I walk (as in os.walk) or glob a website? I don't think there is a way to do that via the web. Of course if you have access to the web servers filesystem you can use os.walk to do it as for any other filesystem, but I don't think its generally possible over http. (And indeed it shouldn''t be for very good security reasons!) OTOH I've been wrong before! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From cindylee2321 at yahoo.com Wed May 18 11:19:41 2011 From: cindylee2321 at yahoo.com (Cindy Lee) Date: Wed, 18 May 2011 10:19:41 +0100 (BST) Subject: [Tutor] Sequencing Message-ID: <947967.89500.qm@web132207.mail.ird.yahoo.com> Hi Pyton Tutors thanks for adding me, I am new to Python and missed one of my classes and am not sure of my homework. We are currently on sequencing and are being asked to make a function that receives text as an argument and returns the same text, but with 1 added to each number. So far I have: def ReceiveAndReturn(): ?? ?sentence=raw_input("Give me a sentence with variables in it: ") ?? ? print ReceiveAndReturn could anyone give me any hints on what else needs to be added? -------------- next part -------------- An HTML attachment was scrubbed... URL: From Steve.Flynn at capita.co.uk Wed May 18 11:28:07 2011 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Wed, 18 May 2011 10:28:07 +0100 Subject: [Tutor] can I walk or glob a website? In-Reply-To: References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> Message-ID: Pardon the crappy quoting - forced to use Exchange. Top posted too... the shame. What about curl and libcurl? http://curl.haxx.se/ S. -----Original Message----- From: tutor-bounces+steve.flynn=capita.co.uk at python.org [mailto:tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of Alan Gauld Sent: Wednesday, May 18, 2011 10:18 AM To: tutor at python.org Subject: Re: [Tutor] can I walk or glob a website? "Albert-Jan Roskam" wrote > How can I walk (as in os.walk) or glob a website? I don't think there is a way to do that via the web. Of course if you have access to the web servers filesystem you can use os.walk to do it as for any other filesystem, but I don't think its generally possible over http. (And indeed it shouldn''t be for very good security reasons!) OTOH I've been wrong before! :-) This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From spawgi at gmail.com Wed May 18 11:28:07 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 18 May 2011 14:58:07 +0530 Subject: [Tutor] Sequencing In-Reply-To: <947967.89500.qm@web132207.mail.ird.yahoo.com> References: <947967.89500.qm@web132207.mail.ird.yahoo.com> Message-ID: I don't think we can solve your homework :). But regarding hint, try to think in terms of each number as part of list and then process the list. Also, consider the option if the numbers will be given as a string or as integers or float etc. Thanks. On Wed, May 18, 2011 at 2:49 PM, Cindy Lee wrote: > Hi Pyton Tutors thanks for adding me, > > I am new to Python and missed one of my classes and am not sure of my > homework. We are currently on sequencing and are being asked to make a > function that receives text as an argument and returns the same text, but > with 1 added to each number. So far I have: > > > def ReceiveAndReturn(): > > sentence=raw_input("Give me a sentence with variables in it: ") > > print ReceiveAndReturn > > > > could anyone give me any hints on what else needs to be added? > > _______________________________________________ > 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 davea at ieee.org Wed May 18 11:51:35 2011 From: davea at ieee.org (Dave Angel) Date: Wed, 18 May 2011 05:51:35 -0400 Subject: [Tutor] can I walk or glob a website? In-Reply-To: References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> Message-ID: <4DD396A7.9000201@ieee.org> On 01/-10/-28163 02:59 PM, Alan Gauld wrote: > > "Albert-Jan Roskam" wrote >> How can I walk (as in os.walk) or glob a website? > > I don't think there is a way to do that via the web. > Of course if you have access to the web servers filesystem you can use > os.walk to do it as for any other filesystem, but I don't think its > generally possible over http. (And indeed it shouldn''t be for very good > security reasons!) > > OTOH I've been wrong before! :-) > It has to be (more or less) possible. That's what google does for their search engine. Three broad issues. 1) Are you violating the terms of service of such a web site? Are you going to be doing this seldom enough that the bandwidth used won't be a DOS attack? Are there copyrights to the material you plan to download? Is the website protected by a login, by cookies, or a VPN? Does the website present a different view to different browsers, different OS's, or different target domains? 2) Websites vary enormously in their adherence to standards. There are many such standards, and browsers tend to be very tolerant of bugs in the site which will be painful for you to accomodate. And some of the extensions/features are very hard to parse, such as flash. Others, such as javascript, can make it hard to do it statically. 3) How important is it to do it reliably? Your code may work perfectly with a particular website, and next week they'll make a change which breaks your code entirely. Are you willing to rework the code each time that happens? Many sites have API's that you can use to access them. Sometimes this is a better answer. With all of that said, I'll point you to Beautiful Soup, as a library that'll parse a page of moderately correct html and give you the elements of it. If it's a static page, you can then walk the elements of the tree that Beautiful Soup gives you, and find all the content that interests you. You can also find all the web pages that the first one refers to, and recurse on that. Notice that you need to limit your scope, since many websites have direct and indirect links to most of the web. For example, you might only recurse into links that refer to the same domain. For many websites, that means you won't get it all. So you may want to supply a list of domains and/or subdomains that you're willing to recurse into. See http://pypi.python.org/pypi/BeautifulSoup/3.2.0 DaveA From davea at ieee.org Wed May 18 12:02:26 2011 From: davea at ieee.org (Dave Angel) Date: Wed, 18 May 2011 06:02:26 -0400 Subject: [Tutor] Sequencing In-Reply-To: <947967.89500.qm@web132207.mail.ird.yahoo.com> References: <947967.89500.qm@web132207.mail.ird.yahoo.com> Message-ID: <4DD39932.8090801@ieee.org> On 01/-10/-28163 02:59 PM, Cindy Lee wrote: > Hi Pyton Tutors thanks for adding me, > > I am new to Python and missed one of my classes and am not sure of my homework. We are currently on sequencing and are being asked to make a function that receives text as an argument and returns the same text, but with 1 added to each number. So far I have: > > > def ReceiveAndReturn(): > > sentence=raw_input("Give me a sentence with variables in it: ") > > print ReceiveAndReturn > > > > could anyone give me any hints on what else needs to be added? As for your code so far, you've omitted the parentheses in the call to ReceiveAndReturn. That's not a very complete assignment description. Without some example text, I can only guess what these "sentences" might be permitted to look like. So let me make a wild guess and see where it leads us. Suppose you assume that the numbers in the "sentence" will be unsigned (positive) integers, and that they will be separated from surrounding characters by whitespace. That's a restrictive assumption, since a sentence might end with a number, and therefore there might be a period, not a space after it. Similarly, a list of numbers might have commas, etc. Assume also that extra spaces are irrelevant, so that one space between each word is fine. So you're looking to parse a 'sentence' like: Joe had 44 baskets and 3 of them were broken. What you might want to do is split that string by whitespace, then loop through the resulting list, discovering any tokens that start with a digit. If it starts with a digit, convert it to an int, add one, and convert it back to a string. Then join the tokens (strings) back together into a single string (using a space character), and print it out. In my description I deliberately used several python keywords and library function names, so that you might be able to search them out in the python docs, to see how to apply them. DaveA From cindylee2321 at yahoo.com Wed May 18 12:27:41 2011 From: cindylee2321 at yahoo.com (Cindy Lee) Date: Wed, 18 May 2011 11:27:41 +0100 (BST) Subject: [Tutor] Sequencing In-Reply-To: <4DD39932.8090801@ieee.org> References: <947967.89500.qm@web132207.mail.ird.yahoo.com> <4DD39932.8090801@ieee.org> Message-ID: <477587.15922.qm@web132209.mail.ird.yahoo.com> Thanks for the advice. I seem to keep getting the same errror: >> help(str.__add__) Help on wrapper_descriptor: __add__(...) ?? ?x.__add__(y) <==> x+y ________________________________ From: Dave Angel To: Cindy Lee Cc: "tutor at python.org" Sent: Wednesday, 18 May 2011, 3:02 Subject: Re: [Tutor] Sequencing On 01/-10/-28163 02:59 PM, Cindy Lee wrote: > Hi Pyton Tutors thanks for adding me, > > I am new to Python and missed one of my classes and am not sure of my homework. We are currently on sequencing and are being asked to make a function that receives text as an argument and returns the same text, but with 1 added to each number. So far I have: > > > def ReceiveAndReturn(): > >? ? ? sentence=raw_input("Give me a sentence with variables in it: ") > > print ReceiveAndReturn > > > > could anyone give me any hints on what else needs to be added? As for your code so far, you've omitted the parentheses in the call to ReceiveAndReturn. That's not a very complete assignment description.? Without some example text, I can only guess what these "sentences" might be permitted to look like.? So let me make a wild guess and see where it leads us. Suppose you assume that the numbers in the "sentence" will be unsigned (positive) integers, and that they will be separated from surrounding characters by whitespace.? That's a restrictive assumption, since a sentence might end with a number, and therefore there might be a period, not a space after it.? Similarly, a list of numbers might have commas, etc.? Assume also that extra spaces are irrelevant, so that one space between each word is fine. So you're looking to parse a 'sentence' like: ? Joe had 44 baskets and 3 of them were broken. What you might want to do is split that string by whitespace, then loop through the resulting list, discovering any tokens that start with a digit.? If it starts with a digit, convert it to an int, add one, and convert it back to a string. Then join the tokens (strings) back together into a single string (using a space character), and print it out. In my description I deliberately used several python keywords and library function names, so that you might be able to search them out in the python docs, to see how to apply them. DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Wed May 18 12:37:34 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 18 May 2011 11:37:34 +0100 Subject: [Tutor] Sequencing In-Reply-To: <477587.15922.qm@web132209.mail.ird.yahoo.com> References: <947967.89500.qm@web132207.mail.ird.yahoo.com> <4DD39932.8090801@ieee.org> <477587.15922.qm@web132209.mail.ird.yahoo.com> Message-ID: On Wed, May 18, 2011 at 11:27 AM, Cindy Lee wrote: > Thanks for the advice. I seem to keep getting the same errror: > Any advise? Also, is the _add_ string something I should be using? >>>> help(str.__add__) > Help on wrapper_descriptor: > __add__(...) > ?? ?x.__add__(y) <==> x+y No, not really. What you want to do is to parse the string given, and then edit the values in place. > ________________________________ > From: Dave Angel > To: Cindy Lee > Cc: "tutor at python.org" > Sent: Wednesday, 18 May 2011, 3:02 > Subject: Re: [Tutor] Sequencing > > On 01/-10/-28163 02:59 PM, Cindy Lee wrote: >> Hi Pyton Tutors thanks for adding me, >> >> I am new to Python and missed one of my classes and am not sure of my >> homework. We are currently on sequencing and are being asked to make a >> function that receives text as an argument and returns the same text, but >> with 1 added to each number. So far I have: >> >> >> def ReceiveAndReturn(): >> >>? ? ? sentence=raw_input("Give me a sentence with variables in it: ") >> >> print ReceiveAndReturn >> >> >> >> could anyone give me any hints on what else needs to be added? > > As for your code so far, you've omitted the parentheses in the call to > ReceiveAndReturn. > > > > That's not a very complete assignment description.? Without some example > text, I can only guess what these "sentences" might be permitted to look > like.? So let me make a wild guess and see where it leads us. > > Suppose you assume that the numbers in the "sentence" will be unsigned > (positive) integers, and that they will be separated from surrounding > characters by whitespace.? That's a restrictive assumption, since a sentence > might end with a number, and therefore there might be a period, not a space > after it.? Similarly, a list of numbers might have commas, etc.? Assume also > that extra spaces are irrelevant, so that one space between each word is > fine. > > So you're looking to parse a 'sentence' like: > > ? Joe had 44 baskets and 3 of them were broken. > > What you might want to do is split that string by whitespace, then loop > through the resulting list, discovering any tokens that start with a digit. > If it starts with a digit, convert it to an int, add one, and convert it > back to a string. > > Then join the tokens (strings) back together into a single string (using a > space character), and print it out. > > In my description I deliberately used several python keywords and library > function names, so that you might be able to search them out in the python > docs, to see how to apply them. > > DaveA > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From steve at pearwood.info Wed May 18 13:13:17 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 18 May 2011 21:13:17 +1000 Subject: [Tutor] can I walk or glob a website? In-Reply-To: <504485.54591.qm@web110716.mail.gq1.yahoo.com> References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> Message-ID: <201105182113.17591.steve@pearwood.info> On Wed, 18 May 2011 07:06:07 pm Albert-Jan Roskam wrote: > Hello, > > How can I walk (as in os.walk) or glob a website? If you're on Linux, use wget or curl. If you're on Mac, you can probably install them using MacPorts. If you're on Windows, you have my sympathies. *wink* > I want to download > all the pdfs from a website (using urllib.urlretrieve), This first part is essentially duplicating wget or curl. The basic algorithm is: - download a web page - analyze that page for links (such but possibly also others) - decide whether you should follow each link and download that page - repeat until there's nothing left to download, the website blocks your IP address, or you've got everything you want except wget and curl already do 90% of the work. If the webpage requires Javascript to make things work, wget or curl can't help. I believe there is a Python library called Mechanize to help with that. For dealing with real-world HTML (also known as "broken" or "completely f***ed" HTML, please excuse the self-censorship), the library BeautifulSoup may be useful. Before doing any mass downloading, please read this: http://lethain.com/an-introduction-to-compassionate-screenscraping/ > extract > certain figures (using pypdf- is this flexible enough?) and make some > statistics/graphs from those figures (using rpy and R). I forgot what > the process of 'automatically downloading' is called again, something > that sounds like 'whacking' (??) Sometimes called screen or web scraping, recursive downloading, or copyright-infringement *wink* http://en.wikipedia.org/wiki/Web_scraping -- Steven D'Aprano From fomcl at yahoo.com Wed May 18 13:23:02 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 18 May 2011 04:23:02 -0700 (PDT) Subject: [Tutor] can I walk or glob a website? In-Reply-To: <4DD396A7.9000201@ieee.org> References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <4DD396A7.9000201@ieee.org> Message-ID: <632570.23346.qm@web110704.mail.gq1.yahoo.com> From: Dave Angel To: Alan Gauld Cc: tutor at python.org Sent: Wed, May 18, 2011 11:51:35 AM Subject: Re: [Tutor] can I walk or glob a website? On 01/-10/-28163 02:59 PM, Alan Gauld wrote: > > "Albert-Jan Roskam" wrote >> How can I walk (as in os.walk) or glob a website? > > I don't think there is a way to do that via the web. > Of course if you have access to the web servers filesystem you can use > os.walk to do it as for any other filesystem, but I don't think its > generally possible over http. (And indeed it shouldn''t be for very good > security reasons!) > > OTOH I've been wrong before! :-) > It has to be (more or less) possible. That's what google does for their search engine. Three broad issues. 1) Are you violating the terms of service of such a web site? Are you going to be doing this seldom enough that the bandwidth used won't be a DOS attack? Are there copyrights to the material you plan to download? Is the website protected by a login, by cookies, or a VPN? Does the website present a different view to different browsers, different OS's, or different target domains? ===> This crossed my mind too. The advantage of using Python is that it's fun and that it saves me from gettng a mouse arm. It is a Dutch government site with pdf quality control reports (from the municipal health service) of kindergartens. I thought it would be fun and useful to make graphic representations of (spider charts) of each kindergarten, so they can be easily compared. This is just a hobby project. It just bothers me that they're not very easy to compare. 2) Websites vary enormously in their adherence to standards. There are many such standards, and browsers tend to be very tolerant of bugs in the site which will be painful for you to accomodate. And some of the extensions/features are very hard to parse, such as flash. Others, such as javascript, can make it hard to do it statically. ===> I checked some of the deep links already. They are of the form [/\\\.a-z]+docid[0-9]+resultid[0-9]+ (roughly speaking), e.g. http://www.landelijkregisterkinderopvang.nl/pp/inzien/Oko/InspectieRapport.jsf?documentId=5547&selectedResultId=5548 I could use a brute force approach and try all the doc/result id combinations. But wouldn't that result in a high server load? If so, I could put the program to sleep for n seconds. 3) How important is it to do it reliably? Your code may work perfectly with a particular website, and next week they'll make a change which breaks your code entirely. Are you willing to rework the code each time that happens? ===> It should be reliable. Portability to other sites is, of course, cool, but not strictly necessary. Many sites have API's that you can use to access them. Sometimes this is a better answer. With all of that said, I'll point you to Beautiful Soup, as a library that'll parse a page of moderately correct html and give you the elements of it. If it's a static page, you can then walk the elements of the tree that Beautiful Soup gives you, and find all the content that interests you. You can also find all the web pages that the first one refers to, and recurse on that. Notice that you need to limit your scope, since many websites have direct and indirect links to most of the web. For example, you might only recurse into links that refer to the same domain. For many websites, that means you won't get it all. So you may want to supply a list of domains and/or subdomains that you're willing to recurse into. See http://pypi.python.org/pypi/BeautifulSoup/3.2.0 ===> Thanks, I'll check BS. DaveA Best wishes, Albert-Jan _______________________________________________ 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 aznjonn at me.com Wed May 18 14:26:58 2011 From: aznjonn at me.com (Johnson Tran) Date: Wed, 18 May 2011 05:26:58 -0700 Subject: [Tutor] Program Message-ID: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> Hi Again All, I had a couple questions about my program: def CollectNames(): answer_set=set([]) sorted_list = sorted(answer_set) word=raw_input("Name #1: ") word=raw_input("Name #2: ") word=raw_input("Name #3: ") word=raw_input("Name #4: ") word=raw_input("Name #5: ") print "Your answer's sorted: ", ','.join(sorted_list) CollectNames() 1.) how do i add each answer given to the list so it is printed at the end? 2.) also im trying to modify the program so if the user puts in the same name, it will give an make them try again until they have 5 completely different names. Thanks, JT From __peter__ at web.de Wed May 18 14:40:25 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 May 2011 14:40:25 +0200 Subject: [Tutor] can I walk or glob a website? References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > How can I walk (as in os.walk) or glob a website? I want to download all > the pdfs from a website (using urllib.urlretrieve), extract certain > figures (using pypdf- is this flexible enough?) and make some > statistics/graphs from those figures (using rpy and R). I forgot what the > process of 'automatically downloading' is called again, something that > sounds like 'whacking' (??) If you've downloaded a source distribution of python you should have this little sucker on your harddisk: http://hg.python.org/cpython/file/31cd146d725c/Tools/webchecker/websucker.py From kb1pkl at aim.com Wed May 18 14:39:47 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 18 May 2011 08:39:47 -0400 Subject: [Tutor] Program In-Reply-To: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> References: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> Message-ID: <4DD3BE13.4000309@aim.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/18/2011 08:26 AM, Johnson Tran wrote: > Hi Again All, > > I had a couple questions about my program: > > def CollectNames(): > > answer_set=set([]) > sorted_list = sorted(answer_set) > word=raw_input("Name #1: ") > > word=raw_input("Name #2: ") > > word=raw_input("Name #3: ") > > word=raw_input("Name #4: ") > > word=raw_input("Name #5: ") > > print "Your answer's sorted: ", ','.join(sorted_list) > > CollectNames() > > > 1.) how do i add each answer given to the list so it is printed at the end? Well, you can't have ALL the answers printed at the end, but one way is to use a list and .append(word) each time. > 2.) also im trying to modify the program so if the user puts in the same name, it will give an make them try again until they have 5 completely different names. Now, you might see a pattern in your prompt. Each time you ask for input, you increment the name number. Perhaps this is the prime place for a loop? If you add in a loop, it will also be fairly easy to add in another loop to make sure they enter a name not in the list. So, your pseudo-code might look something like this: for i in range(6): make prompt string; get name; while name in names_gotten: get name; add name to names_gotten; print names_gotten; (P.S., PEP 8 says functions should be lowercase_with_underscore, not CamelCase) - -- Corey Richardson -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAgAGBQJN074TAAoJEAFAbo/KNFvpdHwIAK1Ji+4Z3Fac0wtH2EgBDwp2 K8t10KpbtRYfWOCjiYfBAzZFWLrQ9I+lrmdth7Asf0ANg72U4gPHkp82ZbO8mhyz 02eDBPXboAmLcntxsxcmMkNlG1xPVeXjcriGwX/VcN2AguGKvrKkKbkkT+Ar+bWZ ZpjH0ycNsAUTNeQLQEHJQJtPMktJ13XvlrjHN0YVoLpk812rAn+nuTZq+p0J5fzc hCgyxUiRcHYllXZv/1AegOWbfon3BMur9fpV2UMo8JcsRTHto3Lb5c3jHqApNjfc M48rpigGXjOzowj0WbsMmSHrskBglcSAy+xo/Ti0vnBXDMU3secWFWkaxDtdidk= =oCrn -----END PGP SIGNATURE----- From aznjonn at me.com Wed May 18 15:05:08 2011 From: aznjonn at me.com (Johnson Tran) Date: Wed, 18 May 2011 06:05:08 -0700 Subject: [Tutor] Program In-Reply-To: <4DD3BE13.4000309@aim.com> References: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> <4DD3BE13.4000309@aim.com> Message-ID: Thanks for the reply. So to append a word is it suppose to look kind of like: word=raw_input("Name #1: ") word.append(words) I keep getting error message: Traceback (most recent call last): File "/Users/JT/Desktop/pythonfinal", line 23, in CollectNames() File "/Users/JT/Desktop/pythonfinal", line 7, in CollectNames word.append(words) AttributeError: 'str' object has no attribute 'append' On May 18, 2011, at 5:39 AM, Corey Richardson wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On 05/18/2011 08:26 AM, Johnson Tran wrote: >> Hi Again All, >> >> I had a couple questions about my program: >> >> def CollectNames(): >> >> answer_set=set([]) >> sorted_list = sorted(answer_set) >> word=raw_input("Name #1: ") >> >> word=raw_input("Name #2: ") >> >> word=raw_input("Name #3: ") >> >> word=raw_input("Name #4: ") >> >> word=raw_input("Name #5: ") >> >> print "Your answer's sorted: ", ','.join(sorted_list) >> >> CollectNames() >> >> >> 1.) how do i add each answer given to the list so it is printed at the end? > > Well, you can't have ALL the answers printed at the end, but one way is > to use a list and .append(word) each time. > >> 2.) also im trying to modify the program so if the user puts in the same name, it will give an make them try again until they have 5 completely different names. > > Now, you might see a pattern in your prompt. Each time you ask for > input, you increment the name number. Perhaps this is the prime place > for a loop? If you add in a loop, it will also be fairly easy to add in > another loop to make sure they enter a name not in the list. So, your > pseudo-code might look something like this: > > for i in range(6): > make prompt string; > get name; > while name in names_gotten: > get name; > add name to names_gotten; > print names_gotten; > > (P.S., PEP 8 says functions should be lowercase_with_underscore, > not CamelCase) > - -- > Corey Richardson > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v2.0.17 (GNU/Linux) > Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ > > iQEcBAEBAgAGBQJN074TAAoJEAFAbo/KNFvpdHwIAK1Ji+4Z3Fac0wtH2EgBDwp2 > K8t10KpbtRYfWOCjiYfBAzZFWLrQ9I+lrmdth7Asf0ANg72U4gPHkp82ZbO8mhyz > 02eDBPXboAmLcntxsxcmMkNlG1xPVeXjcriGwX/VcN2AguGKvrKkKbkkT+Ar+bWZ > ZpjH0ycNsAUTNeQLQEHJQJtPMktJ13XvlrjHN0YVoLpk812rAn+nuTZq+p0J5fzc > hCgyxUiRcHYllXZv/1AegOWbfon3BMur9fpV2UMo8JcsRTHto3Lb5c3jHqApNjfc > M48rpigGXjOzowj0WbsMmSHrskBglcSAy+xo/Ti0vnBXDMU3secWFWkaxDtdidk= > =oCrn > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kb1pkl at aim.com Wed May 18 15:13:37 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 18 May 2011 09:13:37 -0400 Subject: [Tutor] Program In-Reply-To: References: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> <4DD3BE13.4000309@aim.com> Message-ID: <4DD3C601.7080007@aim.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/18/2011 09:05 AM, Johnson Tran wrote: > Thanks for the reply. > > So to append a word is it suppose to look kind of like: > > word=raw_input("Name #1: ") > word.append(words) > > I keep getting error message: > > Traceback (most recent call last): > File "/Users/JT/Desktop/pythonfinal", line 23, in > CollectNames() > File "/Users/JT/Desktop/pythonfinal", line 7, in CollectNames > word.append(words) > AttributeError: 'str' object has no attribute 'append' Yes, because append belongs to list, and not str! http://docs.python.org/tutorial/datastructures.html#more-on-lists words = [ word = raw_input("Name #1: ") words.append(word) Keep in mind the rest of the email I sent, that part was one of the least important (albeit fundamental). - -- Corey Richardson -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (GNU/Linux) iQEcBAEBAgAGBQJN08YBAAoJEAFAbo/KNFvpuSwH/jTqUncnANaRmlkJ3Mgd9C6k QeGEduLfnxT5d0m6DIil7k9q8UKBgrrOE8MKbfanp0f/QIWFn7g4M8WAoNASUF26 Bb0sHuzCjAoEL3Gbf2nOejhBlAPCos4ReveDAysiSwJ4pe8hOQOzxQ73apNq8v1W U8x0/X0JL5J6Cw/g4mEWd/Be2rYiQdL0xchpRB+9m6ATCTfo99g5VDR4kuB8T0Mi wbfq/jEQZbKCWInwCHuD7n7438zUJad4MvNPPlBnrQDb76MzN4sU4ZXnKjRvYdsN Z/fJKy40MWUtD/6Lw8fHhIVdtWFo0k6xM3bUjcPIYfRdHXHvX8NwEwyw3704YAY= =SYly -----END PGP SIGNATURE----- From waynejwerner at gmail.com Wed May 18 15:19:13 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 18 May 2011 08:19:13 -0500 Subject: [Tutor] Program In-Reply-To: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> References: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> Message-ID: On Wed, May 18, 2011 at 7:26 AM, Johnson Tran wrote: > Hi Again All, > > I had a couple questions about my program: > Corey gave you some good pointers already, but let me add a few... > > def CollectNames(): > > answer_set=set([]) > sorted_list = sorted(answer_set) > This won't do what you think it does (I use IPython so my prompt looks different than the >>> you should be used to): In [5]: answer_set = set([]) In [6]: sorted_list = sorted(answer_set) In [7]: sorted_list.append(3) In [8]: sorted_list.append(1) In [9]: sorted_list Out[9]: [3, 1] You can find out why this happens by checking the documentation: In [10]: help(sorted) Help on built-in function sorted in module __builtin__: sorted(...) sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list so sorted returns a list - and if you aren't familiar with lists yet, they are simple collections - un-sorted until you sort them. Instead what you might want to do is add your items to the list (or the set) and then once you have all your items, /then/ return the sorted list (Although, there is another solution to your problem using a set and the size of it... I'll leave that exercise to you) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 18 16:40:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 May 2011 15:40:19 +0100 Subject: [Tutor] can I walk or glob a website? References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <4DD396A7.9000201@ieee.org> Message-ID: "Dave Angel" wrote >> "Albert-Jan Roskam" wrote >>> How can I walk (as in os.walk) or glob a website? >> >> I don't think there is a way to do that via the web. > It has to be (more or less) possible. That's what google does for > their search engine. Google trawls the site following links. If thats all he wants then its fairly easy. I took it he wanted to actually trawl the server getting *all* the pdf files not just the published pdfs... Depends what the real requirement is. Alan G. From susana.delgado_s at utzmg.edu.mx Wed May 18 16:45:26 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Wed, 18 May 2011 09:45:26 -0500 Subject: [Tutor] RuntimeError: file does not exist In-Reply-To: References: Message-ID: Hello Alan!! Can you please tell me, how to rebuild my path? I've tried it, but I didn't succed =( 2011/5/17 Alan Gauld > > "Susana Iraiis Delgado Rodriguez" wrote > > > message which tells me the file I want to work with >> doesn't exist, but it does. >> > > I don't believe you! :-) > > Traceback (most recent call last):... >> >> lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) >> return CreateDatasource(keywords) >> RuntimeError: C:\?ndice.shp/C:\?ndice does not exist >> > > That "file name" has two C: in it which I am pretty sure is > an illegal path in Windows. Therfore the file cannot exist. > > You just need to build your path correctly I suspect. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 18 16:57:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 May 2011 15:57:08 +0100 Subject: [Tutor] Program References: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> Message-ID: "Johnson Tran" wrote > I had a couple questions about my program: > > def CollectNames(): > answer_set=set([]) > sorted_list = sorted(answer_set) This creates an empty set then sorts it and stores the result as an empty list. I'm not sure what you think it does but I'm guessing that's not it... > word=raw_input("Name #1: ") > word=raw_input("Name #2: ") > word=raw_input("Name #3: ") > word=raw_input("Name #4: ") > word=raw_input("Name #5: ") Do you know about loops yet? Any time you find yourself repeating code like this think about a loop. A for loop could be used here: for attempt in range(1,6): word = raw_input("Name #%d" % attempt) Although storing all the names in the same variable is also probably not what you want. You need to add word to your list using the list append() method. > print "Your answers sorted: ", ','.join(sorted_list) And this is where you probably want to call sorted()... > 1.) how do i add each answer given to the list so it is printed at > the end? Use the append method of the list > 2.) also im trying to modify the program so if the > user puts in the same name, it will give an make > them try again until they have 5 completely different > names. A combination of a while loop and a set and the len() function might work here. Keep adding to the set while the length of the set is <5. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmchase.com Wed May 18 16:58:42 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 18 May 2011 10:58:42 -0400 Subject: [Tutor] can I walk or glob a website? In-Reply-To: <4DD396A7.9000201@ieee.org> References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <4DD396A7.9000201@ieee.org> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3F19B50@EMARC112VS01.exchad.jpmchase.net> >>Are you going to be doing this seldom enough that the bandwidth used won't be a >>DOS attack? It will not solve the problem completely, but I know that wget (and probably curl) have speed limiters you can set to help reduce the chances of DOS. If you are using urllib you could look at: http://mail.python.org/pipermail/python-list/2008-January/524004.html or http://stackoverflow.com/questions/456649/throttling-with-urllib2 I would probably suggest using PyCurl (no experience with it) as it will probably be Pythonic and seems to have a way to rate limit already built in: http://stackoverflow.com/questions/4533304/python-urlretrieve-limit-rate-and-resume-partial-download (See the answer) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From wprins at gmail.com Wed May 18 16:59:58 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 18 May 2011 15:59:58 +0100 Subject: [Tutor] RuntimeError: file does not exist In-Reply-To: References: Message-ID: On 18 May 2011 15:45, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > Hello Alan!! > Can you please tell me, how to rebuild my path? I've tried it, but I didn't > succed =( > > Always post the code you tried, and the full error message you received, otherwise you make it unneccesarily hard for us to try and help you (in which case many people might not bother to try.) Thanks, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Wed May 18 17:00:57 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 18 May 2011 11:00:57 -0400 Subject: [Tutor] RuntimeError: file does not exist In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3F19B61@EMARC112VS01.exchad.jpmchase.net> Try hard coding it to test, but it probably wants base as the directory and file as the filename: mapnik.Shapefile(base="C:\\", file=' ?ndice.shp') Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Susana Iraiis Delgado Rodriguez Sent: Wednesday, May 18, 2011 9:45 AM To: Alan Gauld Cc: tutor at python.org Subject: Re: [Tutor] RuntimeError: file does not exist Hello Alan!! Can you please tell me, how to rebuild my path? I've tried it, but I didn't succed =( 2011/5/17 Alan Gauld > "Susana Iraiis Delgado Rodriguez" > wrote message which tells me the file I want to work with doesn't exist, but it does. I don't believe you! :-) Traceback (most recent call last):... lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) return CreateDatasource(keywords) RuntimeError: C:\?ndice.shp/C:\?ndice does not exist That "file name" has two C: in it which I am pretty sure is an illegal path in Windows. Therfore the file cannot exist. You just need to build your path correctly I suspect. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 18 17:07:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 May 2011 16:07:24 +0100 Subject: [Tutor] Sequencing References: <947967.89500.qm@web132207.mail.ird.yahoo.com> Message-ID: "Cindy Lee" wrote > ...asked to make a function that receives text as an argument > and returns the same text, but with 1 added to each number. > So far I have: > def ReceiveAndReturn(): > sentence=raw_input("Give me a sentence with variables in it: > ") The assignment says it should receive the text *as an argument* That means you don't read it using raw_input. Its not clear what the adding one to each number bit means. If we make some assumptions: "2 cats sat on a mat" -> "3 cats sat on a mat" but not "Two cats sat on a mat" -> "Three cats sat on a mat" In other words we are only detecting strings of decimal digits not numeric words. Then we can search the string(a sequence) for consecutive numbers. Convert them from strings to numbers and add one Then insert into the output string. Thats the tricky bit! :-) Have a go, post your code and we will try to help when you get stuck. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmchase.com Wed May 18 17:16:12 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 18 May 2011 11:16:12 -0400 Subject: [Tutor] Looking for feedback on improving my code. In-Reply-To: <327657318-1305671616-cardhu_decombobulator_blackberry.rim.net-1466876317-@b3.c28.bise6.blackberry> References: <327657318-1305671616-cardhu_decombobulator_blackberry.rim.net-1466876317-@b3.c28.bise6.blackberry> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3F19BCC@EMARC112VS01.exchad.jpmchase.net> >The big thing I've noticed is, and I'm a total newbie btw, mind cap conventions. Reading and implementing PEP 8 (http://python.org/dev/peps/pep-0008/) will help make your code more readable and quickly understandable to other Python developers. I highly encourage it. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From fomcl at yahoo.com Wed May 18 19:32:36 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 18 May 2011 10:32:36 -0700 (PDT) Subject: [Tutor] can I walk or glob a website? In-Reply-To: <201105182113.17591.steve@pearwood.info> References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <201105182113.17591.steve@pearwood.info> Message-ID: <290947.59207.qm@web110706.mail.gq1.yahoo.com> Hi Steven, From: Steven D'Aprano To: tutor at python.org Sent: Wed, May 18, 2011 1:13:17 PM Subject: Re: [Tutor] can I walk or glob a website? On Wed, 18 May 2011 07:06:07 pm Albert-Jan Roskam wrote: > Hello, > > How can I walk (as in os.walk) or glob a website? If you're on Linux, use wget or curl. ===> Thanks for your reply. I tried wget, which seems to be a very handy tool. However, it doesn't work on this particular site. I tried wget -e robots=off -r -nc --no-parent -l6 -A.pdf 'http://www.landelijkregisterkinderopvang.nl/' (the quotes are there because I originally used a deeper link that contains ampersands). I also tested it on python.org, where it does work. Adding -e robots=off didn't work either. Do you think this could be a protection from the administrator? If you're on Mac, you can probably install them using MacPorts. If you're on Windows, you have my sympathies. *wink* > I want to download > all the pdfs from a website (using urllib.urlretrieve), This first part is essentially duplicating wget or curl. The basic algorithm is: - download a web page - analyze that page for links (such but possibly also others) - decide whether you should follow each link and download that page - repeat until there's nothing left to download, the website blocks your IP address, or you've got everything you want except wget and curl already do 90% of the work. If the webpage requires Javascript to make things work, wget or curl can't help. I believe there is a Python library called Mechanize to help with that. For dealing with real-world HTML (also known as "broken" or "completely f***ed" HTML, please excuse the self-censorship), the library BeautifulSoup may be useful. Before doing any mass downloading, please read this: http://lethain.com/an-introduction-to-compassionate-screenscraping/ > extract > certain figures (using pypdf- is this flexible enough?) and make some > statistics/graphs from those figures (using rpy and R). I forgot what > the process of 'automatically downloading' is called again, something > that sounds like 'whacking' (??) Sometimes called screen or web scraping, recursive downloading, or copyright-infringement *wink* http://en.wikipedia.org/wiki/Web_scraping -- Steven D'Aprano _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Wed May 18 19:39:51 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 18 May 2011 10:39:51 -0700 (PDT) Subject: [Tutor] can I walk or glob a website? In-Reply-To: References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <4DD396A7.9000201@ieee.org> Message-ID: <6185.15401.qm@web110703.mail.gq1.yahoo.com> ________________________________ From: Alan Gauld To: tutor at python.org Sent: Wed, May 18, 2011 4:40:19 PM Subject: Re: [Tutor] can I walk or glob a website? "Dave Angel" wrote >> "Albert-Jan Roskam" wrote >>> How can I walk (as in os.walk) or glob a website? >> >> I don't think there is a way to do that via the web. > It has to be (more or less) possible. That's what google does for their search >engine. Google trawls the site following links. If thats all he wants then its fairly easy. I took it he wanted to actually trawl the server getting *all* the pdf files not just the published pdfs... Depends what the real requirement is. ===> No, I meant only the published ones. I would consider it somewhat dodgy/unethical/whatever-you-wanna-call-it to download unpublished stuff. Indeed I only need published data. Alan G. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed May 18 19:48:32 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 18 May 2011 10:48:32 -0700 Subject: [Tutor] can I walk or glob a website? In-Reply-To: <504485.54591.qm@web110716.mail.gq1.yahoo.com> References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> Message-ID: On Wed, May 18, 2011 at 2:06 AM, Albert-Jan Roskam wrote: > Hello, > > How can I walk (as in os.walk) or glob a website? I want to download all > the pdfs from a website (using urllib.urlretrieve), extract certain figures > (using pypdf- is this flexible enough?) and make some statistics/graphs from > those figures (using rpy and R). I forgot what the process of 'automatically > downloading' is called again, something that sounds like 'whacking' (??) > > I think the word you're looking for is "scraping". I actually did something (roughly) similar a few years ago, to download a collection of free Russian audiobooks for my father-in-law (an avid reader who was quickly going blind.) I crawled the site looking for .mp3 files, then returned a tree from which I could select files to be downloaded. It's horribly crude, in retrospect, and I'm embarrassed re-reading my code - but if you're interested I can forward it (if only as an example of what _not_to do.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Wed May 18 19:56:06 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 18 May 2011 19:56:06 +0200 Subject: [Tutor] can I walk or glob a website? In-Reply-To: <290947.59207.qm@web110706.mail.gq1.yahoo.com> References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <201105182113.17591.steve@pearwood.info> <290947.59207.qm@web110706.mail.gq1.yahoo.com> Message-ID: On Wed, May 18, 2011 at 7:32 PM, Albert-Jan Roskam wrote: > > ===> Thanks for your reply. I tried wget, which seems to be a very handy > tool. However, it doesn't work on this particular site. I tried wget -e > robots=off -r -nc --no-parent -l6 -A.pdf > 'http://www.landelijkregisterkinderopvang.nl/' (the quotes are there because > I originally used a deeper link that contains ampersands). I also tested it > on python.org, where it does work. Adding -e robots=off didn't work either. > Do you think this could be a protection from the administrator? > wget works by recursively following hyperlinks from the page you supply. The page you entered leads to a search form (which wget wouldn't know how to fill out) but nothing else, so wget cannot retrieve any of the pdf documents. I think your best approach is the brute-force id generation you mentioned earlier. be polite about this: wait a few seconds after four consecutive failed attempts, download only one pdf at a time, wait a second or two after each download, that kind of thing. Just don't flood the server. From ramit.prasad at jpmchase.com Wed May 18 20:04:58 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 18 May 2011 14:04:58 -0400 Subject: [Tutor] can I walk or glob a website? In-Reply-To: References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3FFE2EF@EMARC112VS01.exchad.jpmchase.net> > It's horribly crude, in retrospect, and I'm embarrassed re-reading my code - but if you're interested I can forward it (if only as an example of what _not_to do.) I would be interested even if the OP is not ;) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed May 18 20:21:52 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 18 May 2011 11:21:52 -0700 Subject: [Tutor] can I walk or glob a website? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3FFE2EF@EMARC112VS01.exchad.jpmchase.net> References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3FFE2EF@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Wed, May 18, 2011 at 11:04 AM, Prasad, Ramit wrote: > > It's horribly crude, in retrospect, and I'm embarrassed re-reading my > code - but if you're interested I can forward it (if only as an example of > what _not_to do.) > > I would be interested even if the OP is not ;) > > OK then, but bear in mind that I was young and foolish then. Of course, I'm old and foolish now... -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: knigi.pyw Type: application/octet-stream Size: 9996 bytes Desc: not available URL: From marc.tompkins at gmail.com Wed May 18 21:10:06 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 18 May 2011 12:10:06 -0700 Subject: [Tutor] can I walk or glob a website? In-Reply-To: References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3FFE2EF@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Wed, May 18, 2011 at 11:21 AM, Marc Tompkins wrote: > On Wed, May 18, 2011 at 11:04 AM, Prasad, Ramit > wrote: > >> > It's horribly crude, in retrospect, and I'm embarrassed re-reading my >> code - but if you're interested I can forward it (if only as an example of >> what _not_to do.) >> >> I would be interested even if the OP is not ;) >> >> > OK then, but bear in mind that I was young and foolish then. Of course, > I'm old and foolish now... > I just DID re-read it, and I'd just like to point out: - I wrote my script to work with the structure of one particular website, " audiobooks.ulitka.com". As written, it probably wouldn't work with a generic site. - "audiobooks.ulitka.com" no longer exists, so even if you installed all the dependencies and got my code working, it wouldn't work. The " ulitka.com" domain appears to have been sold to a completely different business/organization... -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Thu May 19 03:17:44 2011 From: carroll at tjc.com (Terry Carroll) Date: Wed, 18 May 2011 18:17:44 -0700 (PDT) Subject: [Tutor] xrange() with start or stop > sys.maxint? Message-ID: Is there any way to use xrange with a start or stop value that exceeds sys.maxint? >>> import sys >>> print sys.maxint 2147483647 >>> start = sys.maxint-1 >>> for i in xrange(start, start+1): ... pass ... >>> start = sys.maxint >>> for i in xrange(start, start+1): ... pass ... Traceback (most recent call last): File "", line 1, in OverflowError: Python int too large to convert to C long >>> Works okay with range, though: >>> start = sys.maxint >>> for i in range(start, start+1): ... pass ... >>> From markc at flexsystems.net Thu May 19 04:41:38 2011 From: markc at flexsystems.net (Mark Cowley - FlexSystems) Date: Wed, 18 May 2011 20:41:38 -0600 Subject: [Tutor] Crystal reports in Python Message-ID: <0ABF5154F1854D199D197F706C60F478@flexmwcdell> Hi Can anybody help me with some info on how to display Crystal reports in Python or suggest any good alternatives. Thanks Mark flex FlexSystems LLC 425 South Bowen Street, Suite 2 Longmont, CO 80501 Office: 303.684.8303 x6102 Cell: 720.938.5842 Fax: 303.926.4494 Email: markc at flexsystems.net Web: www.flexsystems.net This electronic message transmission (including any attachments) may contain confidential or privileged information and is intended solely for the recipient. Its unauthorized review, use, interception or distribution by or to others is prohibited and may be unlawful. Please advise the sender immediately by return e-mail and delete this message and any attachments, without copying or disclosing them, if this message has been received in error. Thank You. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 3191 bytes Desc: not available URL: From joe at chem.com.au Thu May 19 06:36:11 2011 From: joe at chem.com.au (Joe Aquilina) Date: Thu, 19 May 2011 12:36:11 +0800 Subject: [Tutor] Data conversion Message-ID: <4DD49E3B.4070307@chem.com.au> Hello. I am new to this list and very much a beginner to Python. Please excuse me if this is a silly question, but in all my searches this morning I have not been able to find an answer. I have a (single table) database file (SQLite3). It has one table, call it literature, with an integer, autoincrement primary key field. I have created a data entry form in Python that I want to use to enter new rows into this database file. On the data entry form I will enter the values for a new table row - all except the primary key field. What I want to be able to do is to have my data entry form autoincrement this primary key field for me, with no ability to change the contents on the data entry form, and save this incremented value as the value of the num field when I save the new row. So for example, if the last row in the table has a value of 256 in the num field, I want the value of 257 to be saved as the value of the num field into the new row I am adding, without having to see or or enter this new value (or indeed the previous value) on the data entry screen. I hope this makes sense. But how do I do this? I thought about doing a SELECT num FROM literature; from the table, then getting the contents of the num field of the last row in the data that a fetchall() retrieves and incrementing it to save with the new row. However, the fetchall() returns the data as tuples, not integers and I don't know how to convert from a tuple data type to an integer to make this work. Is this possible? Or can I achieve my objective in some other way? Any advice/assistance would be appreciated. Thanks in advance. Joe Aquilina From andreengels at gmail.com Thu May 19 07:53:17 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 19 May 2011 07:53:17 +0200 Subject: [Tutor] Data conversion In-Reply-To: <4DD49E3B.4070307@chem.com.au> References: <4DD49E3B.4070307@chem.com.au> Message-ID: On Thu, May 19, 2011 at 6:36 AM, Joe Aquilina wrote: > I am new to this list and very much a beginner to Python. Please excuse me > if this is a silly question, but in all my searches this morning I have not > been able to find an answer. > > I have a (single table) database file (SQLite3). It has one table, call it > literature, with an integer, autoincrement primary key field. I have created > a data entry form in Python that I want to use to enter new rows into this > database file. On the data entry form I will enter the values for a new > table row - all except the primary key field. > > What I want to be able to do is to have my data entry form autoincrement > this primary key field for me, with no ability to change the contents on the > data entry form, and save this incremented value as the value of the num > field when I save the new row. > > So for example, if the last row in the table has a value of 256 in the num > field, I want the value of 257 to be saved as the value of the num field > into the new row I am adding, without having to see or or enter this new > value (or indeed the previous value) on the data entry screen. > > I hope this makes sense. But how do I do this? > > I thought about doing a > > SELECT num FROM literature; > > from the table, then getting the contents of the num field of the last row > in the data that a fetchall() retrieves and incrementing it to save with the > new row. > > However, the fetchall() returns the data as tuples, not integers and I don't > know how to convert from a tuple data type to an integer to make this work. > > Is this possible? Or can I achieve my objective in some other way? > > Any advice/assistance would be appreciated. Thanks in advance. l assume the tuple is a 1-tuple? Anyway, let fetch be the name of your tuple, then fetch[0] will be the first element of the tuple, fetch[1] the second element, and so on. -- Andr? Engels, andreengels at gmail.com From joe at chem.com.au Thu May 19 08:15:51 2011 From: joe at chem.com.au (Joe Aquilina) Date: Thu, 19 May 2011 14:15:51 +0800 Subject: [Tutor] Data conversion In-Reply-To: References: <4DD49E3B.4070307@chem.com.au> Message-ID: <4DD4B597.8010903@chem.com.au> On 19/05/11 13:53, Andre Engels wrote: > On Thu, May 19, 2011 at 6:36 AM, Joe Aquilina wrote: > >> I am new to this list and very much a beginner to Python. Please excuse me >> if this is a silly question, but in all my searches this morning I have not >> been able to find an answer. >> >> I have a (single table) database file (SQLite3). It has one table, call it >> literature, with an integer, autoincrement primary key field. I have created >> a data entry form in Python that I want to use to enter new rows into this >> database file. On the data entry form I will enter the values for a new >> table row - all except the primary key field. >> >> What I want to be able to do is to have my data entry form autoincrement >> this primary key field for me, with no ability to change the contents on the >> data entry form, and save this incremented value as the value of the num >> field when I save the new row. >> >> So for example, if the last row in the table has a value of 256 in the num >> field, I want the value of 257 to be saved as the value of the num field >> into the new row I am adding, without having to see or or enter this new >> value (or indeed the previous value) on the data entry screen. >> >> I hope this makes sense. But how do I do this? >> >> I thought about doing a >> >> SELECT num FROM literature; >> >> from the table, then getting the contents of the num field of the last row >> in the data that a fetchall() retrieves and incrementing it to save with the >> new row. >> >> However, the fetchall() returns the data as tuples, not integers and I don't >> know how to convert from a tuple data type to an integer to make this work. >> >> Is this possible? Or can I achieve my objective in some other way? >> >> Any advice/assistance would be appreciated. Thanks in advance. > l assume the tuple is a 1-tuple? > > Anyway, let fetch be the name of your tuple, then > > fetch[0] > > will be the first element of the tuple, > > fetch[1] > > the second element, and so on. > > Hello Andre. I realised after I read your response that I probably hadn't included enough information, partly due to my inexperience in Python and partly due to haste on my part. AFter my original post, I had a little play in Python and was able to create this tuple: [1, 2, 3, 4, 5] from which I was able to extract any item I wanted as an integer and work with as I wanted. I am guessing that this is a 1-tuple. It is when I do the fetchall() from the table, that I get the following: [(1,), (2,), (3,)] I don't know enough to know whether this is a 1-tuple or not. It is from this tuple that I want to extract the 3 as an integer so that I can increment it and save as an integer into the next row in the table. Hope that is a little clearer. Cheers. Joe Aquilina From __peter__ at web.de Thu May 19 08:24:18 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 May 2011 08:24:18 +0200 Subject: [Tutor] Data conversion References: <4DD49E3B.4070307@chem.com.au> Message-ID: Joe Aquilina wrote: > I am new to this list and very much a beginner to Python. Please excuse > me if this is a silly question, but in all my searches this morning I > have not been able to find an answer. > > I have a (single table) database file (SQLite3). It has one table, call > it literature, with an integer, autoincrement primary key field. I have > created a data entry form in Python that I want to use to enter new rows > into this database file. On the data entry form I will enter the values > for a new table row - all except the primary key field. > > What I want to be able to do is to have my data entry form autoincrement > this primary key field for me, with no ability to change the contents on > the data entry form, and save this incremented value as the value of the > num field when I save the new row. > > So for example, if the last row in the table has a value of 256 in the > num field, I want the value of 257 to be saved as the value of the num > field into the new row I am adding, without having to see or or enter > this new value (or indeed the previous value) on the data entry screen. > > I hope this makes sense. But how do I do this? > > I thought about doing a > > SELECT num FROM literature; > > from the table, then getting the contents of the num field of the last > row in the data that a fetchall() retrieves and incrementing it to save > with the new row. > > However, the fetchall() returns the data as tuples, not integers and I > don't know how to convert from a tuple data type to an integer to make > this work. > > Is this possible? Or can I achieve my objective in some other way? I may be misunderstanding you, but the point of an autoincrement field is that you don't have to set its value, the database will do it automatically for you. A minimal example: $cat autoinc.py import sqlite3 db = sqlite3.connect("tmp.db") cs = db.cursor() cs.execute("""create table if not exists items (item_id integer primary key autoincrement, name)""") while True: name = raw_input("Enter name ") if not name: break cs.execute("""insert into items (name) values (?)""", (name,)) db.commit() for row in cs.execute("select * from items"): print row$ python autoinc.py Enter name alpha Enter name beta Enter name gamma Enter name (1, u'alpha') (2, u'beta') (3, u'gamma') $python autoinc.py Enter name delta Enter name epsilon Enter name (1, u'alpha') (2, u'beta') (3, u'gamma') (4, u'delta') (5, u'epsilon')$ Even though item_id doesn't appear in the insert statement you get the desired consecutive values... From spawgi at gmail.com Thu May 19 08:35:09 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Thu, 19 May 2011 12:05:09 +0530 Subject: [Tutor] xrange() with start or stop > sys.maxint? In-Reply-To: References: Message-ID: What is the version of python you are using? >From the documentation of python 2.71. http://docs.python.org/library/functions.html#xrange CPython implementation detail: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (?short? Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using the itertools module: islice(count(start, step), (stop-start+step-1)//step). Hope this helps. Thanks and Regards, Sumod On Thu, May 19, 2011 at 6:47 AM, Terry Carroll wrote: > Is there any way to use xrange with a start or stop value that exceeds > sys.maxint? > > import sys >>>> print sys.maxint >>>> >>> 2147483647 > >> start = sys.maxint-1 >>>> for i in xrange(start, start+1): >>>> >>> ... pass > ... > >> start = sys.maxint >>>> for i in xrange(start, start+1): >>>> >>> ... pass > ... > Traceback (most recent call last): > File "", line 1, in > OverflowError: Python int too large to convert to C long > >> >>>> > Works okay with range, though: > > start = sys.maxint >>>> for i in range(start, start+1): >>>> >>> ... pass > ... > >> >>>> _______________________________________________ > 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 fomcl at yahoo.com Thu May 19 09:25:46 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 19 May 2011 00:25:46 -0700 (PDT) Subject: [Tutor] can I walk or glob a website? In-Reply-To: References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3FFE2EF@EMARC112VS01.exchad.jpmchase.net> Message-ID: <627637.78807.qm@web110715.mail.gq1.yahoo.com> Thank you, always useful to study other?people's code. I wasn't planning to create a?Gui for my app. It struck me that the Gui class also contains all the methods that deal with the html parsing. But?maybe that's what your warnings were about. ;-) ?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: Marc Tompkins To: tutor at python.org Sent: Wed, May 18, 2011 9:10:06 PM Subject: Re: [Tutor] can I walk or glob a website? On Wed, May 18, 2011 at 11:21 AM, Marc Tompkins wrote: On Wed, May 18, 2011 at 11:04 AM, Prasad, Ramit wrote: > >> It's horribly crude, in retrospect, and I'm embarrassed re-reading my code - >>but if you're interested I can forward it (if only as an example of what _not_to >>do.) >>I would be interested even if the OP is not ;) >> >OK then, but bear in mind that I was young and foolish then.? Of course, I'm old >and foolish now... >I just DID re-read it, and I'd just like to point out: -? I wrote my script to work with the structure of one particular website, "audiobooks.ulitka.com".? As written, it probably wouldn't work with a generic site. -? "audiobooks.ulitka.com" no longer exists, so even if you installed all the dependencies and got my code working, it wouldn't work.?? The "ulitka.com" domain appears to have been sold to a completely different business/organization... -------------- next part -------------- An HTML attachment was scrubbed... URL: From joe at chem.com.au Thu May 19 10:07:27 2011 From: joe at chem.com.au (Joe Aquilina) Date: Thu, 19 May 2011 16:07:27 +0800 Subject: [Tutor] Data conversion - Problem solved In-Reply-To: <4DD4B597.8010903@chem.com.au> References: <4DD49E3B.4070307@chem.com.au> <4DD4B597.8010903@chem.com.au> Message-ID: <4DD4CFBF.5090807@chem.com.au> On 19/05/11 14:15, Joe Aquilina wrote: > On 19/05/11 13:53, Andre Engels wrote: >> On Thu, May 19, 2011 at 6:36 AM, Joe Aquilina wrote: >> >>> I am new to this list and very much a beginner to Python. Please >>> excuse me >>> if this is a silly question, but in all my searches this morning I >>> have not >>> been able to find an answer. >>> >>> I have a (single table) database file (SQLite3). It has one table, >>> call it >>> literature, with an integer, autoincrement primary key field. I have >>> created >>> a data entry form in Python that I want to use to enter new rows >>> into this >>> database file. On the data entry form I will enter the values for a new >>> table row - all except the primary key field. >>> >>> What I want to be able to do is to have my data entry form >>> autoincrement >>> this primary key field for me, with no ability to change the >>> contents on the >>> data entry form, and save this incremented value as the value of the >>> num >>> field when I save the new row. >>> >>> So for example, if the last row in the table has a value of 256 in >>> the num >>> field, I want the value of 257 to be saved as the value of the num >>> field >>> into the new row I am adding, without having to see or or enter this >>> new >>> value (or indeed the previous value) on the data entry screen. >>> >>> I hope this makes sense. But how do I do this? >>> >>> I thought about doing a >>> >>> SELECT num FROM literature; >>> >>> from the table, then getting the contents of the num field of the >>> last row >>> in the data that a fetchall() retrieves and incrementing it to save >>> with the >>> new row. >>> >>> However, the fetchall() returns the data as tuples, not integers and >>> I don't >>> know how to convert from a tuple data type to an integer to make >>> this work. >>> >>> Is this possible? Or can I achieve my objective in some other way? >>> >>> Any advice/assistance would be appreciated. Thanks in advance. >> l assume the tuple is a 1-tuple? >> >> Anyway, let fetch be the name of your tuple, then >> >> fetch[0] >> >> will be the first element of the tuple, >> >> fetch[1] >> >> the second element, and so on. >> >> > Hello Andre. > > I realised after I read your response that I probably hadn't included > enough information, partly due to my inexperience in Python and > partly due to haste on my part. > > AFter my original post, I had a little play in Python and was able to > create this tuple: > > [1, 2, 3, 4, 5] > > from which I was able to extract any item I wanted as an integer and > work with as I wanted. I am guessing that this is a 1-tuple. > > It is when I do the fetchall() from the table, that I get the following: > > [(1,), (2,), (3,)] > > I don't know enough to know whether this is a 1-tuple or not. It is > from this tuple that I want to extract the 3 as an integer so that I > can increment it and save as an integer into the next row in the table. > > Hope that is a little clearer. > > Cheers. > > Joe Aquilina Please ignore this thread. I have solved my problem. On further experimentation in Python, I found that if my SELECT statement included the whole row (or in fact at least two fields), the tuple returned was in a form that I could then extract the required value as an integer and then increment it as I wanted. I have now incorporated this result into my code and it works as required. Cheers. Joe Aquilina From eike.welk at gmx.net Thu May 19 11:00:17 2011 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 19 May 2011 11:00:17 +0200 Subject: [Tutor] how to read two files and substitute In-Reply-To: References: Message-ID: <201105191104.25768.eike.welk@gmx.net> Hello Lina! On Wednesday 18.05.2011 05:22:50 lina wrote: > May I ask another question: > > where I can get some advanced, terse and powerful python tutorials. > short but powerful and a bit hard to understand at first. The tutorial on Python's website is relatively terse, but it uses a simple language. It is great, if you already know a programming language. http://docs.python.org/tutorial/ For people who do numerical computations the book "Python Scripting for Computational Science" from Hans Petter Langtangen is a great introduction to Python. http://www.amazon.com/Python-Scripting-Computational-Science- Engineering/dp/3540739157/ The book from Langtangen also introduces the most important scientific libries, and shows how to solve common tasks. It is quite badly structured though. Eike. From marc.tompkins at gmail.com Thu May 19 11:24:12 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 19 May 2011 02:24:12 -0700 Subject: [Tutor] can I walk or glob a website? In-Reply-To: <627637.78807.qm@web110715.mail.gq1.yahoo.com> References: <504485.54591.qm@web110716.mail.gq1.yahoo.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA3FFE2EF@EMARC112VS01.exchad.jpmchase.net> <627637.78807.qm@web110715.mail.gq1.yahoo.com> Message-ID: On Thu, May 19, 2011 at 12:25 AM, Albert-Jan Roskam wrote: > Thank you, always useful to study other people's code. I wasn't planning to > create a Gui for my app. > It was necessary for the purpose - I didn't want all, or even most, of the mp3s on the site, but certainly enough of them that automation was required. > It struck me that the Gui class also contains all the methods that deal > with the html parsing. But maybe that's what your warnings were about. ;-) > If that was the worst thing you found, you just weren't looking hard enough ;-) Seriously though, I definitely would do it very differently if I did it again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu May 19 11:26:00 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 19 May 2011 11:26:00 +0200 Subject: [Tutor] Data conversion In-Reply-To: <4DD4B597.8010903@chem.com.au> References: <4DD49E3B.4070307@chem.com.au> <4DD4B597.8010903@chem.com.au> Message-ID: On Thu, May 19, 2011 at 8:15 AM, Joe Aquilina wrote: > I realised after I read your response that I probably hadn't included enough > information, partly due to my ?inexperience in Python and partly due to > haste on my part. > > AFter my original post, I had a little play in Python and was able to create > this tuple: > > [1, 2, 3, 4, 5] > > from which I was able to extract any item I wanted as an integer and work > with as I wanted. I am guessing that this is a 1-tuple. No, this is an array. However, an array and a tuple work similarly in many cases. A 1-tuple is a tuple with one element, so this is definitely not a 1-tuple. > It is when I do the fetchall() from the table, that I get the following: > > [(1,), (2,), (3,)] > > I don't know enough to know whether this is a 1-tuple or not. It is from > this tuple that I want to extract the 3 as an integer so that I can > increment it and save as an integer into the next row in the table. This again is an array, but this time the elements are tuples (indeed 1-tuples). To show you how to get the value 3 from this: >>> A = [(1,), (2,), (3,)] >>> A[2] (3,) >>> A[-1] (3,) >>> B = A[-1] >>> B (3,) >>> B[0] 3 >>> A[-1][0] 3 -- Andr? Engels, andreengels at gmail.com From cindylee2321 at yahoo.com Thu May 19 12:10:47 2011 From: cindylee2321 at yahoo.com (Cindy Lee) Date: Thu, 19 May 2011 11:10:47 +0100 (BST) Subject: [Tutor] Sequencing In-Reply-To: References: <947967.89500.qm@web132207.mail.ird.yahoo.com> Message-ID: <126284.15226.qm@web132204.mail.ird.yahoo.com> Sorry I am still lost. So I am suppose to use a string? Something like: (just not sure is the right string...) def ReceiveAndReturn(): ?? ?str="I have 5 Apples and 6 oranges"; ?? ?print "str._add1" ReceiveAndReturn() Want output to be: I have 6 Apples and 7 oranges ________________________________ From: Alan Gauld To: tutor at python.org Sent: Wednesday, 18 May 2011, 8:07 Subject: Re: [Tutor] Sequencing "Cindy Lee" wrote > ...asked to make a function that receives text as an argument > and returns the same text, but with 1 added to each number. > So far I have: > def ReceiveAndReturn(): >? ? ? ? sentence=raw_input("Give me a sentence with variables in it: ") The assignment says it should receive the text *as an argument* That means you don't read it using raw_input. Its not clear what the adding one to each number bit means. If we make some assumptions: "2 cats sat on a mat" -> "3 cats sat on a mat" but not "Two cats sat on a mat" -> "Three cats sat on a mat" In other words we are only detecting strings of decimal digits not numeric words. Then we can search the string(a sequence) for consecutive numbers. Convert them from strings to numbers and add one Then insert into the output string. Thats the tricky bit! :-) Have a go, post your code and we will try to help when you get stuck. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcgooly at yahoo.com Thu May 19 14:53:00 2011 From: mcgooly at yahoo.com (Brad Posthumus) Date: Thu, 19 May 2011 05:53:00 -0700 (PDT) Subject: [Tutor] RuntimeError: file does not exist In-Reply-To: References: Message-ID: <31655637.post@talk.nabble.com> Susana Iraiis Delgado Rodriguez wrote: > > Hello Alan!! > Can you please tell me, how to rebuild my path? I've tried it, but I > didn't > succed =( > > The doctest for the Shapefile function includes this line: >>> shp = Shapefile(base='/home/mapnik/data',file='world_borders') This tells you "base" is a path, and "file" is your shapefile. In your code below, you're using the full path of the shapefile for both parameters. Fortunately, your code already seems to provide both required inputs. Try changing this line: lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) ...to: lyr.datasource = mapnik.Shapefile(base=ruta, file=filename) --------------- Brad Posthumus -- View this message in context: http://old.nabble.com/-Tutor--RuntimeError%3A-file-does-not-exist-tp31640074p31655637.html Sent from the Python - tutor mailing list archive at Nabble.com. From enalicho at gmail.com Thu May 19 15:20:49 2011 From: enalicho at gmail.com (Noah Hall) Date: Thu, 19 May 2011 14:20:49 +0100 Subject: [Tutor] Sequencing In-Reply-To: <126284.15226.qm@web132204.mail.ird.yahoo.com> References: <947967.89500.qm@web132207.mail.ird.yahoo.com> <126284.15226.qm@web132204.mail.ird.yahoo.com> Message-ID: On Thu, May 19, 2011 at 11:10 AM, Cindy Lee wrote: > Sorry I am still lost. So I am suppose to use a string? Something like: > (just not sure is the right string...) Well, no. The assignment you've been given states the you need to define a function that takes a string as an argument, for example >>> def take_string(some_string): ... return some_string ... >>> take_string("Hello") 'Hello' There, I have defined a function that takes a string as input, and returns the same string unmodified. What your assignment then says, however, is that you need to retrieve numerical values from the string argument, modify them by adding one, then return the new string. So, to break it down for you - 1) Take a string value 2) Go through the string, taking each character one at a time. Create an empty string to hold characters 3) If character is numerical, complete the number from the string and add one to the total value, then skip the extra chars used to complete the number, storing the new value in the empty string 4) If character is not numeric, store the character in the string 5) Return the created string From susana.delgado_s at utzmg.edu.mx Thu May 19 16:16:58 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Thu, 19 May 2011 09:16:58 -0500 Subject: [Tutor] RuntimeError: file does not exist In-Reply-To: <31655637.post@talk.nabble.com> References: <31655637.post@talk.nabble.com> Message-ID: Hello everyone! Well, I tried this code in other computer and it worked just fine. I changed the line: lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) for lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]) I also did hard coding to test my script: lyr.datasource = mapnik.Shapefile(file='C:\\Python26\\tapalpa_05_plani_line') It also worked as well!! But when I run the module in my computer it throws many errors, if I use lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]), it shows Python Runtime Error: wrong file code: -1991225785 2011/5/19 Brad Posthumus > > > > Susana Iraiis Delgado Rodriguez wrote: > > > > Hello Alan!! > > Can you please tell me, how to rebuild my path? I've tried it, but I > > didn't > > succed =( > > > > > > The doctest for the Shapefile function includes this line: > > >>> shp = Shapefile(base='/home/mapnik/data',file='world_borders') > > This tells you "base" is a path, and "file" is your shapefile. > > In your code below, you're using the full path of the shapefile for both > parameters. Fortunately, your code already seems to provide both required > inputs. Try changing this line: > > lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath) > > ...to: > > lyr.datasource = mapnik.Shapefile(base=ruta, file=filename) > > --------------- > Brad Posthumus > > -- > View this message in context: > http://old.nabble.com/-Tutor--RuntimeError%3A-file-does-not-exist-tp31640074p31655637.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From naheedcse at gmail.com Thu May 19 16:45:19 2011 From: naheedcse at gmail.com (naheed arafat) Date: Thu, 19 May 2011 20:45:19 +0600 Subject: [Tutor] string Message-ID: why there is two way to represent strings in python ? single-coated ( ' ' ) and double-coated ( " " ) strings both serve the purpose of string. Then what is the difference? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu May 19 16:51:34 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 19 May 2011 10:51:34 -0400 Subject: [Tutor] string In-Reply-To: References: Message-ID: On Thu, May 19, 2011 at 10:45 AM, naheed arafat wrote: > why there is two way to represent strings in python ? single-coated > ( ' ' ) and double-coated ( " " ) strings both serve the purpose of string. > Then what is the difference? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > This makes it easy to include quotes within strings without excaping them. There are also """ strings for strings over multiple lines -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu May 19 16:55:49 2011 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 May 2011 07:55:49 -0700 Subject: [Tutor] string In-Reply-To: References: Message-ID: On 5/19/2011 7:45 AM naheed arafat said... > why there is two way to represent strings in python ? single-coated > ( ' ' ) and double-coated ( " " ) strings both serve the purpose of > string. Then what is the difference? > Convenience. Particularly when the strings contain quote characters. mystring = "That's the difference" other = 'Python was named after "Monty Python" the TV show' Emile From alan.gauld at btinternet.com Thu May 19 19:51:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 May 2011 18:51:26 +0100 Subject: [Tutor] Sequencing References: <947967.89500.qm@web132207.mail.ird.yahoo.com> <126284.15226.qm@web132204.mail.ird.yahoo.com> Message-ID: "Cindy Lee" wrote > Sorry I am still lost. Noah gave you a good breakdown to follow however... > So I am suppose to use a string? You are supposed to use a string as a parameter of your function and process it to generate a new string which you return from the function. Do you understand the terms: parameter return from the function > def ReceiveAndReturn(): > str="I have 5 Apples and 6 oranges"; > print "str._add1" This creates a fixed string inside the function, it does not receive the string as argument. And the print statement is very confused. Do you understand the difference between - a string literal - a string variable - a string method - calling a string method HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 19 19:55:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 May 2011 18:55:39 +0100 Subject: [Tutor] xrange() with start or stop > sys.maxint? References: Message-ID: "Terry Carroll" wrote > Is there any way to use xrange with a start or stop value that > exceeds sys.maxint? Not in python v2(*), just use range(). In Python v3 xrange has been removed as has sys.maxint.... (*)Or at least up to 2.5, I don;t have 2.6 or 2.7... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 19 20:05:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 May 2011 19:05:07 +0100 Subject: [Tutor] Data conversion References: <4DD49E3B.4070307@chem.com.au> Message-ID: "Joe Aquilina" wrote > I have a (single table) database file (SQLite3). It has one table, > call it literature, with an integer, autoincrement primary key > field. I have created a data entry form in Python that I want to use > to enter new rows into this database file. On the data entry form I > will enter the values for a new table row - all except the primary > key field. > > What I want to be able to do is to have my data entry form > autoincrement this primary key field for me, with no ability to > change the contents on the data entry form, and save this > incremented value as the value of the num field when I save the new > row. Can I ask you why you are trying to do this yourself? Its normal to let the database generate the key - thats why you define it as autoincrement. If you try to double guess the value and the database is doing something in the background you could get in an awful mess! Either define the ID field as a normal int and you do the autoincrement (by fetching the highest value and adding one) or leave it as autoincrement and let the database do its job. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 19 20:05:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 May 2011 19:05:25 +0100 Subject: [Tutor] RuntimeError: file does not exist References: <31655637.post@talk.nabble.com> Message-ID: "Susana Iraiis Delgado Rodriguez" wrote > Well, I tried this code in other computer and it worked just fine. > > But when I run the module in my computer it throws many errors, So what is different between the computers? What are the respective OS versions and Python versions? How exactly are you running the code on each computer - double click in exporer, from IDLE, from the command line? Its hard to tell what the problem is from your description. > lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]), it > shows > Python Runtime Error: wrong file code: -1991225785 But that looks odd, possibly a problem with the python script file itself? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From aznjonn at me.com Thu May 19 20:23:39 2011 From: aznjonn at me.com (Johnson Tran) Date: Thu, 19 May 2011 11:23:39 -0700 Subject: [Tutor] Program In-Reply-To: References: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> Message-ID: <38214E77-A630-49D9-8816-C8168C7FC3BF@me.com> So I figured out how to use the loop method, thanks. I still cannot seem to figure out how to use Len() to show the output of my answers (from all my googling Len() seems to be used to count characters?) Also, I am not really sure I understand how to use the append method of the list. Here's my best guess so far: def CollectNames(): for attempt in range(1,6): word=raw_input("Name #%d" % attempt) list.append("new") print "All the names in alphabetical order are ", len(L); And just to recap, I was trying to get all the names outputted after the last name was collected (and sort them in alphabetical order. Took my sort commands out until I could figure out how to get any output first.... Thanks for any help. On May 18, 2011, at 7:57 AM, Alan Gauld wrote: > > "Johnson Tran" wrote > >> I had a couple questions about my program: >> >> def CollectNames(): >> answer_set=set([]) >> sorted_list = sorted(answer_set) > > This creates an empty set then sorts it and stores > the result as an empty list. I'm not sure what you > think it does but I'm guessing that's not it... > >> word=raw_input("Name #1: ") >> word=raw_input("Name #2: ") >> word=raw_input("Name #3: ") >> word=raw_input("Name #4: ") >> word=raw_input("Name #5: ") > > Do you know about loops yet? > Any time you find yourself repeating code like > this think about a loop. A for loop could be > used here: > > for attempt in range(1,6): > word = raw_input("Name #%d" % attempt) > > Although storing all the names in the same variable > is also probably not what you want. You need to > add word to your list using the list append() method. > >> print "Your answers sorted: ", ','.join(sorted_list) > > And this is where you probably want to call sorted()... > >> 1.) how do i add each answer given to the list so it is printed at the end? > > Use the append method of the list > >> 2.) also im trying to modify the program so if the >> user puts in the same name, it will give an make >> them try again until they have 5 completely different >> names. > > A combination of a while loop and a set and the len() function > might work here. Keep adding to the set while the length of the > set is <5. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From enalicho at gmail.com Thu May 19 20:45:57 2011 From: enalicho at gmail.com (Noah Hall) Date: Thu, 19 May 2011 19:45:57 +0100 Subject: [Tutor] Program In-Reply-To: <38214E77-A630-49D9-8816-C8168C7FC3BF@me.com> References: <8A984FC7-4E4B-454C-8BD3-A5F1A7EDAC7D@me.com> <38214E77-A630-49D9-8816-C8168C7FC3BF@me.com> Message-ID: On Thu, May 19, 2011 at 7:23 PM, Johnson Tran wrote: > So I figured out how to use the loop method, thanks. I still cannot seem to figure out how to use Len() to show the output of my answers (from all my googling Len() seems to be used to count characters?) Also, I am not really sure I understand how to use the append method of the list. That's true, that's exactly what len does (note, len, not Len). The function you're looking for to sort the output is sorted(). append adds an item to the list, for example - >>> names = ['John'] >>> names.append('Katie') >>> names ['John', 'Katie'] > Here's my best guess so far: > > > def CollectNames(): > > ? ?for attempt in range(1,6): > ? ? ? ?word=raw_input("Name #%d" % attempt) > ? ? ? ?list.append("new") You need to create a list to append to, before you can do this. If you want to use some form of validation, then this is where you want len with set usage, for example >>> names = ['Fred', 'Tom', 'Jake', 'Tom', 'Harry'] >>> names ['Fred', 'Tom', 'Jake', 'Tom', 'Harry'] >>> len(names) 5 >>> names_set = set(names) >>> names_set set(['Harry', 'Tom', 'Jake', 'Fred']) >>> len(names_set) 4 Because "Tom" is in the list twice, and set has unique items only, the length of the set is 4, not 5. This is where you can call whatever validation you want (I suggest using a while loop). > ? ?print "All the names in alphabetical order are ", len(L); This isn't where you want len. There's also nothing called "L" - is this what you called your list? Also, L is a bad name for a variable. Try to use descriptive names where possible. > > And just to recap, I was trying to get all the names outputted after the last name was collected (and sort them in alphabetical order. Took my sort commands out until I could figure out how to get any output first.... HTH. From susana.delgado_s at utzmg.edu.mx Thu May 19 20:52:18 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Thu, 19 May 2011 13:52:18 -0500 Subject: [Tutor] RuntimeError: file does not exist In-Reply-To: References: <31655637.post@talk.nabble.com> Message-ID: Hi Alan!! After I read your e-mail, I remebered that I run the scripts in a different way. The script worked properly when I run it from Python IDLE, I don't have any idea the reason why. 2011/5/19 Alan Gauld > > "Susana Iraiis Delgado Rodriguez" wrote > > > Well, I tried this code in other computer and it worked just fine. >> > > >> But when I run the module in my computer it throws many errors, >> > > So what is different between the computers? > What are the respective OS versions and Python versions? > > How exactly are you running the code on each > computer - double click in exporer, from IDLE, from the command line? > > Its hard to tell what the problem is from your description. > > > lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]), it shows >> Python Runtime Error: wrong file code: -1991225785 >> > > But that looks odd, possibly a problem with the python script file itself? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mywrkid at yahoo.com Thu May 19 22:14:08 2011 From: mywrkid at yahoo.com (Neha P) Date: Thu, 19 May 2011 13:14:08 -0700 (PDT) Subject: [Tutor] Error in executing 'Python Filename.py'. Message-ID: <393070.96518.qm@web121805.mail.ne1.yahoo.com> C:\>python hello.py 'python' is not recognized as an internal or external command, operable program or batch file. C:\>cd python26 C:\Python26>python Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> python hello.py ? File "", line 1 ? ? python hello.py ? ? ? ? ? ? ? ?^ SyntaxError: invalid syntax >>> python Traceback (most recent call last): ? File "", line 1, in NameError: name 'python' is not defined >>> Above is the snapshot of the error. M running Windows 7 Home Premium, OS: NT Have??;C:\Python26 added to?the?PATH variable?, still unable to execute any file :( same error. Please help!! Thanks in advance.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu May 19 22:21:18 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 19 May 2011 16:21:18 -0400 Subject: [Tutor] Error in executing 'Python Filename.py'. In-Reply-To: <393070.96518.qm@web121805.mail.ne1.yahoo.com> References: <393070.96518.qm@web121805.mail.ne1.yahoo.com> Message-ID: You're in the python interpreter. Hit control C to go back to cmd and then you can do "python hello.py" On Thu, May 19, 2011 at 4:14 PM, Neha P wrote: > C:\>python hello.py > 'python' is not recognized as an internal or external command, > operable program or batch file. > > C:\>cd python26 > > C:\Python26>python > Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> python hello.py > File "", line 1 > python hello.py > ^ > SyntaxError: invalid syntax > >>> python > Traceback (most recent call last): > File "", line 1, in > NameError: name 'python' is not defined > >>> > > Above is the snapshot of the error. > M running Windows 7 Home Premium, OS: NT > Have ;C:\Python26 added to the PATH variable , still unable to execute > any file :( same error. > > Please help!! Thanks in advance.. > > > > > _______________________________________________ > 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 ian.douglas at iandouglas.com Thu May 19 22:25:11 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Thu, 19 May 2011 13:25:11 -0700 Subject: [Tutor] BaseHTTPServer, how do catch/trap "broken pipe" errors? Message-ID: <4DD57CA7.7000109@iandouglas.com> Hey all, I released my short URL engine last night and it works great. The only problem I'm having now is that it's throwing LOTS of 'broken pipe' errors, which as I understand from looking at raw socket docs in Python, should throw a trappable exception. This might be a little more 'advanced' than the average tutor questions, so I posted some details at StackOverflow.com just so I could keep the huge code sample and error messages off the mailing list. I'd appreciate it if anyone could help me figure out where the best place is to wrap a try/except call, and which exceptions I should be looking for. http://stackoverflow.com/questions/6063416/python-basehttpserver-how-do-i-catch-trap-broken-pipe-errors Cheers, Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Thu May 19 22:36:24 2011 From: enalicho at gmail.com (Noah Hall) Date: Thu, 19 May 2011 21:36:24 +0100 Subject: [Tutor] Error in executing 'Python Filename.py'. In-Reply-To: <393070.96518.qm@web121805.mail.ne1.yahoo.com> References: <393070.96518.qm@web121805.mail.ne1.yahoo.com> Message-ID: On Thu, May 19, 2011 at 9:14 PM, Neha P wrote: > C:\>python hello.py > 'python' is not recognized as an internal or external command, > operable program or batch file. This happens because "python.exe" is not in the system path. > C:\>cd python26 > C:\Python26>python > Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] > on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> python hello.py > ? File "", line 1 > ? ? python hello.py > ? ? ? ? ? ? ? ?^ > SyntaxError: invalid syntax Now, this happens because you're in the python interpretor. Calling python.exe will do this, unless you provide it with a file to interpret. When you run this, you're already in the interpretor. Even if it did work, it wouldn't because hello.py isn't in the path, unless you've saved it to C:\Python26 or the location you've saved it to is in the path. >>>> python > Traceback (most recent call last): > ? File "", line 1, in > NameError: name 'python' is not defined Again, see above. >>>> > Above is the snapshot of the error. > M running Windows 7 Home Premium, OS: NT > Have??;C:\Python26 added to?the?PATH variable?, still unable to execute any > file :( same error. > Please help!! Thanks in advance.. Ah. Well, did you click OK to save it, then restart your shell? If you did, try "echo %PATH%" if you're using cmd, or "$env:Path" if you're using Powershell, and paste the output here. From mywrkid at yahoo.com Thu May 19 22:40:27 2011 From: mywrkid at yahoo.com (Neha P) Date: Thu, 19 May 2011 13:40:27 -0700 (PDT) Subject: [Tutor] Error in executing 'Python Filename.py'. In-Reply-To: <393070.96518.qm@web121805.mail.ne1.yahoo.com> References: <393070.96518.qm@web121805.mail.ne1.yahoo.com> Message-ID: <149081.32491.qm@web121816.mail.ne1.yahoo.com> Hey all, got the solution... Thanks for the help :) :) Just needed to from? C:\Python26>Python hello.py Its working fine... ________________________________ From: Neha P To: "tutor at python.org" Sent: Thursday, May 19, 2011 4:14 PM Subject: [Tutor] Error in executing 'Python Filename.py'. C:\>python hello.py 'python' is not recognized as an internal or external command, operable program or batch file. C:\>cd python26 C:\Python26>python Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> python hello.py ? File "", line 1 ? ? python hello.py ? ? ? ? ? ? ? ?^ SyntaxError: invalid syntax >>> python Traceback (most recent call last): ? File "", line 1, in NameError: name 'python' is not defined >>> Above is the snapshot of the error. M running Windows 7 Home Premium, OS: NT Have??;C:\Python26 added to?the?PATH variable?, still unable to execute any file :( same error. Please help!! Thanks in advance.. _______________________________________________ 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 karim.liateni at free.fr Thu May 19 22:57:06 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 19 May 2011 22:57:06 +0200 Subject: [Tutor] Writing OpenOffice/LibreOffice doc with python Message-ID: <4DD58422.1030809@free.fr> Hello All, Is it possible to write document in ODP or DOC format with a python API? Do you know an easy one and popular one which works with python 2.7.1? Cheers Karim From karim.liateni at free.fr Fri May 20 00:49:37 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 20 May 2011 00:49:37 +0200 Subject: [Tutor] Writing OpenOffice/LibreOffice doc with python In-Reply-To: <4DD58422.1030809@free.fr> References: <4DD58422.1030809@free.fr> Message-ID: <4DD59E81.9040900@free.fr> On 05/19/2011 10:57 PM, Karim wrote: > > Hello All, > > Is it possible to write document in ODP or DOC format with a python API? > > Do you know an easy one and popular one which works with python 2.7.1? > > Cheers > Karim > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I found at last pyUNO include in OpenOffice and the wrapper exist in python standard module uno and unohelper which is pretty fun if you know others don't hesitate. Karim Cheers From joe at chem.com.au Fri May 20 04:02:17 2011 From: joe at chem.com.au (Joe Aquilina) Date: Fri, 20 May 2011 10:02:17 +0800 Subject: [Tutor] Data conversion In-Reply-To: References: <4DD49E3B.4070307@chem.com.au> <4DD4B597.8010903@chem.com.au> Message-ID: <4DD5CBA9.6050407@chem.com.au> On 19/05/11 17:26, Andre Engels wrote: > On Thu, May 19, 2011 at 8:15 AM, Joe Aquilina wrote: > >> I realised after I read your response that I probably hadn't included enough >> information, partly due to my inexperience in Python and partly due to >> haste on my part. >> >> AFter my original post, I had a little play in Python and was able to create >> this tuple: >> >> [1, 2, 3, 4, 5] >> >> from which I was able to extract any item I wanted as an integer and work >> with as I wanted. I am guessing that this is a 1-tuple. > No, this is an array. However, an array and a tuple work similarly in > many cases. A 1-tuple is a tuple with one element, so this is > definitely not a 1-tuple. > >> It is when I do the fetchall() from the table, that I get the following: >> >> [(1,), (2,), (3,)] >> >> I don't know enough to know whether this is a 1-tuple or not. It is from >> this tuple that I want to extract the 3 as an integer so that I can >> increment it and save as an integer into the next row in the table. > This again is an array, but this time the elements are tuples (indeed > 1-tuples). To show you how to get the value 3 from this: > >>>> A = [(1,), (2,), (3,)] >>>> A[2] > (3,) >>>> A[-1] > (3,) >>>> B = A[-1] >>>> B > (3,) >>>> B[0] > 3 >>>> A[-1][0] > 3 > > I see now, and understand how it works. This is a lot simpler and easier than what I tried yesterday. Thanks again. Joe Aquilina. From bugcy013 at gmail.com Fri May 20 13:09:59 2011 From: bugcy013 at gmail.com (Ganesh Kumar) Date: Fri, 20 May 2011 16:39:59 +0530 Subject: [Tutor] What is if __name__ == "__main__" for? Message-ID: Hi Gurus, I am new python programming.. I see many programs if __name__ == '__main__': when I check __name__ always eq __main__. what purpose use these structure.. please guide me.. -Ganesh -- Did I learn something today? If not, I wasted it. From wprins at gmail.com Fri May 20 13:26:39 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 20 May 2011 12:26:39 +0100 Subject: [Tutor] What is if __name__ == "__main__" for? In-Reply-To: References: Message-ID: On 20 May 2011 12:09, Ganesh Kumar wrote: > Hi Gurus, > > I am new python programming.. I see many programs > if __name__ == '__main__': > when I check __name__ always eq __main__. > what purpose use these structure.. please guide me.. > > -Ganesh Here you go: http://lmgtfy.com/?q=What+is+the+purpose+of+if+__name__+%3D+%27__main__%27 ;) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Fri May 20 13:34:15 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Fri, 20 May 2011 17:04:15 +0530 Subject: [Tutor] What is if __name__ == "__main__" for? In-Reply-To: References: Message-ID: If the module is run as a program, then the __name__ is assigned the value __main__ . If the module is imported, then the value is not assigned. Please see here - http://stackoverflow.com/questions/419163/what-does-if-name-main-do On Fri, May 20, 2011 at 4:39 PM, Ganesh Kumar wrote: > Hi Gurus, > > I am new python programming.. I see many programs > if __name__ == '__main__': > when I check __name__ always eq __main__. > what purpose use these structure.. please guide me.. > > -Ganesh > > -- > Did I learn something today? If not, I wasted it. > _______________________________________________ > 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 cwitts at compuscan.co.za Fri May 20 13:29:17 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 20 May 2011 13:29:17 +0200 Subject: [Tutor] What is if __name__ == "__main__" for? In-Reply-To: References: Message-ID: <4DD6508D.2070207@compuscan.co.za> On 2011/05/20 01:09 PM, Ganesh Kumar wrote: > Hi Gurus, > > I am new python programming.. I see many programs > if __name__ == '__main__': > when I check __name__ always eq __main__. > what purpose use these structure.. please guide me.. > > -Ganesh > If you execute the script directly ie. python script.py the __name__ will be __main__ but if you import it it's the name of the file. #first.py print __name__ #second.py import first$ python first.py __main__ $python second.py first -- Christian Witts From cwitts at compuscan.co.za Fri May 20 13:31:28 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 20 May 2011 13:31:28 +0200 Subject: [Tutor] What is if __name__ == "__main__" for? In-Reply-To: <4DD6508D.2070207@compuscan.co.za> References: <4DD6508D.2070207@compuscan.co.za> Message-ID: <4DD65110.4040603@compuscan.co.za> On 2011/05/20 01:29 PM, Christian Witts wrote: > On 2011/05/20 01:09 PM, Ganesh Kumar wrote: >> Hi Gurus, >> >> I am new python programming.. I see many programs >> if __name__ == '__main__': >> when I check __name__ always eq __main__. >> what purpose use these structure.. please guide me.. >> >> -Ganesh >> > > If you execute the script directly ie. python script.py the __name__ > will be __main__ but if you import it it's the name of the file. > > #first.py > print __name__ > > #second.py > import first > >$ python first.py > __main__ > > $python second.py > first > Sorry, forgot to add before sending that the reason I use the if __name__ == '__main__' structure is so that I can have a standalone application that has it's defined entry point and then if I want to reuse functions in the application I can import it without having to worry that it will execute the entire thing. -- Christian Witts From hgfernan at gmail.com Fri May 20 14:32:31 2011 From: hgfernan at gmail.com (Hilton Fernandes) Date: Fri, 20 May 2011 09:32:31 -0300 Subject: [Tutor] What is if __name__ == "__main__" for? In-Reply-To: <4DD65110.4040603@compuscan.co.za> References: <4DD6508D.2070207@compuscan.co.za> <4DD65110.4040603@compuscan.co.za> Message-ID: Hi, Ganesh ! An important use of this feature is the so-called modular testing, aka unit testing. I mean: that way you can provide functionality in your module to test it independently of any application it may be contained in. Unit testing in general is easier and quicker to do than to test the whole application in which any given module is contained, along with probably lots of other modules. The Wikipedia article Unit Testing, at https://secure.wikimedia.org/wikipedia/en/wiki/Unit_testing will make things clear. All the best, hilton On Fri, May 20, 2011 at 8:31 AM, Christian Witts wrote: > On 2011/05/20 01:29 PM, Christian Witts wrote: >> >> On 2011/05/20 01:09 PM, Ganesh Kumar wrote: >>> >>> Hi Gurus, >>> >>> I am new python programming.. I see many programs >>> if __name__ == '__main__': >>> when I check __name__ always eq __main__. >>> what purpose use these structure.. please guide me.. >>> >>> -Ganesh >>> >> >> If you execute the script directly ie. python script.py the __name__ >> will be __main__ but if you import it it's the name of the file. >> >> #first.py >> print __name__ >> >> #second.py >> import first >> >>$ python first.py >> __main__ >> >> $python second.py >> first >> > > Sorry, forgot to add before sending that the reason I use the if __name__ > == '__main__' structure is so that I can have a standalone application that > has it's defined entry point and then if I want to reuse functions in the > application I can import it without having to worry that it will execute the > entire thing. > > -- > Christian Witts > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From hgfernan at lsi.usp.br Fri May 20 14:56:04 2011 From: hgfernan at lsi.usp.br (Hilton Garcia Fernandes) Date: Fri, 20 May 2011 12:56:04 -0000 Subject: [Tutor] What is if __name__ == "__main__" for? In-Reply-To: <4DD65110.4040603@compuscan.co.za> References: <4DD6508D.2070207@compuscan.co.za>, <4DD6508D.2070207@compuscan.co.za> Message-ID: Hi, Ganesh ! Adding to what Christian already stated, i'd like to tell you that an important use of this feature is the so-called modular testing, aka unit testing. I mean: that way you can provide functionality in your module to test it independently of any application it may be contained in. Unit testing in general is easier and quicker to do than to test the whole application in which any given module is contained, along with probably lots of other modules. The Wikipedia article Unit Testing, at https://secure.wikimedia.org/wikipedia/en/wiki/Unit_testing will make things clear. All the best, hilton On Fri, Maio 20, 2011, Christian Witts said: > On 2011/05/20 01:29 PM, Christian Witts wrote: >> On 2011/05/20 01:09 PM, Ganesh Kumar wrote: >>> Hi Gurus, >>> >>> I am new python programming.. I see many programs >>> if __name__ == '__main__': >>> when I check __name__ always eq __main__. >>> what purpose use these structure.. please guide me.. >>> >>> -Ganesh >>> >> >> If you execute the script directly ie. python script.py the __name__ >> will be __main__ but if you import it it's the name of the file. >> >> #first.py >> print __name__ >> >> #second.py >> import first >> >>$ python first.py >> __main__ >> >> $python second.py >> first >> > > Sorry, forgot to add before sending that the reason I use the if > __name__ == '__main__' structure is so that I can have a standalone > application that has it's defined entry point and then if I want to > reuse functions in the application I can import it without having to > worry that it will execute the entire thing. > > -- > Christian Witts > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Hilton Garcia Fernandes Nucleo de Tecnologias sem Fio (NTSF) -- Wireless Technologies Team Lab de Sistemas Integraveis Tecnologico (LSI) -- Integrable Systems Lab Escola Politecnica (Poli) -- Engineering School Univ S Paulo (USP) Tel: (5511)3091-5311 (work) (5511)8131-5213 (mobile) Av. Prof. Luciano Gualberto,158 trav.3 CEP 05508-900 S. Paulo -- SP -- Brazil Pagina inicial: http://www.lsi.usp.br/~hgfernan Blog http://bit.ly/8YITGc com espelhamento em http://bit.ly/4SIgzO From s.charonis at gmail.com Fri May 20 15:12:21 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Fri, 20 May 2011 14:12:21 +0100 Subject: [Tutor] STRING PROC Message-ID: Hello List, A quick string processing query. If I have an entry in a list such as ['>NAME\n'], is there a way to split it into two separate lines: > NAME -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri May 20 15:55:03 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 May 2011 14:55:03 +0100 Subject: [Tutor] STRING PROC References: Message-ID: "Spyros Charonis" wrote > A quick string processing query. If I have an entry in a list such > as > ['>NAME\n'], > is there a way to split it into two separate lines: > >> > NAME Yes if you know where the linebreak will be. s = ">NAME\n" twolines = [s[0],s[1:]] # list of two strings for line in twolines; print line or if you really just want a newline inserted: twolines = s[0] + '\n' + s[1:] insert newline or use replace: twolines = s.replace( '>' , '>\n' ) If you want more sophistication you could use a regex to determine the split point. hth, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From spawgi at gmail.com Fri May 20 16:05:05 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Fri, 20 May 2011 19:35:05 +0530 Subject: [Tutor] STRING PROC In-Reply-To: References: Message-ID: You can also try this >>> a = '>> a '>> a.partition('<') ('', '<', 'NAME') >>> splitstring = a.partition('<') >>> splitstring ('', '<', 'NAME') >>> splitstring[0] '' >>> splitstring[1] '<' >>> splitstring[2] 'NAME' I guess you can use this tuple. Hope this helps. Thanks and Regards, Sumod On Fri, May 20, 2011 at 6:42 PM, Spyros Charonis wrote: > Hello List, > > A quick string processing query. If I have an entry in a list such as > ['>NAME\n'], > is there a way to split it into two separate lines: > > > > NAME > > _______________________________________________ > 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 alan.gauld at btinternet.com Fri May 20 19:16:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 May 2011 18:16:31 +0100 Subject: [Tutor] STRING PROC References: Message-ID: wrote >>>> a.partition('<') > ('', '<', 'NAME') Ooh! A new string method for me. I've never notioced partition before. Thanks for posting. Alan G. From jigenbakuda at yahoo.com Fri May 20 19:43:44 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Fri, 20 May 2011 10:43:44 -0700 (PDT) Subject: [Tutor] Making a script part of the terminal Message-ID: <709143.90354.qm@web130222.mail.mud.yahoo.com> Okay, my title might be undescriptive, let me try to explain it better. I want to take a script I've written and make it usable by typing its name in the terminal. Perfect example is the python interpreter. You just type in the word python to the terminal and then the interpreter runs. I know other programs can do this as well (like mozilla or nautilus or rhythmbox). So how do I make my scripts executable from the terminal? ---- What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Fri May 20 19:57:57 2011 From: eire1130 at gmail.com (James Reynolds) Date: Fri, 20 May 2011 13:57:57 -0400 Subject: [Tutor] Making a script part of the terminal In-Reply-To: <709143.90354.qm@web130222.mail.mud.yahoo.com> References: <709143.90354.qm@web130222.mail.mud.yahoo.com> Message-ID: We just had a similar question yesterday. Just make sure Python is on your PATH. CD to the directory where your file is located and then you can just type "python myfile.py" where myfile is the name of your file. On Fri, May 20, 2011 at 1:43 PM, michael scott wrote: > Okay, my title might be undescriptive, let me try to explain it better. I > want to take a script I've written and make it usable by typing its name in > the terminal. Perfect example is the python interpreter. You just type in > the word python to the terminal and then the interpreter runs. I know other > programs can do this as well (like mozilla or nautilus or rhythmbox). So > how do I make my scripts executable from the terminal? > > ---- > What is it about you... that intrigues me so? > > > _______________________________________________ > 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 timomlists at gmail.com Fri May 20 20:00:53 2011 From: timomlists at gmail.com (Timo) Date: Fri, 20 May 2011 20:00:53 +0200 Subject: [Tutor] Making a script part of the terminal In-Reply-To: <709143.90354.qm@web130222.mail.mud.yahoo.com> References: <709143.90354.qm@web130222.mail.mud.yahoo.com> Message-ID: <4DD6AC55.9040003@gmail.com> On 20-05-11 19:43, michael scott wrote: > Okay, my title might be undescriptive, let me try to explain it > better. I want to take a script I've written and make it usable by > typing its name in the terminal. Perfect example is the python > interpreter. You just type in the word python to the terminal and then > the interpreter runs. I know other programs can do this as well (like > mozilla or nautilus or rhythmbox). So how do I make my scripts > executable from the terminal? I can only speak for Linux, but your script should be in a directory that is in the PATH variable of your environment. The reason why you can just enter a program name in the terminal, is because these should be in /usr/bin or /usr/local/bin and these are in PATH. Type this in the terminal to see which ones: echo$PATH You can either put your script in one of those directories or add on to PATH. Cheers, Timo > ---- > What is it about you... that intrigues me so? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From samudhio at gmail.com Fri May 20 20:03:50 2011 From: samudhio at gmail.com (Edgar Almonte) Date: Fri, 20 May 2011 14:03:50 -0400 Subject: [Tutor] Making a script part of the terminal In-Reply-To: <709143.90354.qm@web130222.mail.mud.yahoo.com> References: <709143.90354.qm@web130222.mail.mud.yahoo.com> Message-ID: hey ! i can answer that ! birst in the fist line of you script put something like this #!/usr/local/bin/python change the path for where you have python ( try using 'whereis python' ) sencond make the file executable add the +x attribute ( using chmod ) third put the script in some place and and that path to the PATH enviroment variable. good luck On Fri, May 20, 2011 at 1:43 PM, michael scott wrote: > Okay, my title might be undescriptive, let me try to explain it better. I > want to take a script I've written and make it usable by typing its name in > the terminal. Perfect example is the python interpreter. You just type in > the word python to the terminal and then the interpreter runs. I know other > programs can do this as well (like mozilla or nautilus or rhythmbox).? So > how do I make my scripts executable from the terminal? > > ---- > What is it about you... that intrigues me so? > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From ralf at schoenian-online.de Fri May 20 20:07:16 2011 From: ralf at schoenian-online.de (ralf at schoenian-online.de) Date: Fri, 20 May 2011 20:07:16 +0200 (CEST) Subject: [Tutor] Making a script part of the terminal In-Reply-To: <709143.90354.qm@web130222.mail.mud.yahoo.com> References: <709143.90354.qm@web130222.mail.mud.yahoo.com> Message-ID: <1883191087.879859.1305914836952.JavaMail.open-xchange@oxltgw16.schlund.de> Hello Michael, ? first you have to give your script an executable bit. Just type chmod +x your_script.py Furhtermore, your script has to be in a directory that is also part of your search path. Type in echo $PATH to see how your path is set. You can either link or copy your script to an approprate location. ? Regards, Ralf? ? michael scott hat am 20. Mai 2011 um 19:43 geschrieben: > > Okay, my title might be undescriptive, let me try to explain it better. I want > to take a script I've written and make it usable by typing its name in the > terminal. Perfect example is the python interpreter. You just type in the word > python to the terminal and then the interpreter runs. I know other programs > can do this as well (like mozilla or nautilus or rhythmbox).? So how do I make > my scripts executable from the terminal? > > ?---- > What is it about you... that intrigues me so? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Fri May 20 20:07:33 2011 From: enalicho at gmail.com (Noah Hall) Date: Fri, 20 May 2011 19:07:33 +0100 Subject: [Tutor] Making a script part of the terminal In-Reply-To: <709143.90354.qm@web130222.mail.mud.yahoo.com> References: <709143.90354.qm@web130222.mail.mud.yahoo.com> Message-ID: On Fri, May 20, 2011 at 6:43 PM, michael scott wrote: > Okay, my title might be undescriptive, let me try to explain it better. I > want to take a script I've written and make it usable by typing its name in > the terminal. Perfect example is the python interpreter. You just type in > the word python to the terminal and then the interpreter runs. I know other > programs can do this as well (like mozilla or nautilus or rhythmbox).? So > how do I make my scripts executable from the terminal? Since you've mentioned Linux applications, I'm going to guess you mean on Linux only. This is easy. In Unix scripts, we use something called a shebang. A shebang is the very first line which basically tells the terminal what program to use to run the script. For Python, it should be "#! /usr/bin/python" (or where ever your python interpreter is, you can find this out by using "which python") Hope this helps. From jigenbakuda at yahoo.com Fri May 20 20:10:57 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Fri, 20 May 2011 11:10:57 -0700 (PDT) Subject: [Tutor] Making a script part of the terminal In-Reply-To: References: <709143.90354.qm@web130222.mail.mud.yahoo.com> Message-ID: <328723.20138.qm@web130202.mail.mud.yahoo.com> Thank you for the reply, but thats not exactly what I mean. Perhaps I should say, how do I install a program to my computer, so that I can use it by its self without running it with python. No matter what directory I'm in I can type mozilla in and it runs, no matter what directory I'm in if I type sudo natutilus it will run, no matter what directory I'm in if I type gedit it will run. So I'm trying to achieve this with the script I wrote. I don't know the terminology to ask the question correctly, so forgive me. ---- What is it about you... that intrigues me so? ________________________________ From: James Reynolds To: michael scott Cc: tutor at python.org Sent: Fri, May 20, 2011 1:57:57 PM Subject: Re: [Tutor] Making a script part of the terminal We just had a similar question yesterday. Just make sure Python is on your PATH. CD to the directory where your file is located and then you can just type "python myfile.py" where myfile is the name of your file. On Fri, May 20, 2011 at 1:43 PM, michael scott wrote: Okay, my title might be undescriptive, let me try to explain it better. I want to take a script I've written and make it usable by typing its name in the terminal. Perfect example is the python interpreter. You just type in the word python to the terminal and then the interpreter runs. I know other programs can do this as well (like mozilla or nautilus or rhythmbox). So how do I make my scripts executable from the terminal? > > ---- >What is it about you... that intrigues me so? > > >_______________________________________________ >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 jigenbakuda at yahoo.com Fri May 20 20:24:06 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Fri, 20 May 2011 11:24:06 -0700 (PDT) Subject: [Tutor] Making a script part of the terminal In-Reply-To: References: <709143.90354.qm@web130222.mail.mud.yahoo.com> Message-ID: <802284.36966.qm@web130221.mail.mud.yahoo.com> Thank you gentlemen so much, I believe I have all that I need to do what I wish. ---- What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Fri May 20 20:29:30 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Fri, 20 May 2011 11:29:30 -0700 Subject: [Tutor] Making a script part of the terminal In-Reply-To: References: <709143.90354.qm@web130222.mail.mud.yahoo.com> Message-ID: <4DD6B30A.3080303@iandouglas.com> To expand further, some distributions of Linux set a 'bin' path under your home folder as part of your native PATH, even if it doesn't exist. So if your Linux username is, say, "mscott", see if "echo$PATH" already includes something like "/home/mscott/bin" in the path already. If so, simply create a bin folder: mkdir ~/bin and then place your Python scripts within that folder, and follow Edgar's other advice about adding #!/usr/local/bin/python and using "chmod +x filename.py" etc. If you're on a non-Linux platform, I'm sure others can provide further help. -id On 05/20/2011 11:03 AM, Edgar Almonte wrote: > hey ! i can answer that ! > > birst in the fist line of you script put something like this > > #!/usr/local/bin/python > > change the path for where you have python ( try using 'whereis python' ) > > sencond make the file executable add the +x attribute ( using chmod ) > > third put the script in some place and and that path to the PATH > enviroment variable. > > good luck > > > On Fri, May 20, 2011 at 1:43 PM, michael scott wrote: >> Okay, my title might be undescriptive, let me try to explain it better. I >> want to take a script I've written and make it usable by typing its name in >> the terminal. Perfect example is the python interpreter. You just type in >> the word python to the terminal and then the interpreter runs. I know other >> programs can do this as well (like mozilla or nautilus or rhythmbox). So >> how do I make my scripts executable from the terminal? >> >> ---- >> What is it about you... that intrigues me so? >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Fri May 20 20:44:45 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Fri, 20 May 2011 11:44:45 -0700 Subject: [Tutor] Making a script part of the terminal In-Reply-To: <328723.20138.qm@web130202.mail.mud.yahoo.com> References: <709143.90354.qm@web130222.mail.mud.yahoo.com> <328723.20138.qm@web130202.mail.mud.yahoo.com> Message-ID: <7D9FF81B-F511-48BB-A20F-3D7D1FE335EF@gmail.com> Hi Michael, You have to do three (four) things. 1 - make a directory where you want your executables to live (after you have created them) on my machine, I copy everything to /usr/local/walkloud/bin/ which requires sudo, but you can put them anywhere in your $PATH 2 - in your .tcshrc or .cshrc or equivalent file (to figure it out, type echo$SHELL to figure out your shell if you have no idea what I am talking about), you must append your path. eg. with tcshrc (in the .tcshrc file) - the .tcshrc file is located in your $HOME dir. setenv PATH /usr/local/walkloud/bin:$PATH 3 - if you haven't, in the directory where your script lives chmod +x your_script 4 - cp your script to this directory in 1- launch a new terminal and it should work. Andre On May 20, 2011, at 11:10 AM, michael scott wrote: > Thank you for the reply, but thats not exactly what I mean. Perhaps I should say, how do I install a program to my computer, so that I can use it by its self without running it with python. No matter what directory I'm in I can type mozilla in and it runs, no matter what directory I'm in if I type sudo natutilus it will run, no matter what directory I'm in if I type gedit it will run. > > So I'm trying to achieve this with the script I wrote. I don't know the terminology to ask the question correctly, so forgive me. > > ---- > What is it about you... that intrigues me so? > > > From: James Reynolds > To: michael scott > Cc: tutor at python.org > Sent: Fri, May 20, 2011 1:57:57 PM > Subject: Re: [Tutor] Making a script part of the terminal > > We just had a similar question yesterday. > > Just make sure Python is on your PATH. CD to the directory where your file is located and then you can just type "pythonmyfile.py" where myfile is the name of your file. > > On Fri, May 20, 2011 at 1:43 PM, michael scott wrote: > Okay, my title might be undescriptive, let me try to explain it better. I want to take a script I've written and make it usable by typing its name in the terminal. Perfect example is the python interpreter. You just type in the word python to the terminal and then the interpreter runs. I know other programs can do this as well (like mozilla or nautilus or rhythmbox). So how do I make my scripts executable from the terminal? > > ---- > What is it about you... that intrigues me so? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri May 20 20:42:19 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 20 May 2011 14:42:19 -0400 Subject: [Tutor] Making a script part of the terminal In-Reply-To: <328723.20138.qm@web130202.mail.mud.yahoo.com> References: <709143.90354.qm@web130222.mail.mud.yahoo.com> <328723.20138.qm@web130202.mail.mud.yahoo.com> Message-ID: On Fri, May 20, 2011 at 2:10 PM, michael scott wrote: > Thank you for the reply, but thats not exactly what I mean. Perhaps I > should say, how do I install a program to my computer, so that I can use it > by its self without running it with python. No matter what directory I'm in > I can type mozilla in and it runs, no matter what directory I'm in if I type > sudo natutilus it will run, no matter what directory I'm in if I type gedit > it will run. > > So I'm trying to achieve this with the script I wrote. I don't know the > terminology to ask the question correctly, so forgive me. > > > ---- > What is it about you... that intrigues me so? > > > ------------------------------ > *From:* James Reynolds > *To:* michael scott > *Cc:* tutor at python.org > *Sent:* Fri, May 20, 2011 1:57:57 PM > *Subject:* Re: [Tutor] Making a script part of the terminal > > We just had a similar question yesterday. > > Just make sure Python is on your PATH. CD to the directory where your file > is located and then you can just type "python myfile.py" where myfile is > the name of your file. > > On Fri, May 20, 2011 at 1:43 PM, michael scott wrote: > >> Okay, my title might be undescriptive, let me try to explain it better. I >> want to take a script I've written and make it usable by typing its name in >> the terminal. Perfect example is the python interpreter. You just type in >> the word python to the terminal and then the interpreter runs. I know other >> programs can do this as well (like mozilla or nautilus or rhythmbox). So >> how do I make my scripts executable from the terminal? >> >> ---- >> What is it about you... that intrigues me so? >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You need to do the #!/usr/bin/env python or #!/usr/bin/python thing in your file Then change it to being executable as described above Lastly, you need to put your program in a directly where the $PATH environment variable knows to look for it -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidheiserca at gmail.com Fri May 20 21:35:30 2011 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Fri, 20 May 2011 12:35:30 -0700 Subject: [Tutor] Making a script part of the terminal References: <709143.90354.qm@web130222.mail.mud.yahoo.com> <328723.20138.qm@web130202.mail.mud.yahoo.com> Message-ID: I think I understand. One thing you can do is create a "myprogram.bat" file with an entry something like: python c:/myprogrampath/myprogram.py Put the "myprogram.bat" file in the root directory or any directory in the PATH. Then it will behave like an executable. In Linux, it would be "myprogram.sh" with the executable bit set. ----- Original Message ----- From: michael scott To: tutor at python.org Sent: Friday, May 20, 2011 11:10 AM Subject: Re: [Tutor] Making a script part of the terminal Thank you for the reply, but thats not exactly what I mean. Perhaps I should say, how do I install a program to my computer, so that I can use it by its self without running it with python. No matter what directory I'm in I can type mozilla in and it runs, no matter what directory I'm in if I type sudo natutilus it will run, no matter what directory I'm in if I type gedit it will run. So I'm trying to achieve this with the script I wrote. I don't know the terminology to ask the question correctly, so forgive me. ---- What is it about you... that intrigues me so? ------------------------------------------------------------------------------ From: James Reynolds To: michael scott Cc: tutor at python.org Sent: Fri, May 20, 2011 1:57:57 PM Subject: Re: [Tutor] Making a script part of the terminal We just had a similar question yesterday. Just make sure Python is on your PATH. CD to the directory where your file is located and then you can just type "python myfile.py" where myfile is the name of your file. On Fri, May 20, 2011 at 1:43 PM, michael scott wrote: Okay, my title might be undescriptive, let me try to explain it better. I want to take a script I've written and make it usable by typing its name in the terminal. Perfect example is the python interpreter. You just type in the word python to the terminal and then the interpreter runs. I know other programs can do this as well (like mozilla or nautilus or rhythmbox). So how do I make my scripts executable from the terminal? ---- What is it about you... that intrigues me so? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri May 20 23:51:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 May 2011 22:51:36 +0100 Subject: [Tutor] Making a script part of the terminal References: <709143.90354.qm@web130222.mail.mud.yahoo.com> <328723.20138.qm@web130202.mail.mud.yahoo.com> Message-ID: "michael scott" wrote > say, how do I install a program to my computer, so that > I can use it by its self without running it with python. Just to be clear, Python programs are interpreted by the Python interpreter. So while you can set things up such that you don't need to explicitly cakll Pyhon, it will always be there in the background. And if you try to run your script on a machine that doesn't have Python installed it will fail. You probably knew that already but I just want to set your expectations... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From robert.sjoblom at gmail.com Sat May 21 12:24:34 2011 From: robert.sjoblom at gmail.com (=?utf-8?Q?Robert_Sj=C3=B6blom?=) Date: Sat, 21 May 2011 12:24:34 +0200 Subject: [Tutor] Help with understanding classes Message-ID: I'm trying to wrap my head around classes and their attributes, but am having a hard time doing so. The websites and books that I have consulted haven't been much help; most of them assume prior programming/oop experience, something I lack. From what I understand it's a "blueprint", so each time you instantiate it you run whatever's in the __self__ part is assigned to the instance. What I'm wondering is how to access and change attributes in the instance (whatever it might be; a list, a specific value, a string...). I just can't seem to grasp the concept or syntax very well, and none of the sources I've found go to great lengths explaining them to someone as thick-headed as me. So if anyone could take the time to explain, or point me to sources to read, I'd be grateful Thanks in advance, and best regards, Robert S. Sent from my iPhone From steve at pearwood.info Sat May 21 13:49:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 21 May 2011 21:49:27 +1000 Subject: [Tutor] Help with understanding classes In-Reply-To: References: Message-ID: <201105212149.27820.steve@pearwood.info> On Sat, 21 May 2011 08:24:34 pm Robert Sj?blom wrote: > I'm trying to wrap my head around classes and their attributes, but > am having a hard time doing so. The websites and books that I have > consulted haven't been much help; most of them assume prior > programming/oop experience, something I lack. Let's start with a simple question -- what is an object? In programming, an object is a thing that combines data and behaviour together in one handy package. Back in the Dark Ages *wink*, code and behaviour were always separate, so you would have to design a data structure in one place of your program, then write functions to manipulate it somewhere else. If you had two different data structures which needed similar actions, you had to jump through hoops to keep the functions for one separate from the functions of the other. But objects let you keep related pieces of code together, so they don't get in the way of unrelated code with the same name: class Artist: def draw(self): print("I splashed paint on the canvas until it looked like" " my mother on a rocking horse.") class GunSlinger: def draw(self): print("The stranger reached for his gun, but I was too" " quick for him and plugged him full of lead.") The function (actually "method") called draw for Artists doesn't get over-ridden by the method with the same name for GunSlingers: >>> whistler = Artist() >>> wyatt_earp = GunSlinger() >>> whistler.draw() I splashed paint on the canvas until it looked like my mother on a rocking horse. >>> wyatt_earp.draw() The stranger reached for his gun, but I was too quick for him and plugged him full of lead. Here you see object code in action. You start with a class, which is something vaguely like a template. (It's actually nothing like a template, but that will do for now.) Before you can use the class, you normally have to instantiate it. Think of it like this: in the real world, "car" is a kind of machine, or if you prefer, a *class* of machine. But you can't just get into the abstract class of "car" and drive to the shops, you need an actual, concrete, physical car: an *instance* of the class. In object oriented programming ("OOP"), this is normally the same: you create an instance of the class, and then work with that. The instance gets its behaviour (and sometimes its data) from the class. The examples above are classes with behaviour only, no data or state. They never change. That's not very useful. Normally you want to store data in the class instance, sometimes in the class itself. Here's an example: class Paper: colour = "white" size = "A4" This defines a class with no behaviour, only state. In this case, it has two attributes, colour and size. The values stored in the class are global defaults: all Paper instances share the same value. But you can give individual instances their own independent value by assignment: >>> sheet = Paper() >>> sheet.colour 'white' >>> >>> another_sheet = Paper() >>> another_sheet.size = "A5" # cut the paper in half >>> another_sheet.colour = "green" # and paint it >>> another_sheet.colour # check that the change is stored 'green' >>> >>> sheet.colour # and check that the other sheet is unchanged 'white' Normally though, you don't need or want to set default state that applies to all instances. In the above Paper example, it is harmless, but sometimes it can lead to bugs, so be careful with class attributes. So although attributes common to all instances of a class can sometimes be useful, generally people try to avoid them, and it is more common to put off defining the instance's attributes until the instance is created. For that, Python has a special method called "__init__" (that's two underscores at the front and back). When you create an instance by calling Paper(), the __init__ method (if any) is automatically called by Python. class Paper: def __init__(self, colour="white", size="A4"): self.colour = colour self.size = size Now the attributes no longer live inside the class, but inside the instance. Paper instances no longer share global state. Each instance gets its own independent attribute for colour and size, which you can specify when you create it: >>> sheet = Paper("blue", "Foolscap") >>> sheet.colour 'blue' Now, I've skimmed over a couple of important things here. Firstly, syntax: in Python, the syntax for attribute access is with a dot: paper.size lets you retrieve the attribute. To set the attribute, you simply assign to it: paper.size = "A3" Notice that dot is the same syntax used for accessing methods: whistler.draw() That's because in Python, methods are just another attribute, only you can call them with () syntax. This lets you do all sorts of cool and advanced things, like store a method somewhere to use it later: import random if random.random() < 0.5: method = wyatt_earp.draw # no parentheses! else: method = whistler.draw # later... method() # call the method but I digress. The other thing I glossed over was the mysterious "self" parameter in the method definitions. Remember, methods are defined inside the class, not inside the instance. When you call a method, how does the class know which instance it should look at? The answer is, Python does some sleight of hand in the background, changing what you write: whistler.draw() into what actually gets executed: Artist.draw(whistler) That's moderately advanced though, you don't need to care about it, *except* that you have to remember to declare a parameter in all your methods to hold that auto-magic instance argument. Conventionally, we call it "self", but you can call it anything you like. (You can, but you shouldn't.) Forgetting to declare "self" in your methods is one of the more common source of bugs. That's pretty much all you need to know to start using objects. There's a lot more though: inheritance, class methods and static methods (as opposed to ordinary methods), properties, descriptors (advanced!), slots, and more. But one step at a time. Any questions, don't hesitate to ask! -- Steven D'Aprano From mehgcap at gmail.com Sat May 21 13:59:15 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 21 May 2011 07:59:15 -0400 Subject: [Tutor] Help with understanding classes In-Reply-To: References: Message-ID: On 5/21/11, Robert Sj?blom wrote: > I'm trying to wrap my head around classes and their attributes, but am > having a hard time doing so. The websites and books that I have consulted > haven't been much help; most of them assume prior programming/oop > experience, something I lack. > > From what I understand it's a "blueprint", so each time you instantiate it > you run whatever's in the __self__ part is assigned to the instance. What > I'm wondering is how to access and change attributes in the instance > (whatever it might be; a list, a specific value, a string...). Say we have an animal class: #open a new class class animal: #make the __init__, which is automatically called when a new instance of the class #is created; put initial setup things here def __init__(self, nameString): #"nameString" is assigned to this class's "name" variable self.name=nameString #this function, since it is in the class, can be called on an instance of the class def printName(self): print self.name #make an animal whose name is Fluffy: myDog=animal("Fluffy") #call the animal class's method on this instance myDog.printName() #Fluffy #now change the name: myDog.name="Rover" #call the same method on the same instance: myDog.printName() #Rover > > I just can't seem to grasp the concept or syntax very well, and none of the > sources I've found go to great lengths explaining them to someone as > thick-headed as me. So if anyone could take the time to explain, or point me > to sources to read, I'd be grateful The above is not too in-depth, but I am also not quite sure which parts of syntax or concepts you are stuck on. In the above example, what, specifically, does not make sense? > > Thanks in advance, and best regards, > Robert S. > Sent from my iPhone > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Sat May 21 19:19:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 May 2011 18:19:12 +0100 Subject: [Tutor] Help with understanding classes References: Message-ID: "Robert Sj?blom" wrote > I'm trying to wrap my head around classes ...The websites > and books that I have consulted ...assume prior > programming/oop experience, something I lack. Alex, and especially Steven (great job BTW!,) have given you good explanations, provided you understand the basics of programming. However, in your post, you suggest you don't have prior *programming* experience? If that's the case, forget about OOP and classes for now and go learn how to write basic code up to the point where you are comfortable defining and using your own functions. Then come back to classes and OOP and it will all make a lot more sense. OTOH If you can already create and use functions then Alex and Steven's explanations should be useful and if you still have specific questions feel free to post them here. You can also try my OOP tutorial topic, but it does assume basic familiarity with creating functions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bermanrl at cfl.rr.com Sat May 21 22:22:05 2011 From: bermanrl at cfl.rr.com (RL Berman) Date: Sat, 21 May 2011 16:22:05 -0400 Subject: [Tutor] Help with understanding classes In-Reply-To: <201105212149.27820.steve@pearwood.info> References: <201105212149.27820.steve@pearwood.info> Message-ID: <4DD81EED.3010909@cfl.rr.com> What a phenomenally clear explanation. Thank you very much, Steven. Robert Berman On 05/21/2011 07:49 AM, Steven D'Aprano wrote: > On Sat, 21 May 2011 08:24:34 pm Robert Sj?blom wrote: >> I'm trying to wrap my head around classes and their attributes, but >> am having a hard time doing so. The websites and books that I have >> consulted haven't been much help; most of them assume prior >> programming/oop experience, something I lack. > Let's start with a simple question -- what is an object? In programming, > an object is a thing that combines data and behaviour together in one > handy package. Back in the Dark Ages *wink*, code and behaviour were > always separate, so you would have to design a data structure in one > place of your program, then write functions to manipulate it somewhere > else. If you had two different data structures which needed similar > actions, you had to jump through hoops to keep the functions for one > separate from the functions of the other. > > But objects let you keep related pieces of code together, so they don't > get in the way of unrelated code with the same name: > > class Artist: > def draw(self): > print("I splashed paint on the canvas until it looked like" > " my mother on a rocking horse.") > > class GunSlinger: > def draw(self): > print("The stranger reached for his gun, but I was too" > " quick for him and plugged him full of lead.") > > > The function (actually "method") called draw for Artists doesn't get > over-ridden by the method with the same name for GunSlingers: > > >>>> whistler = Artist() >>>> wyatt_earp = GunSlinger() >>>> whistler.draw() > I splashed paint on the canvas until it looked like my mother on a > rocking horse. >>>> wyatt_earp.draw() > The stranger reached for his gun, but I was too quick for him and > plugged him full of lead. > > > Here you see object code in action. You start with a class, which is > something vaguely like a template. (It's actually nothing like a > template, but that will do for now.) Before you can use the class, you > normally have to instantiate it. > > Think of it like this: in the real world, "car" is a kind of machine, or > if you prefer, a *class* of machine. But you can't just get into the > abstract class of "car" and drive to the shops, you need an actual, > concrete, physical car: an *instance* of the class. In object oriented > programming ("OOP"), this is normally the same: you create an instance > of the class, and then work with that. The instance gets its behaviour > (and sometimes its data) from the class. > > The examples above are classes with behaviour only, no data or state. > They never change. That's not very useful. Normally you want to store > data in the class instance, sometimes in the class itself. Here's an > example: > > class Paper: > colour = "white" > size = "A4" > > This defines a class with no behaviour, only state. In this case, it has > two attributes, colour and size. The values stored in the class are > global defaults: all Paper instances share the same value. But you can > give individual instances their own independent value by assignment: > >>>> sheet = Paper() >>>> sheet.colour > 'white' >>>> another_sheet = Paper() >>>> another_sheet.size = "A5" # cut the paper in half >>>> another_sheet.colour = "green" # and paint it >>>> another_sheet.colour # check that the change is stored > 'green' >>>> sheet.colour # and check that the other sheet is unchanged > 'white' > > > Normally though, you don't need or want to set default state that > applies to all instances. In the above Paper example, it is harmless, > but sometimes it can lead to bugs, so be careful with class attributes. > > So although attributes common to all instances of a class can sometimes > be useful, generally people try to avoid them, and it is more common to > put off defining the instance's attributes until the instance is > created. For that, Python has a special method called "__init__" > (that's two underscores at the front and back). When you create an > instance by calling Paper(), the __init__ method (if any) is > automatically called by Python. > > class Paper: > def __init__(self, colour="white", size="A4"): > self.colour = colour > self.size = size > > Now the attributes no longer live inside the class, but inside the > instance. Paper instances no longer share global state. Each instance > gets its own independent attribute for colour and size, which you can > specify when you create it: > >>>> sheet = Paper("blue", "Foolscap") >>>> sheet.colour > 'blue' > > > Now, I've skimmed over a couple of important things here. Firstly, > syntax: in Python, the syntax for attribute access is with a dot: > > paper.size > > lets you retrieve the attribute. To set the attribute, you simply assign > to it: > > paper.size = "A3" > > Notice that dot is the same syntax used for accessing methods: > > whistler.draw() > > That's because in Python, methods are just another attribute, only you > can call them with () syntax. This lets you do all sorts of cool and > advanced things, like store a method somewhere to use it later: > > import random > if random.random()< 0.5: > method = wyatt_earp.draw # no parentheses! > else: > method = whistler.draw > > # later... > method() # call the method > > but I digress. > > The other thing I glossed over was the mysterious "self" parameter in > the method definitions. Remember, methods are defined inside the class, > not inside the instance. When you call a method, how does the class > know which instance it should look at? The answer is, Python does some > sleight of hand in the background, changing what you write: > > whistler.draw() > > into what actually gets executed: > > Artist.draw(whistler) > > That's moderately advanced though, you don't need to care about it, > *except* that you have to remember to declare a parameter in all your > methods to hold that auto-magic instance argument. Conventionally, we > call it "self", but you can call it anything you like. (You can, but > you shouldn't.) Forgetting to declare "self" in your methods is one of > the more common source of bugs. > > > That's pretty much all you need to know to start using objects. There's > a lot more though: inheritance, class methods and static methods (as > opposed to ordinary methods), properties, descriptors (advanced!), > slots, and more. But one step at a time. > > Any questions, don't hesitate to ask! > > > From evosweet at hotmail.com Sun May 22 13:51:44 2011 From: evosweet at hotmail.com (Rayon) Date: Sun, 22 May 2011 07:51:44 -0400 Subject: [Tutor] need help with lxml errors Message-ID: I am trying to import lxml from lxml import etree bb = etree.Element(self.get_time) return str(bb) and I get this error: File "C:\Python26\lib\site-packages\lxml\apihelpers.pxi", line 1480, in lxml.etree.__getNsTag (src/lxml/lxml.etree.c:23373) File "C:\Python26\lib\site-packages\lxml\apihelpers.pxi", line 1364, in lxml.etree._utf8 (src/lxml/lxml.etree.c:22190) TypeError: Argument must be bytes or unicode, got 'instancemethod' Regards Rayon -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun May 22 14:22:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 22 May 2011 22:22:49 +1000 Subject: [Tutor] need help with lxml errors In-Reply-To: References: Message-ID: <201105222222.49628.steve@pearwood.info> On Sun, 22 May 2011 09:51:44 pm Rayon wrote: > I am trying to import lxml > > from lxml import etree And that succeeds fine. Your problem lies elsewhere. > bb = etree.Element(self.get_time) > return str(bb) In future, please copy and paste (do NOT retype, simplify or summarize) the full traceback you get, not just the error message. In this case, I *think* I can *guess* your error, based on the error message alone, but I could be completely off-base. But my guess is that you need: bb = etree.Element(self.get_time()) rather than: bb = etree.Element(self.get_time) The later tries to insert a method get_time into the element tree. You need to call the method by putting brackets () after it. -- Steven D'Aprano From evosweet at hotmail.com Sun May 22 14:48:13 2011 From: evosweet at hotmail.com (Rayon) Date: Sun, 22 May 2011 08:48:13 -0400 Subject: [Tutor] need help with lxml errors In-Reply-To: <201105222222.49628.steve@pearwood.info> References: <201105222222.49628.steve@pearwood.info> Message-ID: Wow I did not see that, long day and night :) thanks a lot. Regards Rayon -----Original Message----- From: tutor-bounces+evosweet=hotmail.com at python.org [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of Steven D'Aprano Sent: Sunday, May 22, 2011 8:23 AM To: tutor at python.org Subject: Re: [Tutor] need help with lxml errors On Sun, 22 May 2011 09:51:44 pm Rayon wrote: > I am trying to import lxml > > from lxml import etree And that succeeds fine. Your problem lies elsewhere. > bb = etree.Element(self.get_time) > return str(bb) In future, please copy and paste (do NOT retype, simplify or summarize) the full traceback you get, not just the error message. In this case, I *think* I can *guess* your error, based on the error message alone, but I could be completely off-base. But my guess is that you need: bb = etree.Element(self.get_time()) rather than: bb = etree.Element(self.get_time) The later tries to insert a method get_time into the element tree. You need to call the method by putting brackets () after it. -- Steven D'Aprano _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From lowelltackett at yahoo.com Sun May 22 18:04:26 2011 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Sun, 22 May 2011 09:04:26 -0700 (PDT) Subject: [Tutor] Help with understanding classes Message-ID: <598573.62347.qm@web110115.mail.gq1.yahoo.com> Robert...I am similarly where you are stuck, a beginner with little insight, so my perspective might have some draw to it. Try this on for size - while watching a friend stencil Christmas decorations on living room windows last year, it dawned on me that a class is quite simply - a stencil. While using a "Santa Claus" stencil, I watched my friend employ different features in different places; a Santa Claus here, some reindeer there, a few pine bows in another spot, and each with different colored spray paint...and the light bulb came on. Each different "thing" she stenciled was an "instance" of the class (stencil) "Santa Claus". For me, that was the magic moment. Very unprofessional, I'm sure, but, hey, so what?! >From the virtual desk of Lowell Tackett? --- On Sat, 5/21/11, Robert Sj?blom wrote: From: Robert Sj?blom Subject: [Tutor] Help with understanding classes To: "tutor at python.org" Date: Saturday, May 21, 2011, 6:24 AM I'm trying to wrap my head around classes and their attributes, but am having a hard time doing so. The websites and books that I have consulted haven't been much help; most of them assume prior programming/oop experience, something I lack. >From what I understand it's a "blueprint", so each time you instantiate it you run whatever's in the __self__ part is assigned to the instance. What I'm wondering is how to access and change attributes in the instance (whatever it might be; a list, a specific value, a string...). I just can't seem to grasp the concept or syntax very well, and none of the sources I've found go to great lengths explaining them to someone as thick-headed as me. So if anyone could take the time to explain, or point me to sources to read, I'd be grateful Thanks in advance, and best regards, Robert S. Sent from my iPhone _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From jigenbakuda at yahoo.com Sun May 22 20:09:39 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Sun, 22 May 2011 11:09:39 -0700 (PDT) Subject: [Tutor] Python and the web Message-ID: <680185.59365.qm@web130203.mail.mud.yahoo.com> I want to start getting into web site development. I already know basic html and css, which will create a basic webpage. But my question is what exactly does python bring to the web? Are forums, blogs, flash sites, etc the results of web programming or can they all be achieved with standard html / css? What exactly can I do differently with python than with html and css? Or should I say, how can I use python WITH html and css to create something better? ---- What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun May 22 21:05:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 May 2011 20:05:36 +0100 Subject: [Tutor] Python and the web References: <680185.59365.qm@web130203.mail.mud.yahoo.com> Message-ID: "michael scott" wrote >I want to start getting into web site development. I already > know basic html and css, which will create a basic webpage. > But my question is what exactly does python bring to the web? Action. Your HTML/CSS web page cannot do anything it is just static information. Using JavaScript you can make the brower do a few things like pop up dialog boxes and so on but thats about it. You use Python at the web server end to generate html pages and those pages will be based on dynamic things like database content or information retrieved from other web pages. So, for example of the lead news story in the NY Times is about events in Mexico, your web page might display the Mexican flag as an Icon, but if the headline is about Greece it shows the Greek flag, - and if its about a Hollywood starlet it shows a yawning dog... You need a dynamic programming language to do the lookup and then draw the right image on the page. Thats a simple example, but of course you can do much more sophisticated things too - like create a web shop like Amazon, or an Auction site like eBay or a search engine like google.. > Are forums, blogs, flash sites, etc the results of > web programming or can they all be achieved with > standard html / css? They all need programming althoufgh some of them can be downloaded or bought as packages where the programming has been done for you. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From spawgi at gmail.com Sun May 22 21:41:11 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Mon, 23 May 2011 01:11:11 +0530 Subject: [Tutor] Python and the web In-Reply-To: <680185.59365.qm@web130203.mail.mud.yahoo.com> References: <680185.59365.qm@web130203.mail.mud.yahoo.com> Message-ID: Please see the Django framework and Google App Engine using Python. I particularly recommend the GAE using Python to create a basic data driven application. It will give answers to quite a few of your questions. Regards SWP On Sun, May 22, 2011 at 11:39 PM, michael scott wrote: > I want to start getting into web site development. I already know basic > html and css, which will create a basic webpage. But my question is what > exactly does python bring to the web? > > Are forums, blogs, flash sites, etc the results of web programming or can > they all be achieved with standard html / css? What exactly can I do > differently with python than with html and css? Or should I say, how can I > use python WITH html and css to create something better? > > > > ---- > What is it about you... that intrigues me so? > > > _______________________________________________ > 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 tidal.espeon at gmail.com Sun May 22 22:29:07 2011 From: tidal.espeon at gmail.com (Tidal Espeon) Date: Sun, 22 May 2011 16:29:07 -0400 Subject: [Tutor] Some ways lists and dictionaries can be used unconventionally? Message-ID: I've been trying to make a text-based character creator program, and it was going pretty well. I was debugging it earlier, and I was well on my way. The problem is, that its something I have to do at the end of a python book's chapter about learning lists and dictionaries, and I didn't use either in my code. I've been trying to think of how lists and dictionaries can be useful (or even significantly relevant. storing a bunch of variables just shortens the code by a few lines), but I fail to see any significant connection. (honestly, i don't get a key-value pair make this sort of program easier to make.) :/ Since the book told me to do it, I know there must be something. I'd like to be taught some uses of dictionaries besides using it as a semi-literal dictionary, and uses of lists besides being conveniently changeable tuples. I think I can figure it out myself afterwards. Please and thank you! :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From ladymcse2000 at gmail.com Sun May 22 23:11:56 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Sun, 22 May 2011 14:11:56 -0700 Subject: [Tutor] Question about comparing values Message-ID: I realize this is a fairly generic type of question, but being new to programming, I'm not sure how best to approach it. I'm doing a tutorial and was given a problem, using shelve. It's taking a user name and then asking for scores in a game, until you end the loop. Whatever score is the high score, should be returned from the function: Here is what I have so far: import shelve def user_scores(): user_name = input ("What is the user name?").rstrip() scores = int(input("What is the users score, enter 0 if done")) shelf = shelve.open('scores.py', writeback=True) score = [scores] user = {user_name:score} shelf['user'] = user shelf.close() while scores > 0: scores = int (input("What is the next score")) shelf = shelve.open('scores.py', writeback=True) score.append(scores) shelf['score'] = score shelf.sync() shelf.close() What I'm not sure of is how to compare the values of score, to find and print the one that is highest. Any suggestions? Becky -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun May 22 23:21:53 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 22 May 2011 23:21:53 +0200 Subject: [Tutor] Question about comparing values In-Reply-To: References: Message-ID: On Sun, May 22, 2011 at 11:11 PM, Becky Mcquilling wrote: > I realize this is a fairly generic type of question, but being new to > programming, I'm not sure how best to approach it. > I'm doing a tutorial and was given a problem, using shelve. ?It's taking a > user name and then asking for scores in a game, until you end the loop. > ?Whatever score is the high score, should be returned from the function: > Here is what I have so far: > import shelve > def user_scores(): > ? user_name = input ("What is the user name?").rstrip() > ? scores = int(input("What is the users score, enter 0 if done")) > ? shelf = shelve.open('scores.py', writeback=True) > ? score = [scores] > ? user = {user_name:score} > ? shelf['user'] = user > ? shelf.close() > ? while scores > 0: > ? ? scores = int (input("What is the next score")) > ? ? shelf = shelve.open('scores.py', writeback=True) > ? ? score.append(scores) > ? ? shelf['score'] = score > ? ? shelf.sync() > ? ? shelf.close() > What I'm not sure of is how to compare the values of score, to find and > print the one that is highest. ?Any suggestions? > Becky > > Look up the function called max(). I think that should take care of what you need. Hugo From robert.sjoblom at gmail.com Mon May 23 00:19:07 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 23 May 2011 00:19:07 +0200 Subject: [Tutor] Help with understanding classes Message-ID: > That's pretty much all you need to know to start using objects. There's > a lot more though: inheritance, class methods and static methods (as > opposed to ordinary methods), properties, descriptors (advanced!), > slots, and more. But one step at a time. > > Any questions, don't hesitate to ask! Wow, amazing explanations! > However, in your post, you suggest you don't have prior > *programming* experience? My bad; I meant prior programming experience outside Python (which consists of some BASIC from, oh, 20 years ago). Anyway, with the explanations I'm slowly getting my head around it all. I'm sure I'll be back with more questions as soon as I can formulate them. My biggest problem, which everyone (except this list) skimmed over was the __init__ and self parts. Now that I've had those explained to me, it's starting to make sense. Thanks to everyone, again. best regards, Robert S. From wprins at gmail.com Mon May 23 01:08:18 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 23 May 2011 00:08:18 +0100 Subject: [Tutor] Some ways lists and dictionaries can be used unconventionally? In-Reply-To: References: Message-ID: On 22 May 2011 21:29, Tidal Espeon wrote: > I've been trying to make a text-based character creator program, and it was > going pretty well. I was debugging it earlier, and I was well on my way. The > problem is, that its something I have to do at the end of a python book's > chapter about learning lists and dictionaries, and I didn't use either in my > code. > > I've been trying to think of how lists and dictionaries can be useful (or > even significantly relevant. storing a bunch of variables just shortens the > code by a few lines), but I fail to see any significant connection. > (honestly, i don't get a key-value pair make this sort of program easier to > make.) :/ > > Since the book told me to do it, I know there must be something. I'd like > to be taught some uses of dictionaries besides using it as a semi-literal > dictionary, and uses of lists besides being conveniently changeable tuples. > I think I can figure it out myself afterwards. > > Please and thank you! :) Which book are you using and what does the excercise say to do exactly? Regardless, I'm curious about how you're storing your character information presently. Suppose you had to store an arbitrary number of characters (assuming your'e currently basically dealing with one single character's attributes only), would your existing data structure still work well for you? Regarding lists and dicts -- It often happens in programming that you need to store lists of things (where the number of things are not neccesarily known in advance or fixed) or be able to find things based on some identifying attribute. Lists and dicts are (some of) the Python language supplied ingredients for you to be able to do this easily and efficiently. Don't know if that's enough to help clarify things or not. HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon May 23 01:44:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 May 2011 00:44:55 +0100 Subject: [Tutor] Some ways lists and dictionaries can be usedunconventionally? References: Message-ID: "Tidal Espeon" wrote > I've been trying to make a text-based character creator program, > ...chapter about learning lists and dictionaries, ... > I've been trying to think of how lists and dictionaries > can be useful ... but I fail to see any significant connection. OK, Assuming your characters attributes have names, would it be useful to have all the attributes of your character accessible by looking up their name? As the value part of a dictionary say? And since you have a bunch of characters to manage wouldn't it be useful to have them stored in a collection, maybe a list say? Or even a dictionary where the key is the characters name? So we wind up with a dictionary full of characters, each of which is a dictionary of attributes. Then we can do things like: characters["Tidal"]["strength"] = 45 print characters["Alan"]["Weapons"] Which is probably easier to read than using fixed variables like player1_strength and player1_name which is pretty much what you would need to do without a dictionary or list. Does that help? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon May 23 01:57:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 May 2011 00:57:45 +0100 Subject: [Tutor] Question about comparing values References: Message-ID: "Becky Mcquilling" wrote > I'm doing a tutorial and was given a problem, using shelve. Remember that a shelve is basically a dictionary stored in a file rather than in memory. So treat it like you would a dictionary. > Here is what I have so far: > > import shelve > > def user_scores(): > user_name = input ("What is the user name?").rstrip() > scores = int(input("What is the users score, enter 0 if done")) > shelf = shelve.open('scores.py', writeback=True) > score = [scores] I've no idea what you think this is doing? Its actually creating a single valued list and assigning that to score. Is that what you intended? If so why? > user = {user_name:score} > shelf['user'] = user This is storing a single dictionary under the key 'user'. Wouldn't it be easier to store the score under the key user_name? That way you could store more than one value. As it is you can only ever have a single entry for 'user' in your shelf. > shelf.close() > while scores > 0: > scores = int (input("What is the next score")) > shelf = shelve.open('scores.py', writeback=True) > score.append(scores) OK, so now you append more scores to the liist, but I still don't get why you need a list? > shelf['score'] = score And now you add a new entry under 'score' which is the list of scores. > shelf.sync() > shelf.close() So at the end you haven't read anything from your shelf but you have written two entries, one with a dictionary of name and list. The other with a list of scores where the first value happens to be the same as the one stored under 'user' And in memory you still have that raw data, at least until you exit the function... > What I'm not sure of is how to compare the values > of score, to find and print the one that is highest. I think you have far bigger problems to solve than that! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon May 23 02:16:19 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 23 May 2011 10:16:19 +1000 Subject: [Tutor] Python and the web In-Reply-To: <680185.59365.qm@web130203.mail.mud.yahoo.com> References: <680185.59365.qm@web130203.mail.mud.yahoo.com> Message-ID: <201105231016.19421.steve@pearwood.info> On Mon, 23 May 2011 04:09:39 am michael scott wrote: > I want to start getting into web site development. I already know > basic html and css, which will create a basic webpage. But my > question is what exactly does python bring to the web? > > Are forums, blogs, flash sites, etc the results of web programming or > can they all be achieved with standard html / css? What exactly can I > do differently with python than with html and css? Or should I say, > how can I use python WITH html and css to create something better? Consider the difference between going to your local hardware store and buying lumber, nails and a nailgun, then building the framework of your house, versus going out into a forest and cutting down the trees yourself, digging up the iron ore to make the nails, and banging them in to the timber with a rock. That's the difference between using a web framework, versus doing everything in pure HTML and CSS. Whether the framework is written in Python, Ruby, or some other language is incidental. If your site stores any sort of user-generated information (forum posts, comments, etc) you need to store it in some sort of database, securely, without giving random passers-by on the Internet unrestricted access to the server hosting your site. A framework will handle this for you. As for "flash sites", by definition they must be written in Flash, otherwise they wouldn't be *Flash* sites, would they? But please don't inflict another of those abominations on the world. -- Steven D'Aprano From sigzero at gmail.com Mon May 23 04:35:45 2011 From: sigzero at gmail.com (Robert) Date: Sun, 22 May 2011 22:35:45 -0400 Subject: [Tutor] Python and the web References: <680185.59365.qm@web130203.mail.mud.yahoo.com> Message-ID: On 2011-05-22 14:09:39 -0400, michael scott said: > I want to start getting into web site development. I already know basic > html and css, which will create a basic webpage. But my question is > what exactly does python bring to the web? > > Are forums, blogs, flash sites, etc the results of web programming or > can they all be achieved with standard html / css? What exactly can I > do differently with python than with html and css? Or should I say, how > can I use python WITH html and css to create something better? > You might be interested in this if you are going the Python3 route: Python 3 Web Development Beginner's Guide [Paperback] I am not affiliated with the book at all...just saw it today. -- Robert From ladymcse2000 at gmail.com Mon May 23 06:13:37 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Sun, 22 May 2011 21:13:37 -0700 Subject: [Tutor] Question about comparing values In-Reply-To: References: Message-ID: Thanks, you are correct of course. I need to just scrap this and start over, but I understand it a lot better now. On Sun, May 22, 2011 at 4:57 PM, Alan Gauld wrote: > "Becky Mcquilling" wrote > > I'm doing a tutorial and was given a problem, using shelve. >> > > Remember that a shelve is basically a dictionary stored > in a file rather than in memory. So treat it like you would > a dictionary. > > > Here is what I have so far: >> >> import shelve >> >> def user_scores(): >> user_name = input ("What is the user name?").rstrip() >> scores = int(input("What is the users score, enter 0 if done")) >> shelf = shelve.open('scores.py', writeback=True) >> score = [scores] >> > > I've no idea what you think this is doing? > Its actually creating a single valued list and assigning that to score. > Is that what you intended? If so why? > > > user = {user_name:score} >> shelf['user'] = user >> > > This is storing a single dictionary under the key 'user'. > Wouldn't it be easier to store the score under > the key user_name? That way you could store > more than one value. As it is you can only ever > have a single entry for 'user' in your shelf. > > > > shelf.close() >> while scores > 0: >> scores = int (input("What is the next score")) >> shelf = shelve.open('scores.py', writeback=True) >> score.append(scores) >> > > OK, so now you append more scores to the liist, > but I still don't get why you need a list? > > shelf['score'] = score >> > > And now you add a new entry under 'score' which is the > list of scores. > > shelf.sync() >> shelf.close() >> > > So at the end you haven't read anything from your shelf > but you have written two entries, one with a dictionary > of name and list. The other with a list of scores where > the first value happens to be the same as the one stored > under 'user' > > And in memory you still have that raw data, at least > until you exit the function... > > > What I'm not sure of is how to compare the values >> of score, to find and print the one that is highest. >> > > I think you have far bigger problems to solve than that! > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at gmail.com Mon May 23 19:14:54 2011 From: denis.spir at gmail.com (spir) Date: Mon, 23 May 2011 19:14:54 +0200 Subject: [Tutor] module/package search Message-ID: <4DDA960E.8040201@gmail.com> Hello, I'm developing a package. I need user/test/special modules (inside or outside the package) to import given modules from the package, or the whole package or a sub-package. I'm looking for a general solution for this. For an importing module located inside the package, the obvious solution is to use a relative import. But this does not work (for what reason?) if the importer is not itself imported as element of the package (error: "relative import attempted in non package", or such). Even if it's indeed inside the package, in a dir with an __init__.py. I've found some posts on this bug, but no reason stated, and no solution. For instance, a test module part of a package cannot import what it is intended to test... Same thing for a module that holds its own test suite (and thus indeed needs to be run stand- alone). Note that the package's dir and every subdir hold __init__.py pseudo-modules. Is there a solution I'm overlooking to use relative imports? Now, for using absolute imports, IIUC the package's dir must be on python's package search path list, meaning sys.path, is that all? I tried to extend sys.path using * PYTHONPATH * a custom spir.pth (placed inside /usr/lib/pythonX.Y on Linux) Both methods fail by me: sys.path still does not hold the package's dir, thus absolute imports fail (error: "no module called..."). One more question: in both cases above, I added *both* the package's proper dir, and the dir above it, eg both /home/me/prog/python & /home/me/prog/python/packname. What's the right one? (the package's top __init__.py is in /home/me/prog/python/packname) In any case, if I manage to add /home/me/prog/python to sys.path, will all packages (each located in a sub-dir from there) be found? Or do I need to add one path per package, even if they're all grouped in a super-dir? Denis -- _________________ vita es estrany spir.wikidot.com From s.charonis at gmail.com Mon May 23 22:53:30 2011 From: s.charonis at gmail.com (Spyros Charonis) Date: Mon, 23 May 2011 21:53:30 +0100 Subject: [Tutor] Logical Structure of Snippet Message-ID: Hello List, I'm trying to read some sequence files and modify them to a particular format. These files are structured something like: >P1; ICA1_HUMAN AAEVDTG..... (A very long sequence of letters) >P1;ICA1_BOVIN TRETG....(A very long sequence of letters) >P1;ICA2_HUMAN WKH.....(another sequence) I read a database file which has information that I need to modify my sequence files. I must extract one of the data fields from the database (done this) and place it in the sequence file (structure shown above). The relevant database fields go like: tt; ICA1_HUMAN Description tt; ICA1_BOVIN Description tt; ICA2_HUMAN Description What I would like is to extract the tt; fields (I already have code for that) and then to read through the sequence file and insert the TT field corresponding to the >P1 header right underneath the >P1 header. Basically, I need a newline everytime >P1 occurs in the sequence file and I need to paste its corresponding TT field in that newline (for P1; ICA1_HUMAN,that would be ICA1_HUMAN Description, etc). the pseudocode would go like this: for line sequence file: if line.startswith('>P1; ICA ....) make a newline go to list with extracted tt; fields* find the one with the same query (tt; ICA1 ...)* insert this field in the newline The steps marked * are the ones I am not sure how to implement. What logical structure would I need to make Python match a tt; field (I already have the list of entries) whenever it finds a header with the same content? Apologies for the verbosity, but I did want to be clear as it is quite specific. S. -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.miesner at gmail.com Mon May 23 16:26:09 2011 From: michael.miesner at gmail.com (michael.miesner at gmail.com) Date: Mon, 23 May 2011 09:26:09 -0500 Subject: [Tutor] how are you? Message-ID: <4dda6e81.047d0e0a.0aa7.ffffd819@mx.google.com> hello its insane how different my life is now http://careersindemand.com/redirect.php?to=aHR0cDovL3d3dy5jbmJjNy5jb20vP3BpZD0yOTcwODY= From alan.gauld at btinternet.com Tue May 24 01:54:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 May 2011 00:54:57 +0100 Subject: [Tutor] Logical Structure of Snippet References: Message-ID: "Spyros Charonis" wrote >>P1; ICA1_HUMAN > AAEVDTG..... (A very long sequence of letters) > > I must extract one of the data fields from the database (done this) > and place it in the sequence file (structure shown above). The > relevant > database fields go like: > > tt; ICA1_HUMAN Description > tt; ICA1_BOVIN Description > tt; ICA2_HUMAN Description > > What I would like is to extract the tt; fields (I already have code > for > that) and then to read through the sequence file and insert the > TT field corresponding to the >P1 header right underneath > the >P1 header. Basically, I need a newline everytime >P1 > occurs in the sequence file and I need to paste > its corresponding TT field in that newline > the pseudocode would go like this: modified to: for line sequence file: insert line if line.startswith('>P1; ICA ....) go to list with extracted tt; fields* find the one with the same query (tt; ICA1 ...)* insert this field as a newline > The steps marked * are the ones I am not sure how to implement. What > logical structure would I need to make Python match a tt; field What about a dictionary keyed by field type? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue May 24 01:56:54 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 24 May 2011 09:56:54 +1000 Subject: [Tutor] Logical Structure of Snippet In-Reply-To: References: Message-ID: <201105240956.54819.steve@pearwood.info> On Tue, 24 May 2011 06:53:30 am Spyros Charonis wrote: > Hello List, > > I'm trying to read some sequence files and modify them to a > particular [...] You should almost never modify files in place, especially if you need to insert text. It *might*, sometimes, be acceptable to modify files in place if you are just over-writing what is already there, but absolutely not if you have to insert text! The problem is that file systems don't support insert. They support shrinking files, adding to the end, and overwriting in place. To insert, you have to do a LOT more work, which is slow, fragile and risky: if something goes bad, you end up with a corrupted file. It is almost always better to read the file into memory, process it, then write the output back out to the file. You ask: > for line sequence file: > if line.startswith('>P1; ICA ....) > make a newline > go to list with extracted tt; fields* > find the one with the same query (tt; ICA1 ...)* > insert this field in the newline This is better to become some variation of: infile = open('sequence file', 'r') outfile = open('processed file', 'w') for line in infile: outfile.write(line) if line.startswith('>P1; ICA'): new_line = ... #### what to do here??? outfile.write(new_info) outfile.close() infile.close() The problem then becomes, how to calculate the new_line above. Break that into steps: you have a line that looks like ">P1; ICA1_HUMAN" and you want to extract the ICA... part. def extract_ica(line): line = line.strip() if not line.startswith('>P1;'): raise ValueError('not a >P1 line') p = line.index(';') s = line[p+1:] s = s.strip() if s.startswith('ICA'): return s else: raise ValueError('no ICA... field in line') Meanwhile, you have a dict (not a list, a dictionary) that looks like this: descriptions = { 'ICA1_BOVINE': description, 'ICA1_HUMAN': description, ...} If you need help assembling this dict, just ask. With a dict, searches are easy. Making the new line takes three short lines of code: key = extract_ica(line) descr = descriptions[key] new_line = 'tt; ' + key + ' ' + desc -- Steven D'Aprano From zebra05 at gmail.com Tue May 24 11:59:23 2011 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Tue, 24 May 2011 11:59:23 +0200 Subject: [Tutor] Parsing an XML document using ElementTree Message-ID: Hi Everyone, I am trying to parse an XML feed and display the text of each child node without any success. My code in the python shell is as follows: >>>import urllib >>>from xml.etree import ElementTree as ET >>>content = urllib.urlopen(' http://xml.matchbook.com/xmlfeed/feed?sport-id=&vendor=TEST&sport-name=&short-name=Po ') >>>xml_content = ET.parse(content) I then check the xml_content object as follows: >>>xml_content And now, to iterate through its child nodes and print out the text of each node: >>>for node in xml_content.getiterator('contest'): ... name = node.attrib.get('text') ... print name ... >>> Nothing is printed, even though the document does have 'contest' tags with text in them. If I try to count the contest tags and increment an integer (to see that the document is traversed) I get the same result - the int remains at 0. >>> i = 0 >>> for node in xml_content.getiterator('contest'): ... i += 1 ... >>> i 0 What am I getting wrong? Any hints would be appreciated. -- Regards, Sithembewena Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 24 12:20:32 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 May 2011 11:20:32 +0100 Subject: [Tutor] Parsing an XML document using ElementTree References: Message-ID: "Sithembewena Lloyd Dube" wrote > And now, to iterate through its child nodes and print out the text > of each > node: > >>>>for node in xml_content.getiterator('contest'): > ... name = node.attrib.get('text') > ... print name > ... >>>> > > Nothing is printed, > >>>> i = 0 >>>> for node in xml_content.getiterator('contest'): > ... i += 1 > ... >>>> i > 0 > > What am I getting wrong? Any hints would be appreciated. Looks like you are getting an empty list back. Try printing list(xml_content.getiterator('contest')) And if thats empty try checking the case of your tag? I'm pretty sure it will be case sensitive? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From stefan_ml at behnel.de Tue May 24 12:35:55 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 24 May 2011 12:35:55 +0200 Subject: [Tutor] Parsing an XML document using ElementTree In-Reply-To: References: Message-ID: Sithembewena Lloyd Dube, 24.05.2011 11:59: > I am trying to parse an XML feed and display the text of each child node > without any success. My code in the python shell is as follows: > > >>> import urllib > >>> from xml.etree import ElementTree as ET > > >>> content = urllib.urlopen(' > http://xml.matchbook.com/xmlfeed/feed?sport-id=&vendor=TEST&sport-name=&short-name=Po > ') > >>> xml_content = ET.parse(content) > > I then check the xml_content object as follows: > > >>> xml_content > Well, yes, it does return an XML document, but not what you expect: >>> urllib.urlopen('URL see above').read() "\r\n you must add 'accept-encoding' as 'gzip,deflate' to the header of your request\r \n" Meaning, the server forces you to pass an HTTP header to the request in order to receive gzip compressed data. Once you have that, you must decompress it before passing it into ElementTree's parser. See the documentation on the gzip and urllib modules in the standard library. Stefan From hwilkinson at triad.rr.com Tue May 24 15:10:29 2011 From: hwilkinson at triad.rr.com (Hank Wilkinson) Date: Tue, 24 May 2011 09:10:29 -0400 Subject: [Tutor] python scripting using "./" Message-ID: I am trying to do script in python using "./" Here is a session showing "bad interpreter: No such file or directory" Is this a python question/problem? Last login: Sat May 21 14:22:49 on ttys000 John-Wilkinsons-iMac:~ wilkinson$ cd /Users/wilkinson/Documents/py32/p31summerfield John-Wilkinsons-iMac:p31summerfield wilkinson$pwd /Users/wilkinson/Documents/py32/p31summerfield John-Wilkinsons-iMac:p31summerfield wilkinson$ ls hello.py hello.py John-Wilkinsons-iMac:p31summerfield wilkinson$python hello.py Hello World! John-Wilkinsons-iMac:p31summerfield wilkinson$ chmod +X hello.py John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No such file or directory John-Wilkinsons-iMac:p31summerfield wilkinson$ echo $PATH /opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin John-Wilkinsons-iMac:p31summerfield wilkinson$ cat hello.py #!/usr/local/bin/python3.1 print("Hello", "World!") John-Wilkinsons-iMac:p31summerfield wilkinson$python Python 3.1.2 (r312:79147, Mar 20 2011, 17:15:01) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python31.zip', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/plat-darwin', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/lib-dynload', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages'] Thank you. Hank From Steve.Flynn at capita.co.uk Tue May 24 15:20:32 2011 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Tue, 24 May 2011 14:20:32 +0100 Subject: [Tutor] python scripting using "./" In-Reply-To: References: Message-ID: What is your Python executable called? You refer to it as "python" on the command line but your "#!" line in your script refers to the executable as "python3.1". tried it with just "python" in the #! Line? Check the output of 'ls -al /usr/local/bin/pytho*'... S. -----Original Message----- From: tutor-bounces+steve.flynn=capita.co.uk at python.org [mailto:tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of Hank Wilkinson Sent: Tuesday, May 24, 2011 2:10 PM To: tutor at python.org Subject: [Tutor] python scripting using "./" I am trying to do script in python using "./" Here is a session showing "bad interpreter: No such file or directory" Is this a python question/problem? Last login: Sat May 21 14:22:49 on ttys000 John-Wilkinsons-iMac:~ wilkinson$ cd /Users/wilkinson/Documents/py32/p31summerfield John-Wilkinsons-iMac:p31summerfield wilkinson$pwd /Users/wilkinson/Documents/py32/p31summerfield John-Wilkinsons-iMac:p31summerfield wilkinson$ ls hello.py hello.py John-Wilkinsons-iMac:p31summerfield wilkinson$python hello.py Hello World! John-Wilkinsons-iMac:p31summerfield wilkinson$ chmod +X hello.py John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No such file or directory John-Wilkinsons-iMac:p31summerfield wilkinson$ echo $PATH /opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/ bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin John-Wilkinsons-iMac:p31summerfield wilkinson$ cat hello.py #!/usr/local/bin/python3.1 print("Hello", "World!") John-Wilkinsons-iMac:p31summerfield wilkinson$python Python 3.1.2 (r312:79147, Mar 20 2011, 17:15:01) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 1.zip', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 .1', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 .1/plat-darwin', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 .1/lib-dynload', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 .1/site-packages'] Thank you. Hank _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This email has been scanned for all viruses by the MessageLabs SkyScan service. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From wprins at gmail.com Tue May 24 15:27:38 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 24 May 2011 14:27:38 +0100 Subject: [Tutor] python scripting using "./" In-Reply-To: References: Message-ID: The problem likely is as intimated by the error message that your python interpreter not called "/usr/local/bin/python3.1" but I'd offhand guess, probably "/usr/local/bin/python". (Indeed, you run the interpreter yourself as "python" not "python3.1" so you should not be using "python3.1" in your script header.) To check, try: John-Wilkinsons-iMac:~ wilkinson$ which python Assuming you have the "which" command this will tell you which version of python is used then you do e.g. "python hello.py." Then change the hash-bang (#!) header in your script to match the location you found. (If you dont have "which", you can also try "whereis" or "env" or "type -a".) Note, some people use the following hash-bang header in preference of a hard coded path as I've suggested above, as follows: #!/usr/bin/env python /usr/bin/env goes off and looks up the appropriate path for (in this case) the "python" interpreter, then passes control to that, thereby making your script a little less dependent on a hardcoded paths present on your system. This works provided of course that "env" is available and found in /usr/bin. (Thought I'd mention that in case you wanted to use that instead/try it.) Disclaimer: I don't have a Mac, the above is basically general advice which should however work any Unix'ish or GNU'ish system, including I believe on the Mac providing Apple's not changed things that I'm not aware of. Hope that helps Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From hwilkinson at triad.rr.com Tue May 24 15:28:22 2011 From: hwilkinson at triad.rr.com (Hank Wilkinson) Date: Tue, 24 May 2011 09:28:22 -0400 Subject: [Tutor] python scripting using "./" In-Reply-To: References: Message-ID: <69E40D22-E503-4129-A360-39364AAF773A@triad.rr.com> Here is what you asked me: John-Wilkinsons-iMac:p31summerfield wilkinson$ls -al /usr/local/bin/pytho* lrwxr-xr-x 1 root wheel 69 Mar 21 13:45 /usr/local/bin/python3 -> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/python3 lrwxr-xr-x 1 root wheel 76 Mar 21 13:45 /usr/local/bin/python3-config -> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/python3-config lrwxr-xr-x 1 root wheel 71 Mar 21 13:45 /usr/local/bin/python3.1 -> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/python3.1 lrwxr-xr-x 1 root wheel 78 Mar 21 13:45 /usr/local/bin/python3.1-config -> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/python3.1-config lrwxr-xr-x 1 root wheel 70 Mar 21 13:45 /usr/local/bin/pythonw3 -> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/pythonw3 lrwxr-xr-x 1 root wheel 72 Mar 21 13:45 /usr/local/bin/pythonw3.1 -> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/pythonw3.1 John-Wilkinsons-iMac:p31summerfield wilkinson$ On May 24, 2011, at 9:20 AM, Flynn, Stephen (L & P - IT) wrote: > What is your Python executable called? You refer to it as "python" on > the command line but your "#!" line in your script refers to the > executable as "python3.1". tried it with just "python" in the #! Line? > > Check the output of 'ls -al /usr/local/bin/pytho*'... > > S. > > -----Original Message----- > From: tutor-bounces+steve.flynn=capita.co.uk at python.org > [mailto:tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of > Hank Wilkinson > Sent: Tuesday, May 24, 2011 2:10 PM > To: tutor at python.org > Subject: [Tutor] python scripting using "./" > > I am trying to do script in python using "./" > Here is a session showing "bad interpreter: No such file or directory" > Is this a python question/problem? > > Last login: Sat May 21 14:22:49 on ttys000 > John-Wilkinsons-iMac:~ wilkinson$cd > /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$ pwd > /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$ls hello.py > hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$ python hello.py > Hello World! > John-Wilkinsons-iMac:p31summerfield wilkinson$chmod +X hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$ ./hello.py > -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No such > file or directory > John-Wilkinsons-iMac:p31summerfield wilkinson$echo$PATH > /opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/ > bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin > John-Wilkinsons-iMac:p31summerfield wilkinson$cat hello.py > #!/usr/local/bin/python3.1 > > print("Hello", "World!") > John-Wilkinsons-iMac:p31summerfield wilkinson$ python > Python 3.1.2 (r312:79147, Mar 20 2011, 17:15:01) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.path > ['', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > 1.zip', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1/plat-darwin', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1/lib-dynload', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1/site-packages'] > > Thank you. > Hank > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > This email has been scanned for all viruses by the MessageLabs SkyScan > service. > > This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. > > Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. > > All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. > > Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From hwilkinson at triad.rr.com Tue May 24 15:24:53 2011 From: hwilkinson at triad.rr.com (Hank Wilkinson) Date: Tue, 24 May 2011 09:24:53 -0400 Subject: [Tutor] python scripting using "./" In-Reply-To: References: Message-ID: <8FF2FF2E-7415-4ED8-B56A-8A9795DB30F9@triad.rr.com> John-Wilkinsons-iMac:p31summerfield wilkinson$ls -al /usr/local/bin/python ls: /usr/local/bin/python: No such file or directory John-Wilkinsons-iMac:p31summerfield wilkinson$ ls -al /usr/local/bin/python3 lrwxr-xr-x 1 root wheel 69 Mar 21 13:45 /usr/local/bin/python3 -> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/python3 John-Wilkinsons-iMac:p31summerfield wilkinson$On May 24, 2011, at 9:20 AM, Flynn, Stephen (L & P - IT) wrote: > What is your Python executable called? You refer to it as "python" on > the command line but your "#!" line in your script refers to the > executable as "python3.1". tried it with just "python" in the #! Line? > > Check the output of 'ls -al /usr/local/bin/pytho*'... > > S. > > -----Original Message----- > From: tutor-bounces+steve.flynn=capita.co.uk at python.org > [mailto:tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of > Hank Wilkinson > Sent: Tuesday, May 24, 2011 2:10 PM > To: tutor at python.org > Subject: [Tutor] python scripting using "./" > > I am trying to do script in python using "./" > Here is a session showing "bad interpreter: No such file or directory" > Is this a python question/problem? > > Last login: Sat May 21 14:22:49 on ttys000 > John-Wilkinsons-iMac:~ wilkinson$ cd > /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$pwd > /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$ ls hello.py > hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$python hello.py > Hello World! > John-Wilkinsons-iMac:p31summerfield wilkinson$ chmod +X hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py > -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No such > file or directory > John-Wilkinsons-iMac:p31summerfield wilkinson$ echo $PATH > /opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/ > bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin > John-Wilkinsons-iMac:p31summerfield wilkinson$ cat hello.py > #!/usr/local/bin/python3.1 > > print("Hello", "World!") > John-Wilkinsons-iMac:p31summerfield wilkinson$python > Python 3.1.2 (r312:79147, Mar 20 2011, 17:15:01) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.path > ['', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > 1.zip', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1/plat-darwin', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1/lib-dynload', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1/site-packages'] > > Thank you. > Hank > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > This email has been scanned for all viruses by the MessageLabs SkyScan > service. > > This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. > > Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. > > All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. > > Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From joel.goldstick at gmail.com Tue May 24 15:30:28 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 24 May 2011 09:30:28 -0400 Subject: [Tutor] python scripting using "./" In-Reply-To: References: Message-ID: On Tue, May 24, 2011 at 9:10 AM, Hank Wilkinson wrote: > I am trying to do script in python using "./" > Here is a session showing "bad interpreter: No such file or directory" > Is this a python question/problem? > > Last login: Sat May 21 14:22:49 on ttys000 > John-Wilkinsons-iMac:~ wilkinson$ cd > /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$pwd > /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$ ls hello.py > hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$python hello.py > Hello World! > John-Wilkinsons-iMac:p31summerfield wilkinson$ chmod +X hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py > -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No such > file or directory > John-Wilkinsons-iMac:p31summerfield wilkinson$ echo $PATH > > /opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin > John-Wilkinsons-iMac:p31summerfield wilkinson$ cat hello.py > #!/usr/local/bin/python3.1 > > print("Hello", "World!") > John-Wilkinsons-iMac:p31summerfield wilkinson$python > Python 3.1.2 (r312:79147, Mar 20 2011, 17:15:01) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> sys.path > ['', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python31.zip', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/plat-darwin', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/lib-dynload', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages'] > > Thank you. > Hank > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > do you have this in first line of your file: #!/usr/bin/env python in your path you have /usr/bin. if you go there you will probably see a directory with python executable in it. -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From Steve.Flynn at capita.co.uk Tue May 24 15:30:52 2011 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Tue, 24 May 2011 14:30:52 +0100 Subject: [Tutor] python scripting using "./" In-Reply-To: <8FF2FF2E-7415-4ED8-B56A-8A9795DB30F9@triad.rr.com> References: <8FF2FF2E-7415-4ED8-B56A-8A9795DB30F9@triad.rr.com> Message-ID: You missed a "*" from the end of the ls command but it matters not. Your python executable is named "/usr/local/bin/python3" so if you change the first line of your script to... #!/usr/local/bin/python3 ...you should get along much better! :) S. -----Original Message----- From: Hank Wilkinson [mailto:hwilkinson at triad.rr.com] Sent: Tuesday, May 24, 2011 2:25 PM To: Flynn, Stephen (L & P - IT) Cc: tutor at python.org Subject: Re: [Tutor] python scripting using "./" John-Wilkinsons-iMac:p31summerfield wilkinson$ ls -al /usr/local/bin/python ls: /usr/local/bin/python: No such file or directory John-Wilkinsons-iMac:p31summerfield wilkinson$ls -al /usr/local/bin/python3 lrwxr-xr-x 1 root wheel 69 Mar 21 13:45 /usr/local/bin/python3 -> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/python3 John-Wilkinsons-iMac:p31summerfield wilkinson$ On May 24, 2011, at 9:20 AM, Flynn, Stephen (L & P - IT) wrote: > What is your Python executable called? You refer to it as "python" on > the command line but your "#!" line in your script refers to the > executable as "python3.1". tried it with just "python" in the #! Line? > > Check the output of 'ls -al /usr/local/bin/pytho*'... > > S. > > -----Original Message----- > From: tutor-bounces+steve.flynn=capita.co.uk at python.org > [mailto:tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of > Hank Wilkinson > Sent: Tuesday, May 24, 2011 2:10 PM > To: tutor at python.org > Subject: [Tutor] python scripting using "./" > > I am trying to do script in python using "./" > Here is a session showing "bad interpreter: No such file or directory" > Is this a python question/problem? > > Last login: Sat May 21 14:22:49 on ttys000 > John-Wilkinsons-iMac:~ wilkinson$cd > /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$ pwd > /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$ls hello.py > hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$ python hello.py > Hello World! > John-Wilkinsons-iMac:p31summerfield wilkinson$chmod +X hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$ ./hello.py > -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No such > file or directory > John-Wilkinsons-iMac:p31summerfield wilkinson$echo$PATH > /opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/ > bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin > John-Wilkinsons-iMac:p31summerfield wilkinson$cat hello.py > #!/usr/local/bin/python3.1 > > print("Hello", "World!") > John-Wilkinsons-iMac:p31summerfield wilkinson$ python > Python 3.1.2 (r312:79147, Mar 20 2011, 17:15:01) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.path > ['', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > 1.zip', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1/plat-darwin', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1/lib-dynload', > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 > .1/site-packages'] > > Thank you. > Hank > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > This email has been scanned for all viruses by the MessageLabs SkyScan > service. > > This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. > > Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. > > All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. > > Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. This email has been scanned for all viruses by the MessageLabs SkyScan service. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From cwitts at compuscan.co.za Tue May 24 15:29:32 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 24 May 2011 15:29:32 +0200 Subject: [Tutor] python scripting using "./" In-Reply-To: References: Message-ID: <4DDBB2BC.9010302@compuscan.co.za> On 2011/05/24 03:10 PM, Hank Wilkinson wrote: > I am trying to do script in python using "./" > Here is a session showing "bad interpreter: No such file or directory" > Is this a python question/problem? > > Last login: Sat May 21 14:22:49 on ttys000 > John-Wilkinsons-iMac:~ wilkinson$cd /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$ pwd > /Users/wilkinson/Documents/py32/p31summerfield > John-Wilkinsons-iMac:p31summerfield wilkinson$ls hello.py > hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$ python hello.py > Hello World! > John-Wilkinsons-iMac:p31summerfield wilkinson$chmod +X hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$ ./hello.py > -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No such file or directory > John-Wilkinsons-iMac:p31summerfield wilkinson$echo$PATH > /opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin > John-Wilkinsons-iMac:p31summerfield wilkinson$cat hello.py > #!/usr/local/bin/python3.1 > > print("Hello", "World!") > John-Wilkinsons-iMac:p31summerfield wilkinson$ python > Python 3.1.2 (r312:79147, Mar 20 2011, 17:15:01) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.path > ['', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python31.zip', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/plat-darwin', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/lib-dynload', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages'] > > Thank you. > Hank > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Where is the python binary actually located ? You can check with which python to find the location, mine was always /usr/bin/python with *nix, can't say off-hand the location with Mac. -- Christian Witts From __peter__ at web.de Tue May 24 15:38:31 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 24 May 2011 15:38:31 +0200 Subject: [Tutor] python scripting using "./" References: Message-ID: Hank Wilkinson wrote: > I am trying to do script in python using "./" > Here is a session showing "bad interpreter: No such file or directory" > Is this a python question/problem? It's a bash problem. The shell cannot cope with Windows line endings: ^M in the error message stands for chr(13) or Carriage Return. > -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No such > file or directory John-Wilkinsons-iMac:p31summerfield wilkinson$echo There is a utility program called dos2unix to convert line endings, but I don't know if it's available on the Mac.$ cat -v tmp.py #!/usr/bin/python^M print "hello"^M $./tmp.py bash: ./tmp.py: /usr/bin/python^M: bad interpreter: No such file or directory$ dos2unix tmp.py $./tmp.py hello$ From hwilkinson at triad.rr.com Tue May 24 15:51:18 2011 From: hwilkinson at triad.rr.com (Hank Wilkinson) Date: Tue, 24 May 2011 09:51:18 -0400 Subject: [Tutor] python scripting using "./" In-Reply-To: References: <8FF2FF2E-7415-4ED8-B56A-8A9795DB30F9@triad.rr.com> Message-ID: <4A87484F-1EF5-4D55-AF78-CE8C7E6A20B8@triad.rr.com> Thank you, I changed the first line to: #!/usr/bin/env/python3 then I tried again: John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py -bash: ./hello.py: /usr/bin/env/python3^M: bad interpreter: Not a directory John-Wilkinsons-iMac:p31summerfield wilkinson$ So I am getting different messages, but ... On May 24, 2011, at 9:30 AM, Flynn, Stephen (L & P - IT) wrote: > You missed a "*" from the end of the ls command but it matters not. > > Your python executable is named "/usr/local/bin/python3" so if you > change the first line of your script to... > > #!/usr/local/bin/python3 > > ...you should get along much better! :) > > S. > > -----Original Message----- > From: Hank Wilkinson [mailto:hwilkinson at triad.rr.com] > Sent: Tuesday, May 24, 2011 2:25 PM > To: Flynn, Stephen (L & P - IT) > Cc: tutor at python.org > Subject: Re: [Tutor] python scripting using "./" > > John-Wilkinsons-iMac:p31summerfield wilkinson$ls -al > /usr/local/bin/python > ls: /usr/local/bin/python: No such file or directory > John-Wilkinsons-iMac:p31summerfield wilkinson$ ls -al > /usr/local/bin/python3 > lrwxr-xr-x 1 root wheel 69 Mar 21 13:45 /usr/local/bin/python3 -> > ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/python3 > John-Wilkinsons-iMac:p31summerfield wilkinson$> > On May 24, 2011, at 9:20 AM, Flynn, Stephen (L & P - IT) wrote: > >> What is your Python executable called? You refer to it as "python" on >> the command line but your "#!" line in your script refers to the >> executable as "python3.1". tried it with just "python" in the #! Line? >> >> Check the output of 'ls -al /usr/local/bin/pytho*'... >> >> S. >> >> -----Original Message----- >> From: tutor-bounces+steve.flynn=capita.co.uk at python.org >> [mailto:tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf > Of >> Hank Wilkinson >> Sent: Tuesday, May 24, 2011 2:10 PM >> To: tutor at python.org >> Subject: [Tutor] python scripting using "./" >> >> I am trying to do script in python using "./" >> Here is a session showing "bad interpreter: No such file or directory" >> Is this a python question/problem? >> >> Last login: Sat May 21 14:22:49 on ttys000 >> John-Wilkinsons-iMac:~ wilkinson$ cd >> /Users/wilkinson/Documents/py32/p31summerfield >> John-Wilkinsons-iMac:p31summerfield wilkinson$pwd >> /Users/wilkinson/Documents/py32/p31summerfield >> John-Wilkinsons-iMac:p31summerfield wilkinson$ ls hello.py >> hello.py >> John-Wilkinsons-iMac:p31summerfield wilkinson$python hello.py >> Hello World! >> John-Wilkinsons-iMac:p31summerfield wilkinson$ chmod +X hello.py >> John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py >> -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No > such >> file or directory >> John-Wilkinsons-iMac:p31summerfield wilkinson$ echo $PATH >> > /opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/ >> bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin >> John-Wilkinsons-iMac:p31summerfield wilkinson$ cat hello.py >> #!/usr/local/bin/python3.1 >> >> print("Hello", "World!") >> John-Wilkinsons-iMac:p31summerfield wilkinson$python >> Python 3.1.2 (r312:79147, Mar 20 2011, 17:15:01) >> [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import sys >>>>> sys.path >> ['', >> > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 >> 1.zip', >> > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 >> .1', >> > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 >> .1/plat-darwin', >> > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 >> .1/lib-dynload', >> > '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3 >> .1/site-packages'] >> >> Thank you. >> Hank >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> This email has been scanned for all viruses by the MessageLabs SkyScan >> service. >> >> This email and any attachment to it are confidential. Unless you are > the intended recipient, you may not use, copy or disclose either the > message or any information contained in the message. If you are not the > intended recipient, you should delete this email and notify the sender > immediately. >> >> Any views or opinions expressed in this email are those of the sender > only, unless otherwise stated. All copyright in any Capita material in > this email is reserved. >> >> All emails, incoming and outgoing, may be recorded by Capita and > monitored for legitimate business purposes. >> >> Capita exclude all liability for any loss or damage arising or > resulting from the receipt, use or transmission of this email to the > fullest extent permitted by law. > > > This email has been scanned for all viruses by the MessageLabs SkyScan > service. > > This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. > > Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. > > All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. > > Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From hwilkinson at triad.rr.com Tue May 24 15:53:40 2011 From: hwilkinson at triad.rr.com (Hank Wilkinson) Date: Tue, 24 May 2011 09:53:40 -0400 Subject: [Tutor] python scripting using "./" In-Reply-To: References: Message-ID: <990EA720-8848-4541-B9D6-7B42BD567EA1@triad.rr.com> Thank you. John-Wilkinsons-iMac:p31summerfield wilkinson$ which python /opt/local/bin/python On May 24, 2011, at 9:27 AM, Walter Prins wrote: > The problem likely is as intimated by the error message that your python interpreter not called "/usr/local/bin/python3.1" but I'd offhand guess, probably "/usr/local/bin/python". (Indeed, you run the interpreter yourself as "python" not "python3.1" so you should not be using "python3.1" in your script header.) > > To check, try: > > John-Wilkinsons-iMac:~ wilkinson$which python > > Assuming you have the "which" command this will tell you which version of python is used then you do e.g. "python hello.py." Then change the hash-bang (#!) header in your script to match the location you found. (If you dont have "which", you can also try "whereis" or "env" or "type -a".) > > Note, some people use the following hash-bang header in preference of a hard coded path as I've suggested above, as follows: > > #!/usr/bin/env python > > /usr/bin/env goes off and looks up the appropriate path for (in this case) the "python" interpreter, then passes control to that, thereby making your script a little less dependent on a hardcoded paths present on your system. This works provided of course that "env" is available and found in /usr/bin. (Thought I'd mention that in case you wanted to use that instead/try it.) > > Disclaimer: I don't have a Mac, the above is basically general advice which should however work any Unix'ish or GNU'ish system, including I believe on the Mac providing Apple's not changed things that I'm not aware of. > > Hope that helps > > Walter > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From wprins at gmail.com Tue May 24 15:57:07 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 24 May 2011 14:57:07 +0100 Subject: [Tutor] python scripting using "./" In-Reply-To: <990EA720-8848-4541-B9D6-7B42BD567EA1@triad.rr.com> References: <990EA720-8848-4541-B9D6-7B42BD567EA1@triad.rr.com> Message-ID: On 24 May 2011 14:53, Hank Wilkinson wrote: > Thank you. > John-Wilkinsons-iMac:p31summerfield wilkinson$ which python > /opt/local/bin/python > > OK excellent. So you can either use '#!/opt/local/bin/python' in your script, or alternatively '/usr/bin/env python' (presuming that you have 'env' available.) Note the space between the /usr/bin/env" part and the "python" part. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue May 24 16:02:04 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 24 May 2011 15:02:04 +0100 Subject: [Tutor] python scripting using "./" In-Reply-To: <4A87484F-1EF5-4D55-AF78-CE8C7E6A20B8@triad.rr.com> References: <8FF2FF2E-7415-4ED8-B56A-8A9795DB30F9@triad.rr.com> <4A87484F-1EF5-4D55-AF78-CE8C7E6A20B8@triad.rr.com> Message-ID: On 24 May 2011 14:51, Hank Wilkinson wrote: > Thank you, I changed the first line to: > #!/usr/bin/env/python3 > then I tried again: > John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py > -bash: ./hello.py: /usr/bin/env/python3^M: bad interpreter: Not a directory > John-Wilkinsons-iMac:p31summerfield wilkinson$ > > So I am getting different messages, but ... > > Yes, the exact line to use is: #!/usr/bin/env python Note the space between "/usr/bin/env" and "python". If you'd like to know what's happening here I'll explain. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From hwilkinson at triad.rr.com Tue May 24 16:15:18 2011 From: hwilkinson at triad.rr.com (Hank Wilkinson) Date: Tue, 24 May 2011 10:15:18 -0400 Subject: [Tutor] python scripting using "./" In-Reply-To: References: <8FF2FF2E-7415-4ED8-B56A-8A9795DB30F9@triad.rr.com> <4A87484F-1EF5-4D55-AF78-CE8C7E6A20B8@triad.rr.com> Message-ID: <12F4F770-55CB-4509-AE18-CA05F808AF8B@triad.rr.com> Yes, I would love to know why it doesn't work, or what I'm doing wrong. John-Wilkinsons-iMac:p31summerfield wilkinson$cat hello.py #!/usr/bin/env python print("Hello world") John-Wilkinsons-iMac:p31summerfield wilkinson$ chmod +X hello.py John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py -bash: ./hello.py: Permission denied John-Wilkinsons-iMac:p31summerfield wilkinson$ On May 24, 2011, at 10:02 AM, Walter Prins wrote: > > > On 24 May 2011 14:51, Hank Wilkinson wrote: > Thank you, I changed the first line to: > #!/usr/bin/env/python3 > then I tried again: > John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py > -bash: ./hello.py: /usr/bin/env/python3^M: bad interpreter: Not a directory > John-Wilkinsons-iMac:p31summerfield wilkinson$ > > So I am getting different messages, but ... > > Yes, the exact line to use is: > > #!/usr/bin/env python > > Note the space between "/usr/bin/env" and "python". > > If you'd like to know what's happening here I'll explain. > > Walter > > _______________________________________________ > 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 wprins at gmail.com Tue May 24 16:39:16 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 24 May 2011 15:39:16 +0100 Subject: [Tutor] python scripting using "./" In-Reply-To: <12F4F770-55CB-4509-AE18-CA05F808AF8B@triad.rr.com> References: <8FF2FF2E-7415-4ED8-B56A-8A9795DB30F9@triad.rr.com> <4A87484F-1EF5-4D55-AF78-CE8C7E6A20B8@triad.rr.com> <12F4F770-55CB-4509-AE18-CA05F808AF8B@triad.rr.com> Message-ID: Hi Hank, On 24 May 2011 15:15, Hank Wilkinson wrote: > Yes, I would love to know why it doesn't work, or what I'm doing wrong. > > John-Wilkinsons-iMac:p31summerfield wilkinson$cat hello.py > #!/usr/bin/env python > > print("Hello world") > John-Wilkinsons-iMac:p31summerfield wilkinson$ chmod +X hello.py > John-Wilkinsons-iMac:p31summerfield wilkinson$./hello.py > -bash: ./hello.py: Permission denied > OK you had me scratching my head for a couple of minutes, but then I tried your steps on my Ubuntu box and managed to reproduce it. The problem here is you're using +X (capital X) when setting the file execute permission. You should be using +x (lowercase x) when setting the script to be executable. Capital X will only set the file to be executable if it's **already** executable for some other user/group (which is not the case in your new script's case.) Lowercase x will set it executable full stop. Cheers Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From ctsterne at gmail.com Tue May 24 18:08:37 2011 From: ctsterne at gmail.com (Cory Teshera-Sterne) Date: Tue, 24 May 2011 12:08:37 -0400 Subject: [Tutor] Need help wrapping my head around duck typing Message-ID: Hi folks, Coming from a language background that has a different approach to variables (*cough* Java *cough*), I'm trying to understand Python's typing conventions and how to deal with unknown variable types in my code. And as a newbie, I'm really concerned with not writing code that will make the actual Python programmer who will be maintaining my code jump out the window from frustration. An example: I have a directory tree containing year directories (in the form YYYY, ie, "2011"), which contain month directories (in the form MM, ie, "05"), which in turn contain files. I'm writing a Python function to iterate over the tree & return a list of the file names from either the full tree (args==None) or a specified time period within that - ie, Feb. '10 to May '11 (args==startdate, enddate). I'm not sure what the most pythonic approach to dealing with the variables here would be. I have several options: - accept datetime objects and then get the year/month info from that - accept a string (and maybe check its length, add "20" if it's two digits, or reject it if it's more than 4) - accept an integer (and maybe check that it's reasonable) My first inclination would be to only accept 4-digit year and 2-digit month integers and fail the rest, but I understand the value of dealing with different input types here. My second guess would be to use isinstance() for each possibility, since different things need to happen in each case. The "pythonic" approach, as best as I can gather, would be a try/catch block and use the exception types to do the different processing. However, for example, both trying to get a year from a string and a len() of an int raise a TypeError, and in general I'm not sure how to approach this - or am I overthinking things? Finally, I'm aware that I'm really bringing up two topics here: 1) What is the best approach in this and similar cases, in terms of actual, working code that won't make the next user of this code cry? How do/should I distinguish error types in this case?, and less importantly, 2) Can anyone help me get a good handle on the philosophical issues here? I've read several discussions (both strongly against type-checkingand more lenient, as well as good general explanations), but some of it's over my head, a lot of it says something like "I suggest we change Python so it does X", and I'm not sure what it all means for me and my little filename-grabbing script. It's all just a bunch of quaking to me right now ... Thanks so much, Cory -------------- next part -------------- An HTML attachment was scrubbed... URL: From mywrkid at yahoo.com Tue May 24 22:37:06 2011 From: mywrkid at yahoo.com (Neha P) Date: Tue, 24 May 2011 13:37:06 -0700 (PDT) Subject: [Tutor] Python Interview Questions.. Message-ID: <143576.33767.qm@web121816.mail.ne1.yahoo.com> Hey I'll be appearing for Job Interviews and wondering if anybody of you appeared for a Python Interview?Or if on the other end as an interviewer. ? Can you please share the questions asked? ? That will be of great help :) Regards, Neha -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 24 23:41:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 May 2011 22:41:07 +0100 Subject: [Tutor] Python Interview Questions.. References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> Message-ID: "Neha P" wrote > Hey I'll be appearing for Job Interviews and wondering > if anybody of you appeared for a Python Interview > Or if on the other end as an interviewer. > > Can you please share the questions asked? I've been an interviewer many times, but the approach we use is a tehnique called, amongst other things, "situational experience" and involves questions such as: "Tell me about a time when your project was running late." "So what did you do to rectify things?" "And what was the result? "So what did you learn that you would do diferently?" And so on. A more technical example might be: "When you are programming in what is the most common error you make? "So what do you do to avoid it?" "And what is the result? "So what did you learn that you now do differently?" etc etc. The key thing we are looking for is the individual's own contribution. We don't want to hear "as a team we solved world hunger", we want to hear what/how that individual directly contributed - they personally planted 3 tonnes of miracle rice, or whatever. Not sure if that helps? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From martin at linux-ip.net Wed May 25 00:11:39 2011 From: martin at linux-ip.net (Martin A. Brown) Date: Wed, 25 May 2011 00:11:39 +0200 Subject: [Tutor] Python Interview Questions.. In-Reply-To: <143576.33767.qm@web121816.mail.ne1.yahoo.com> References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> Message-ID: Hi there, : Hey I'll be appearing for Job Interviews and wondering if anybody : of you appeared for a Python Interview?Or if on the other end as : an interviewer. ? Can you please share the questions asked? ? : That will be of great help :) I would point out that there are many types of interviews. There's the technical screen, which is what it sounds like you are asking about, but there are other types of interviews that tend to focus on drawing out your approach to problems or your mindset. With the latter type of interview, I would only suggest that you know yourself. If however, you are worried about the technical content of an interview, it is possible that having my list of questions may help you. It may also hinder you, because the set of questions that I ask may differ dramatically from another technical interviewer. We are a fickle lot, prone to ask questions we (think we) know the answers to, which may differ from what you know [0]. With that said, here's a subset of the questions that I commonly use when interviewing candidates for a technical screen--I would rarely ask all of these. * What's your favorite stdlib module? (And, why?) * Distinguish a dict() and a set(). When would I use which? * Distinguish a tuple() and a list(). When would I use which? * What's the risk of 't = sys.stdin.readlines()'? * What's an iterator? Why would I care? * When should I use 'with'? Is there any advantage? * What's a regex? Why not just use string matching? * What does os.stat() return? For what is this useful? * What's WSGI? Why would I use it? * What are ElementTree and lxml? * What's a decorator? * What (unit) testing tools exist and how would I use them? * What does 'raise' do? What does 'pass' do? * Describe Python's inheritance model. And, some others that are geared more toward those who have written network (or SQL) applications: * What's a file descriptor? * What's a socket? * How do I create a listening socket in Python? * What's a signal? * How do I talk to a SQL DB from Python? Any other DBs? * What tools are available for calling an external process? * What's a queue? * What's a thread? Are there any (special) concerns about threads I should have as a Python programmer? If you have some familiarity with Python (particularly in a Unix-like environment) many of these questions would be familiar to you. I would get some idea of your facility with the language and the underlying operating system from the accuracy and comfort with which you answered. You might also find one or two of these (mis)leading and might want to tell me about corner cases that you as a developer have faced. That would also be interesting to me as a technical interviewer. -Martin [0] http://www.quotationspage.com/quote/12220.html -- Martin A. Brown http://linux-ip.net/ From ian.douglas at iandouglas.com Wed May 25 00:50:48 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Tue, 24 May 2011 15:50:48 -0700 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> Message-ID: <4DDC3648.2080809@iandouglas.com> To expand on Martin's questions, when I've interviewed in the past, I've asked (or been asked as an interviewee) questions that investigate critical thinking, like those silly-sounding questions of "how many golf balls would fit in a bus" or "how many windows are there in Seattle". Those kinds of questions are meant to gauge how you think through a problem, not necessarily coming up with the correct answer. When giving an interview, I ask interviewees to write samples of code. A popular one is to write the Fibonacci algorithm in code, or how to write a quick-sort or merge-sort algorithm. Being familiar with some of these computer science principles will show your familiarity with lower level understandings of how software works. It also helps identify people who are self-taught and only know higher level operations, and those who have gone to college/university for computer science or formal software development training. Another favorite of mine was asking a candidate to write a piece of code that took a paragraph of text as a parameter, and while maintaining the order of the sentences, reverse the order of the words in each sentence. So "The sky was blue. The grass was green." would become "blue was sky The. green was grass The." Good luck on your interviewing. -id On 05/24/2011 03:11 PM, Martin A. Brown wrote: > Hi there, > > : Hey I'll be appearing for Job Interviews and wondering if anybody > : of you appeared for a Python Interview Or if on the other end as > : an interviewer. Can you please share the questions asked? > : That will be of great help :) > > I would point out that there are many types of interviews. There's > the technical screen, which is what it sounds like you are asking > about, but there are other types of interviews that tend to focus on > drawing out your approach to problems or your mindset. With the > latter type of interview, I would only suggest that you know > yourself. > > If however, you are worried about the technical content of an > interview, it is possible that having my list of questions may help > you. It may also hinder you, because the set of questions that I > ask may differ dramatically from another technical interviewer. We > are a fickle lot, prone to ask questions we (think we) know the > answers to, which may differ from what you know [0]. > > With that said, here's a subset of the questions that I commonly use > when interviewing candidates for a technical screen--I would rarely > ask all of these. > > * What's your favorite stdlib module? (And, why?) > * Distinguish a dict() and a set(). When would I use which? > * Distinguish a tuple() and a list(). When would I use which? > * What's the risk of 't = sys.stdin.readlines()'? > * What's an iterator? Why would I care? > * When should I use 'with'? Is there any advantage? > * What's a regex? Why not just use string matching? > * What does os.stat() return? For what is this useful? > * What's WSGI? Why would I use it? > * What are ElementTree and lxml? > * What's a decorator? > * What (unit) testing tools exist and how would I use them? > * What does 'raise' do? What does 'pass' do? > * Describe Python's inheritance model. > > And, some others that are geared more toward those who have written > network (or SQL) applications: > > * What's a file descriptor? > * What's a socket? > * How do I create a listening socket in Python? > * What's a signal? > * How do I talk to a SQL DB from Python? Any other DBs? > * What tools are available for calling an external process? > * What's a queue? > * What's a thread? Are there any (special) concerns about > threads I should have as a Python programmer? > > If you have some familiarity with Python (particularly in a > Unix-like environment) many of these questions would be familiar to > you. I would get some idea of your facility with the language and > the underlying operating system from the accuracy and comfort with > which you answered. You might also find one or two of these > (mis)leading and might want to tell me about corner cases that you > as a developer have faced. That would also be interesting to me as > a technical interviewer. > > -Martin > > [0] http://www.quotationspage.com/quote/12220.html > > > > _______________________________________________ > 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 izzaddin.ruhulessin at gmail.com Wed May 25 01:56:17 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Wed, 25 May 2011 01:56:17 +0200 Subject: [Tutor] Need help wrapping my head around duck typing In-Reply-To: References: Message-ID: Hi Cory, >From your description it seems to me that your case is more one of asserting that your function received valid arguments, than a matter of static-vs-ducktyping. Even with type checking, they can still generate errors (out of bounds, incorrect formatting). Now i've seen some discussions where people stated that type checking and argument assertion are bad and that the programmer should just let the code run until it bumps into and error. Python programmers are very inclined to "forgiveness is easier than permission", also referred to in the article you mentioned. However, the principle is only valid in cases where it is guaranteed that an incorrect type or value will produce and exception. For example, if you are interfacing between C and Python this can often not be the case -- or it will crash your programme without any kind of traceback (the dreaded segfault) Will an incorrect type or value raise an exception in your proposed solutions? It probably will, so it is probably best to go for try-except-finally clauses. A sidenote: personnally I would glob the directory and then sort the list by file creation date. Kind regards, Izz ad-Din Ruhulessin 2011/5/24 Cory Teshera-Sterne > Hi folks, > > Coming from a language background that has a different approach to > variables (*cough* Java *cough*), I'm trying to understand Python's typing > conventions and how to deal with unknown variable types in my code. And as a > newbie, I'm really concerned with not writing code that will make the actual > Python programmer who will be maintaining my code jump out the window from > frustration. > > An example: I have a directory tree containing year directories (in the > form YYYY, ie, "2011"), which contain month directories (in the form MM, ie, > "05"), which in turn contain files. I'm writing a Python function to iterate > over the tree & return a list of the file names from either the full tree > (args==None) or a specified time period within that - ie, Feb. '10 to May > '11 (args==startdate, enddate). I'm not sure what the most pythonic approach > to dealing with the variables here would be. I have several options: > - accept datetime objects and then get the year/month info from that > - accept a string (and maybe check its length, add "20" if it's two > digits, or reject it if it's more than 4) > - accept an integer (and maybe check that it's reasonable) > > My first inclination would be to only accept 4-digit year and 2-digit month > integers and fail the rest, but I understand the value of dealing with > different input types here. My second guess would be to use isinstance() for > each possibility, since different things need to happen in each case. The > "pythonic" approach, as best as I can gather, would be a try/catch block and > use the exception types to do the different processing. However, for > example, both trying to get a year from a string and a len() of an int raise > a TypeError, and in general I'm not sure how to approach this - or am I > overthinking things? > > Finally, I'm aware that I'm really bringing up two topics here: > > 1) What is the best approach in this and similar cases, in terms of actual, > working code that won't make the next user of this code cry? How do/should I > distinguish error types in this case?, and less importantly, > > 2) Can anyone help me get a good handle on the philosophical issues here? > I've read several discussions (both strongly against type-checkingand more > lenient, > as well as good general explanations), > but some of it's over my head, a lot of it says something like "I suggest we > change Python so it does X", and I'm not sure what it all means for me and > my little filename-grabbing script. It's all just a bunch of quaking to me > right now ... > > Thanks so much, > Cory > > _______________________________________________ > 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 izzaddin.ruhulessin at gmail.com Wed May 25 01:57:58 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Wed, 25 May 2011 01:57:58 +0200 Subject: [Tutor] Need help wrapping my head around duck typing In-Reply-To: References: Message-ID: I forgot to mention strptime 2011/5/25 Izz ad-Din Ruhulessin > Hi Cory, > > From your description it seems to me that your case is more one of > asserting that your function received valid arguments, than a matter of > static-vs-ducktyping. Even with type checking, they can still generate > errors (out of bounds, incorrect formatting). > > Now i've seen some discussions where people stated that type checking and > argument assertion are bad and that the programmer should just let the code > run until it bumps into and error. Python programmers are very inclined to > "forgiveness is easier than permission", also referred to in the article you > mentioned. However, the principle is only valid in cases where it is > guaranteed that an incorrect type or value will produce and exception. For > example, if you are interfacing between C and Python this can often not be > the case -- or it will crash your programme without any kind of traceback > (the dreaded segfault) > > Will an incorrect type or value raise an exception in your proposed > solutions? It probably will, so it is probably best to go for > try-except-finally clauses. > > A sidenote: personnally I would glob the directory and then sort the list > by file creation date. > > Kind regards, > > Izz ad-Din Ruhulessin > > 2011/5/24 Cory Teshera-Sterne > >> Hi folks, >> >> Coming from a language background that has a different approach to >> variables (*cough* Java *cough*), I'm trying to understand Python's typing >> conventions and how to deal with unknown variable types in my code. And as a >> newbie, I'm really concerned with not writing code that will make the actual >> Python programmer who will be maintaining my code jump out the window from >> frustration. >> >> An example: I have a directory tree containing year directories (in the >> form YYYY, ie, "2011"), which contain month directories (in the form MM, ie, >> "05"), which in turn contain files. I'm writing a Python function to iterate >> over the tree & return a list of the file names from either the full tree >> (args==None) or a specified time period within that - ie, Feb. '10 to May >> '11 (args==startdate, enddate). I'm not sure what the most pythonic approach >> to dealing with the variables here would be. I have several options: >> - accept datetime objects and then get the year/month info from that >> - accept a string (and maybe check its length, add "20" if it's two >> digits, or reject it if it's more than 4) >> - accept an integer (and maybe check that it's reasonable) >> >> My first inclination would be to only accept 4-digit year and 2-digit >> month integers and fail the rest, but I understand the value of dealing with >> different input types here. My second guess would be to use isinstance() for >> each possibility, since different things need to happen in each case. The >> "pythonic" approach, as best as I can gather, would be a try/catch block and >> use the exception types to do the different processing. However, for >> example, both trying to get a year from a string and a len() of an int raise >> a TypeError, and in general I'm not sure how to approach this - or am I >> overthinking things? >> >> Finally, I'm aware that I'm really bringing up two topics here: >> >> 1) What is the best approach in this and similar cases, in terms of >> actual, working code that won't make the next user of this code cry? How >> do/should I distinguish error types in this case?, and less importantly, >> >> 2) Can anyone help me get a good handle on the philosophical issues here? >> I've read several discussions (both strongly against type-checkingand more >> lenient, >> as well as good general explanations), >> but some of it's over my head, a lot of it says something like "I suggest we >> change Python so it does X", and I'm not sure what it all means for me and >> my little filename-grabbing script. It's all just a bunch of quaking to me >> right now ... >> >> Thanks so much, >> Cory >> >> _______________________________________________ >> 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 ctsterne at gmail.com Wed May 25 04:17:43 2011 From: ctsterne at gmail.com (Cory Teshera-Sterne) Date: Tue, 24 May 2011 22:17:43 -0400 Subject: [Tutor] Need help wrapping my head around duck typing In-Reply-To: References: Message-ID: Hello, Thanks for the input. I guess you're right, this is more of a case of argument assertion - but then I'm not sure how to do error handling here, because, for example, multiple issues that should be dealt with in very different ways could raise the same error (as in the original example). I'm also not sure how using glob would work any differently here - wouldn't I still need to iterate over a specified section the directory tree, and therefore have to figure out how to specify it? (Admittedly, I've only played with it for a few minutes, so I might be missing something obvious - and file creation dates don't mean anything in this particular context.) Thanks again, Cory On Tue, May 24, 2011 at 7:57 PM, Izz ad-Din Ruhulessin < izzaddin.ruhulessin at gmail.com> wrote: > I forgot to mention strptime > > > 2011/5/25 Izz ad-Din Ruhulessin > >> Hi Cory, >> >> From your description it seems to me that your case is more one of >> asserting that your function received valid arguments, than a matter of >> static-vs-ducktyping. Even with type checking, they can still generate >> errors (out of bounds, incorrect formatting). >> >> Now i've seen some discussions where people stated that type checking and >> argument assertion are bad and that the programmer should just let the code >> run until it bumps into and error. Python programmers are very inclined to >> "forgiveness is easier than permission", also referred to in the article you >> mentioned. However, the principle is only valid in cases where it is >> guaranteed that an incorrect type or value will produce and exception. For >> example, if you are interfacing between C and Python this can often not be >> the case -- or it will crash your programme without any kind of traceback >> (the dreaded segfault) >> >> Will an incorrect type or value raise an exception in your proposed >> solutions? It probably will, so it is probably best to go for >> try-except-finally clauses. >> >> A sidenote: personnally I would glob the directory and then sort the list >> by file creation date. >> >> Kind regards, >> >> Izz ad-Din Ruhulessin >> >> 2011/5/24 Cory Teshera-Sterne >> >>> Hi folks, >>> >>> Coming from a language background that has a different approach to >>> variables (*cough* Java *cough*), I'm trying to understand Python's typing >>> conventions and how to deal with unknown variable types in my code. And as a >>> newbie, I'm really concerned with not writing code that will make the actual >>> Python programmer who will be maintaining my code jump out the window from >>> frustration. >>> >>> An example: I have a directory tree containing year directories (in the >>> form YYYY, ie, "2011"), which contain month directories (in the form MM, ie, >>> "05"), which in turn contain files. I'm writing a Python function to iterate >>> over the tree & return a list of the file names from either the full tree >>> (args==None) or a specified time period within that - ie, Feb. '10 to May >>> '11 (args==startdate, enddate). I'm not sure what the most pythonic approach >>> to dealing with the variables here would be. I have several options: >>> - accept datetime objects and then get the year/month info from that >>> - accept a string (and maybe check its length, add "20" if it's two >>> digits, or reject it if it's more than 4) >>> - accept an integer (and maybe check that it's reasonable) >>> >>> My first inclination would be to only accept 4-digit year and 2-digit >>> month integers and fail the rest, but I understand the value of dealing with >>> different input types here. My second guess would be to use isinstance() for >>> each possibility, since different things need to happen in each case. The >>> "pythonic" approach, as best as I can gather, would be a try/catch block and >>> use the exception types to do the different processing. However, for >>> example, both trying to get a year from a string and a len() of an int raise >>> a TypeError, and in general I'm not sure how to approach this - or am I >>> overthinking things? >>> >>> Finally, I'm aware that I'm really bringing up two topics here: >>> >>> 1) What is the best approach in this and similar cases, in terms of >>> actual, working code that won't make the next user of this code cry? How >>> do/should I distinguish error types in this case?, and less importantly, >>> >>> 2) Can anyone help me get a good handle on the philosophical issues here? >>> I've read several discussions (both strongly against type-checkingand more >>> lenient, >>> as well as good general explanations), >>> but some of it's over my head, a lot of it says something like "I suggest we >>> change Python so it does X", and I'm not sure what it all means for me and >>> my little filename-grabbing script. It's all just a bunch of quaking to me >>> right now ... >>> >>> Thanks so much, >>> Cory >>> >>> _______________________________________________ >>> 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 waynejwerner at gmail.com Wed May 25 04:37:01 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 24 May 2011 21:37:01 -0500 Subject: [Tutor] Need help wrapping my head around duck typing In-Reply-To: References: Message-ID: On Tue, May 24, 2011 at 9:17 PM, Cory Teshera-Sterne wrote: > Hello, > > Thanks for the input. I guess you're right, this is more of a case of > argument assertion - but then I'm not sure how to do error handling here, > because, for example, multiple issues that should be dealt with in very > different ways could raise the same error (as in the original example). > Well, there are (usually) built-in exceptions that work quite well. Wrong type? Raise a TypeError. Value out of bounds? Raise a ValueError. Usually it turns out that if you're raising more than one error, you probably have your function doing too many things. I'm also not sure how using glob would work any differently here - wouldn't > I still need to iterate over a specified section the directory tree, and > therefore have to figure out how to specify it? (Admittedly, I've only > played with it for a few minutes, so I might be missing something obvious - > and file creation dates don't mean anything in this particular context.) > Specifying a directory tree is quite simple - ask the user! Then you assume that the directory is correct/exists and you check the files, either with glob or os.listdir, and return a list of anything that matches. In the case that they enter an incorrect directory? If you use glob, you'll get nothing. If you use os.listdir, you'll get something like this: >>> os.listdir('/home/flugle/') Traceback (most recent call last): File "", line 1, in OSError: [Errno 2] No such file or directory: '/home/flugle/' Which you can handle in whatever way makes the most sense. Alternatively, if you don't mind using Tkinter, you could do something like: import tkFileDialog as fg import Tkinter as tk root = tk.Tk() root.withdraw() filename = fd.askdirectory() root.quit() # Go and do something with filename. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ctsterne at gmail.com Wed May 25 04:57:53 2011 From: ctsterne at gmail.com (Cory Teshera-Sterne) Date: Tue, 24 May 2011 22:57:53 -0400 Subject: [Tutor] Need help wrapping my head around duck typing In-Reply-To: References: Message-ID: Hmm ... I thought I was going to try to keep this as general as possible, but it may be more helpful if I gave a more concrete example. The code below is the existing function; I'd be ok with throwing it out & starting over, but originally thought I could modify it fairly easily. The directory structure this function works on contains directories named as years (2010, 2009, 2008, ...), each containing month directories (01, 02, 03, ...), which in turn contain files (I can assume the files' extension, but not their creation date). I'm trying to modify the function so that it only returns filepaths from a specified time period (ie, May '10 to Feb '11, or, in directories, the contents of /2010/05, /06 ..., then /2011/01, 02). This means I have two problems: 1) how to limit the iteration, and 2) how to accept a specified time period, and check/handle errors caused by incorrect input I think I've figured out #1 but would appreciate suggestions; #2 is really throwing me for a loop & exposing a lot that I don't know about Python. Thanks, Cory def getpaths(dirpath): yeardirs = os.listdir(dirpath) filepaths = [] for yeardir in yeardirs: yearpath = os.path.join(sitepath, yeardir) if not os.path.isdir(yearpath): continue mondirs = os.listdir(yearpath) for mondir in mondirs: monpath = os.path.join(yearpath, mondir) files = os.listdir(monpath) filepaths.extend([os.path.join(monpath,file) for file in files]) filepaths.sort() return filepaths On Tue, May 24, 2011 at 10:37 PM, Wayne Werner wrote: > On Tue, May 24, 2011 at 9:17 PM, Cory Teshera-Sterne wrote: > >> Hello, >> >> Thanks for the input. I guess you're right, this is more of a case of >> argument assertion - but then I'm not sure how to do error handling here, >> because, for example, multiple issues that should be dealt with in very >> different ways could raise the same error (as in the original example). >> > > Well, there are (usually) built-in exceptions that work quite well. Wrong > type? Raise a TypeError. Value out of bounds? Raise a ValueError. Usually it > turns out that if you're raising more than one error, you probably have your > function doing too many things. > > I'm also not sure how using glob would work any differently here - wouldn't >> I still need to iterate over a specified section the directory tree, and >> therefore have to figure out how to specify it? (Admittedly, I've only >> played with it for a few minutes, so I might be missing something obvious - >> and file creation dates don't mean anything in this particular context.) >> > > Specifying a directory tree is quite simple - ask the user! > > Then you assume that the directory is correct/exists and you check the > files, either with glob or os.listdir, and return a list of anything that > matches. In the case that they enter an incorrect directory? If you use > glob, you'll get nothing. If you use os.listdir, you'll get something like > this: > > >>> os.listdir('/home/flugle/') > Traceback (most recent call last): > File "", line 1, in > OSError: [Errno 2] No such file or directory: '/home/flugle/' > > Which you can handle in whatever way makes the most sense. > > Alternatively, if you don't mind using Tkinter, you could do something > like: > > import tkFileDialog as fg > import Tkinter as tk > > root = tk.Tk() > root.withdraw() > filename = fd.askdirectory() > root.quit() > # Go and do something with filename. > > HTH, > Wayne > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arcejaeger at gmail.com Wed May 25 06:14:22 2011 From: arcejaeger at gmail.com (Rachel-Mikel ArceJaeger) Date: Tue, 24 May 2011 21:14:22 -0700 Subject: [Tutor] Python Variables Changing in Other Functions Message-ID: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> Hello, I am having trouble with determining when python is passing by reference and by value and how to fix it to do what I want: I am writing a program that will take in a list of book titles and will allow many people to rank them in terms of popularity and will export the results to Excel. I'll include the whole code below, but the function I'm having trouble with is rankRandom(). I want it to take in a list of titles, randomize the list (so that I can be certain the order isn't influencing the results of the rankings), get a person's rankings, and then resort the order of the rankings to match the original order of title list (that way I can match up different people's rankings to the correct title). The issue is this: random.shuffle() mutates the list in place, rather than creating a new copy. This is fine, but rather than modifying just the local copy of my titles, it is modifying it in the other functions, too. For instance, rankRandom() is called by main(), which passes it listOfTitles. When rankRandom() returns, listOfTitles has been changed to the randomized version of titles. To fix this, I tried copying the original title list and then assigning it to the mutated version right before the rankRandom() function returns. The local version of titles in rankRandom() does indeed regain its original value, but listOfTitles in main() is still being assigned to the randomized version, and not to the original version. This boggles me, since it seems like shuffle is mutating the titles as if it were a global variable, but assignment is treating it only as a local. What exactly is going on here, and how do I avoid this problem? Many thank! Rachel ---------------------------- import xlwt as excel import random import copy def getTitleList(): """ Makes a list of all the lines in a file """ filename = raw_input("Name and Extension of File: ") myFile = open( filename ) titles = [] title = "none" while title != "": title = myFile.readline() if title not in ["\n",""]: titles.append(title) return titles def rank( titles ): """ Gets a user-input ranking for each line of text. Returns those rankings """ ranks = [] for t in titles: rank = raw_input(t + " ") ranks.append(rank) return ranks def rankRandom( titles ): """ Takes a list of titles, puts them in random order, gets ranks, and then returns the ranks to their original order (so that the rankings always match the correct titles). """ finalRanks = [0]*len(titles) origTitles = copy.copy(titles) #print "Orign: ", origTitles random.shuffle(titles) # Shuffle works in-place ranks = rank(titles) i = 0 for t in titles: finalRanks[ origTitles.index(t) ] = ranks[i] i += 1 titles = origTitles # Must restore, since python passes by reference, not # value, and the original structure was changed by # shuffle #print "t: ", titles return finalRanks def writeToExcel(titles, allRanks): # Open new workbook mydoc = excel.Workbook() # Add a worksheet mysheet = mydoc.add_sheet("Ranks") # Write headers header_font = excel.Font() # Make a font object header_font.bold = True header_font.underline = True # Header font needs to be style, actually header_style = excel.XFStyle(); header_style.font = header_font # Write Headers: write( row, col, data, style ) row = 0 col = 0 for t in titles: # Write data. Indexing is zero based, row then column mysheet.write(row, col, t, header_style) col += 1 # Write Data row += 1 for ranks in allRanks: col = 0 for r in ranks: mysheet.write(row, col, r) col += 1 row += 1 # Save file. You don't have to close it like you do with a file object mydoc.save("r.xls") def main(): listOfTitles = getTitleList() allRanks = [] done = raw_input("Done?: ") while done != "y": allRanks.append( rankRandom( listOfTitles ) ) #print listOfTitles done = raw_input("Done?: ") writeToExcel(listOfTitles, allRanks ) if __name__ == "__main__" : main() From andreengels at gmail.com Wed May 25 07:27:32 2011 From: andreengels at gmail.com (Andre Engels) Date: Wed, 25 May 2011 07:27:32 +0200 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> Message-ID: On Wed, May 25, 2011 at 6:14 AM, Rachel-Mikel ArceJaeger wrote: > I am having trouble with determining when python is passing by reference and by value and how to fix it to do what I want: > > I am writing a program that will take in a list of book titles and will allow many people to rank them in terms of popularity and will export the results to Excel. I'll include the whole code below, but the function I'm having trouble with is rankRandom(). I want it to take in a list of titles, randomize the list (so that I can be certain the order isn't influencing the results of the rankings), get a person's rankings, and then resort the order of the rankings to match the original order of title list (that way I can match up different people's rankings to the correct title). > > The issue is this: random.shuffle() mutates the list in place, rather than creating a new copy. This is fine, but rather than modifying just the local copy of my titles, it is modifying it in the other functions, too. For instance, rankRandom() is called by main(), which passes it listOfTitles. When rankRandom() returns, listOfTitles has been changed to the randomized version of titles. > > To fix this, I tried copying the original title list and then assigning it to the mutated version right before the rankRandom() function returns. The local version of titles in rankRandom() does indeed regain its original value, but listOfTitles in main() is still being assigned to the randomized version, and not to the original version. This boggles me, since it seems like shuffle is mutating the titles as if it were a global variable, but assignment is treating it only as a local. > > What exactly is going on here, and how do I avoid this problem? You should not think of 'pass by reference' or 'pass by value'. That's how things work in the C world. In Python, the data model is that variables are a name for an object. What you are providing when calling an argument with a function is not the variable itself, be it by reference or by value, but the object that the variable refers to. Thus, in your code, when calling rank_random(), "title" becomes (within the function) a name of the object that also has the name listOfTitles in main(). This object is then changed by random.shuffle(). The assignment titles = origTitles gives the object referred to by origTitles a new name, 'titles'. This does _not_ change the object that originally had the name titles, which thus still has the shuffled value. As for how to do what you wanted to do, do make a copy like you do, but then _do the shuffling on the copy_. You could also change the call to the function to have a copy rather than the original variable as its argument, but that solution is not as useful for re-use of the function. Oh, and one more remark: copying a list objects is often done using objects[:] rather than copy.copy(objects) -- Andr? Engels, andreengels at gmail.com From wolf.halton at gmail.com Wed May 25 12:23:10 2011 From: wolf.halton at gmail.com (Wolf Halton) Date: Wed, 25 May 2011 06:23:10 -0400 Subject: [Tutor] python scripting using "./" In-Reply-To: References: <8FF2FF2E-7415-4ED8-B56A-8A9795DB30F9@triad.rr.com> <4A87484F-1EF5-4D55-AF78-CE8C7E6A20B8@triad.rr.com> <12F4F770-55CB-4509-AE18-CA05F808AF8B@triad.rr.com> Message-ID: An oddity of the PATH variable in Linux (or at least Ubuntu) is that there is a folder in PATH called /home/~/bin. The ~ is replaced with your profile name. If you create that folder and put the file into it, you can invoke it from anywhere in the filesystem with just its name. On Tue, May 24, 2011 at 10:39 AM, Walter Prins wrote: > Hi Hank, > > On 24 May 2011 15:15, Hank Wilkinson wrote: > >> Yes, I would love to know why it doesn't work, or what I'm doing wrong. >> >> John-Wilkinsons-iMac:p31summerfield wilkinson$ cat hello.py >> #!/usr/bin/env python >> >> print("Hello world") >> John-Wilkinsons-iMac:p31summerfield wilkinson$chmod +X hello.py >> John-Wilkinsons-iMac:p31summerfield wilkinson$ ./hello.py >> -bash: ./hello.py: Permission denied >> > > OK you had me scratching my head for a couple of minutes, but then I tried > your steps on my Ubuntu box and managed to reproduce it. > > The problem here is you're using +X (capital X) when setting the file > execute permission. You should be using +x (lowercase x) when setting the > script to be executable. Capital X will only set the file to be executable > if it's **already** executable for some other user/group (which is not the > case in your new script's case.) Lowercase x will set it executable full > stop. > > Cheers > > Walter > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- This Apt Has Super Cow Powers - http://sourcefreedom.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed May 25 14:16:22 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 25 May 2011 07:16:22 -0500 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> Message-ID: On Tue, May 24, 2011 at 11:14 PM, Rachel-Mikel ArceJaeger < arcejaeger at gmail.com> wrote: > Hello, > > I am having trouble with determining when python is passing by reference > and by value and how to fix it to do what I want: > Andre already mentioned that you shouldn't think of Python as 'pass-by-reference' or 'pass-by-value', but this link should help you understand why not: http://effbot.org/zone/call-by-object.htm > The issue is this: random.shuffle() mutates the list in place, rather than > creating a new copy. This is fine, but rather than modifying just the local > copy of my titles, it is modifying it in the other functions, too. For > instance, rankRandom() is called by main(), which passes it listOfTitles. > When rankRandom() returns, listOfTitles has been changed to the randomized > version of titles. > > To fix this, I tried copying the original title list and then assigning it > to the mutated version right before the rankRandom() function returns. The > local version of titles in rankRandom() does indeed regain its original > value, but listOfTitles in main() is still being assigned to the randomized > version, and not to the original version. This boggles me, since it seems > like shuffle is mutating the titles as if it were a global variable, but > assignment is treating it only as a local. > > What exactly is going on here, and how do I avoid this problem? > Well, you also have some non-idiomatic code, so I'll go through and comment on the whole thing > ---------------------------- > > import xlwt as excel > import random > import copy > > def getTitleList(): > """ Makes a list of all the lines in a file """ > > filename = raw_input("Name and Extension of File: ") > > myFile = open( filename ) > > titles = [] > You can eliminate from here... > title = "none" > > while title != "": > > title = myFile.readline() > to here, by iterating over your file object directly. The for loop in Python is quite powerful, and in this case you can simply say: for title in myFile: This is easier to read, especially by other Python programmers. You could call it a design pattern - when you want to read a file line by line you can say: for line in filehandle: # do something with line > > if title not in ["\n",""]: > titles.append(title) > > return titles > It also turns out that you can replace almost this entire function with a list comprehension. Because doing this sort of thing: collection = [] for item in another_collection: if item == criteria: collection.append(item) is so common, there is a shortcut - you basically put the loop inside the [] braces and you get the same result: collection = [item for item in another_collection if item == criteria] The syntax is much more terse, but once you understand what's happening, they are much cleaner to both read and write (IMO - some people disagree) So for your program you could say: titles = [title for title in myFile if title not in ["\n",""]] Much shorter than your original function! > > def rank( titles ): > """ Gets a user-input ranking for each line of text. > Returns those rankings > """ > > ranks = [] > > for t in titles: > > rank = raw_input(t + " ") > ranks.append(rank) > What happens if someone inputs "Crunchy Frog" for their rank? What would you expect to happen? > > return ranks > > def rankRandom( titles ): > """ Takes a list of titles, puts them in random order, gets ranks, and > then > returns the ranks to their original order (so that the rankings > always > match the correct titles). > """ > > finalRanks = [0]*len(titles) > > origTitles = copy.copy(titles) > #print "Orign: ", origTitles > > random.shuffle(titles) # Shuffle works in-place > ranks = rank(titles) > > i = 0 > for t in titles: > > finalRanks[ origTitles.index(t) ] = ranks[i] > i += 1 > This code looks clunky. And usually when code looks clunky, that means there's a better way to do it! In your case, I would strongly recommend using a dictionary. As a matter of fact, your problem just begs to use a dictionary, which is a collection of related items, such as a title and a rank. So in your case, you could have something like: finalRanks = {} for title, rank in zip(titles, ranks): # you really should avoid 1-letter variables, except maybe in the case of axes in a graph finalRanks[title] = rank Which would give you something like: {'Gone With the Wind': 2, 'Dune': 1, 'Harold and the Purple Crayon': 3} > > titles = origTitles # Must restore, since python passes by reference, > not > # value, and the original structure was changed by > # shuffle > #print "t: ", titles > > return finalRanks > > def writeToExcel(titles, allRanks): > > # Open new workbook > mydoc = excel.Workbook() > > # Add a worksheet > mysheet = mydoc.add_sheet("Ranks") > > # Write headers > header_font = excel.Font() # Make a font object > header_font.bold = True > header_font.underline = True > > # Header font needs to be style, actually > header_style = excel.XFStyle(); header_style.font = header_font > You should probably break that up onto two lines. You don't gain anything by keeping it on one line, but you lose a lot of readability. > > # Write Headers: write( row, col, data, style ) > row = 0 > col = 0 > for t in titles: > # Write data. Indexing is zero based, row then column > mysheet.write(row, col, t, header_style) > col += 1 > > # Write Data > row += 1 > for ranks in allRanks: > col = 0 > for r in ranks: > mysheet.write(row, col, r) > col += 1 > row += 1 > Remember the part about looking clunky? Having lots of += hanging around is a perfect example of a code smell (i.e. something in this code stinks, and we should change it). Part of being a good programmer is learning to recognize those bad smells and getting rid of them. Turns out, Python has a lot of nice built-in functions for the elimination of code smells. In this case, it's the enumerate function: >>> help(enumerate) Help on class enumerate in module __builtin__: class enumerate(object) | enumerate(iterable[, start]) -> iterator for index, value of iterable | | Return an enumerate object. iterable must be another object that supports | iteration. The enumerate object yields pairs containing a count (from | start, which defaults to zero) and a value yielded by the iterable argument. | enumerate is useful for obtaining an indexed list: | (0, seq[0]), (1, seq[1]), (2, seq[2]), ... . . . for row, ranks in enumerate(allRanks, row+1): # Since apparently you're starting from row + 1 for col, rank in enumerate(ranks): # Again eliminate those 1-letter variables mysheet.write(row, col, rank) Three lines to replace 7. And it's much clearer what's going on here, even if you don't know exactly what enumerate does - because from the loop variables (row, ranks) we can infer that it does something useful, like produce the row and ranks. And since we know there's lots of useful documentation both through using the help() function, and through the web, we can easily look up "python enumerate" or help(enumerate) and find all sorts of useful information and examples. # Save file. You don't have to close it like you do with a file object > mydoc.save("r.xls") > > def main(): > > listOfTitles = getTitleList() > > allRanks = [] > > done = raw_input("Done?: ") > It's usually a good idea to give users an indication of what sort of values you'll accept, such as "Done? (y/[n]): " - this tells the user that you're expecting a y or an n (technically this is a lie, since anything not 'y' will continue, but most people won't care so much. They just need to know that entering 'yes' will not finish the program like they expect!) > > while done != "y": > allRanks.append( rankRandom( listOfTitles ) ) > #print listOfTitles > done = raw_input("Done?: ") > And here is another opportunity to look for code smells. Notice one? Any time you have to write identical code twice, that's probably a bad thing. In this case, you have a couple of options. First, you could simply initialize done this way: done = '' while done.lower() != 'y': # Let the user input 'Y' as well # do stuff done = raw_input("Done? (y/[n]): ") > writeToExcel(listOfTitles, allRanks ) > > > if __name__ == "__main__" : main() > Again, here you don't gain anything by keeping main() on the same line, but you lose some readability. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Wed May 25 14:40:56 2011 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Wed, 25 May 2011 14:40:56 +0200 Subject: [Tutor] Parsing an XML document using ElementTree In-Reply-To: References: Message-ID: Hi Everyone, Thanks for all your suggestions. I read up on gzip and urllib and also learned in the process that I could use urllib2 as its the latest form of that library. Herewith my solution: I don't know how elegant it is, but it works just fine. def get_contests(): url = ' http://xml.matchbook.com/xmlfeed/feed?sport-id=&vendor=TEST&sport-name=&short-name=Po ' req = urllib2.Request(url) req.add_header('accept-encoding','gzip/deflate') opener = urllib2.build_opener() response = opener.open(req) compressed_data = response.read() compressed_stream = StringIO.StringIO(compressed_data) gzipper = gzip.GzipFile(fileobj=compressed_stream) data = gzipper.read() current_path = os.path.realpath(MEDIA_ROOT + '/xml-files/d.xml') data_file = open(current_path, 'w') data_file.write(data) data_file.close() xml_data = ET.parse(open(current_path, 'r')) contest_list = [] for contest_parent_node in xml_data.getiterator('contest'): contest = Contest() for contest_child_node in contest_parent_node: if (contest_child_node.tag == "name" and contest_child_node.text is not None and contest_child_node.text != ""): contest.name = contest_child_node.text if (contest_child_node.tag == "league" and contest_child_node.text is not None and contest_child_node.text != ""): contest.league = contest_child_node.text if (contest_child_node.tag == "acro" and contest_child_node.text is not None and contest_child_node.text != ""): contest.acro = contest_child_node.text if (contest_child_node.tag == "time" and contest_child_node.text is not None and contest_child_node.text != ""): contest.time = contest_child_node.text if (contest_child_node.tag == "home" and contest_child_node.text is not None and contest_child_node.text != ""): contest.home = contest_child_node.text if (contest_child_node.tag == "away" and contest_child_node.text is not None and contest_child_node.text != ""): contest.away = contest_child_node.text contest_list.append(contest) try: os.remove(current_path) except: pass return contest_list Many thanks! On Tue, May 24, 2011 at 12:35 PM, Stefan Behnel wrote: > Sithembewena Lloyd Dube, 24.05.2011 11:59: > > I am trying to parse an XML feed and display the text of each child node >> without any success. My code in the python shell is as follows: >> >> >>> import urllib >> >>> from xml.etree import ElementTree as ET >> >> >>> content = urllib.urlopen(' >> >> http://xml.matchbook.com/xmlfeed/feed?sport-id=&vendor=TEST&sport-name=&short-name=Po >> ') >> >>> xml_content = ET.parse(content) >> >> I then check the xml_content object as follows: >> >> >>> xml_content >> >> > > Well, yes, it does return an XML document, but not what you expect: > > >>> urllib.urlopen('URL see above').read() > "\r\n you must add 'accept-encoding' as > 'gzip,deflate' to the header of your request\r > \n" > > Meaning, the server forces you to pass an HTTP header to the request in > order to receive gzip compressed data. Once you have that, you must > decompress it before passing it into ElementTree's parser. See the > documentation on the gzip and urllib modules in the standard library. > > Stefan > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Sithembewena Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Wed May 25 15:10:06 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 25 May 2011 15:10:06 +0200 Subject: [Tutor] Parsing an XML document using ElementTree In-Reply-To: References: Message-ID: Sithembewena Lloyd Dube, 25.05.2011 14:40: > Thanks for all your suggestions. I read up on gzip and urllib and also > learned in the process that I could use urllib2 as its the latest form of > that library. > > Herewith my solution: I don't know how elegant it is, but it works just > fine. > > def get_contests(): > url = ' > http://xml.matchbook.com/xmlfeed/feed?sport-id=&vendor=TEST&sport-name=&short-name=Po > ' > req = urllib2.Request(url) > req.add_header('accept-encoding','gzip/deflate') > opener = urllib2.build_opener() > response = opener.open(req) This is ok. > compressed_data = response.read() > compressed_stream = StringIO.StringIO(compressed_data) > gzipper = gzip.GzipFile(fileobj=compressed_stream) > data = gzipper.read() This should be simplifiable to uncompressed_stream = gzip.GzipFile(fileobj=response) > current_path = os.path.realpath(MEDIA_ROOT + '/xml-files/d.xml') > data_file = open(current_path, 'w') > data_file.write(data) > data_file.close() > xml_data = ET.parse(open(current_path, 'r')) And this subsequently becomes xml_data = ET.parse(uncompressed_stream) > contest_list = [] > for contest_parent_node in xml_data.getiterator('contest'): Take a look at ET.iterparse(). > contest = Contest() > for contest_child_node in contest_parent_node: > if (contest_child_node.tag == "name" and > contest_child_node.text is not None and contest_child_node.text != ""): > contest.name = contest_child_node.text > if (contest_child_node.tag == "league" and > contest_child_node.text is not None and contest_child_node.text != ""): > contest.league = contest_child_node.text > if (contest_child_node.tag == "acro" and > contest_child_node.text is not None and contest_child_node.text != ""): > contest.acro = contest_child_node.text > if (contest_child_node.tag == "time" and > contest_child_node.text is not None and contest_child_node.text != ""): > contest.time = contest_child_node.text > if (contest_child_node.tag == "home" and > contest_child_node.text is not None and contest_child_node.text != ""): > contest.home = contest_child_node.text > if (contest_child_node.tag == "away" and > contest_child_node.text is not None and contest_child_node.text != ""): > contest.away = contest_child_node.text This is screaming for a simplification, such as for child in contest_parent_node: if child.tag in ('name', 'league', ...): # etc. if child.text: setattr(context, child.tag, child.text) Stefan From bfocus at tznic.or.tz Wed May 25 16:16:05 2011 From: bfocus at tznic.or.tz (Bryton) Date: Wed, 25 May 2011 17:16:05 +0300 Subject: [Tutor] Cherrypy Message-ID: <4DDD0F25.4050302@tznic.or.tz> Is anyone having a step by step tutorial of cherrypy(or book title).I have used the tutorial in their site as well as the book (cherrypy essentials) and I would like to have a one that is a bit more step by step...Please help... -- Regards, Bryton. From wolf.halton at gmail.com Wed May 25 19:25:59 2011 From: wolf.halton at gmail.com (Wolf Halton) Date: Wed, 25 May 2011 13:25:59 -0400 Subject: [Tutor] Clunky Password maker Message-ID: Is there a less clunky way to do this? [code] def new_pass(): series = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', \ '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', \ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\', \ 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '|', \ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "'", \ 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', \ 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', \ 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?'] passwd = [] p = input("Enter the length you want your password to be: ") # length of password for i in range(p): r = random.randint(0, 94) passwd.append(series[r]) # Append a random char from series[] to passwd #print passwd #print passwd[0], passwd[1], passwd[2], passwd[3] print "" print "".join(map(str, passwd)), " is your new password. \n" [/code] [output] >>> Enter 1 to run a MD5 hash on your password Enter 2 to run a SHA1 hash on your password Enter 3 to run a SHA224 hash on your password Enter 9 to get a new randomy password Enter 10 to run away... he he he Enter your choice here> 9 Enter the length you want your password to be: 4 !bnR is your new password. >>> [/output] -- This Apt Has Super Cow Powers - http://sourcefreedom.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: hashy.py Type: application/octet-stream Size: 2808 bytes Desc: not available URL: From enalicho at gmail.com Wed May 25 19:55:24 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 25 May 2011 18:55:24 +0100 Subject: [Tutor] Clunky Password maker In-Reply-To: References: Message-ID: On Wed, May 25, 2011 at 6:25 PM, Wolf Halton wrote: > Is there a less clunky way to do this? > [code] > def new_pass(): > ?? ?series = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', > '=', \ > ?? ? ? ? ? ? ?'~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', > '+', \ > ?? ? ? ? ? ? ?'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', > '\\', \ > ?? ? ? ? ? ? ?'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', > '|', \ > ?? ? ? ? ? ? ?'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "'", \ > ?? ? ? ? ? ? ?'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', \ > ?? ? ? ? ? ? ?'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', \ > ?? ? ? ? ? ? ?'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?'] > ?? ?passwd = [] > ?? ?p = input("Enter the length you want your password to be: ") > ?? ? ? ? ? ? ?# length of password > ?? ?for i in range(p): > ?? ? ? ?r = random.randint(0, 94) > ?? ? ? ?passwd.append(series[r]) # Append a random char from series[] to > passwd > ?? ?#print passwd > ?? ?#print passwd[0], passwd[1], passwd[2], passwd[3] > ?? ?print "" > ?? ?print "".join(map(str, passwd)), " is your new password. \n" > [/code] I suggest you read up on the random module - there's two things that you'll find immediately useful - random.choice and random.sample. I suggest you use sample instead of the for loop you're using. Also, when you print the output, there's no need to use map - everything in your series. From sander.sweers at gmail.com Wed May 25 20:15:03 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 25 May 2011 20:15:03 +0200 Subject: [Tutor] Clunky Password maker In-Reply-To: References: Message-ID: <1306347303.14140.6.camel@Nokia-N900> On Wed, 25 May 2011, 19:25:59 CEST, Wolf Halton wrote: > [code] > def new_pass(): >? ? ? ? series = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', > '=', \ >? ? ? ? ? ? ? ? ? ? ? ? ? ? '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', > '+', \ >? ? ? ? ? ? ? ? ? ? ? ? ? ? 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', > '\\', \ >? ? ? ? ? ? ? ? ? ? ? ? ? ? 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', > '|', \ >? ? ? ? ? ? ? ? ? ? ? ? ? ? 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "'", \ >? ? ? ? ? ? ? ? ? ? ? ? ? ? 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', \ >? ? ? ? ? ? ? ? ? ? ? ? ? ? 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', \ >? ? ? ? ? ? ? ? ? ? ? ? ? ? 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?'] Have a look at the string module as it has all the above already. Greets Sander -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Wed May 25 20:34:34 2011 From: martin at linux-ip.net (Martin A. Brown) Date: Wed, 25 May 2011 20:34:34 +0200 Subject: [Tutor] Clunky Password maker In-Reply-To: References: Message-ID: Hello, : Is there a less clunky way to do this? Yes. There are probably many ways to do this, and this is just something I cooked up at a moment's notice in reply to your question, and probably could be significantly improved upon. : def new_pass(): Your function takes no arguments. Maybe this is something to reconsider. Keep reading. : series = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', \ : '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', \ : 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\', \ : 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '|', \ : 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "'", \ : 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', \ : 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', \ : 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?'] So, if I were staring at my keyboard and starting to type in the characters (not a QWERTZ or AZERTY keyboard, it seems), I would ask myself the question--is there any module that has the complete set of characters that are available to me already, so I don't have to type them all in? Indeed, there is? I found the module called 'string'. In that module, the following are available to you: ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' hexdigits = '0123456789abcdefABCDEF' letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' lowercase = 'abcdefghijklmnopqrstuvwxyz' octdigits = '01234567' printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU... punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_{|}~' uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' whitespace = '\t\n\x0b\x0c\r ' OK, so because I believe in strong (or, at least, reasonably strong) passwords, I'll concatenate a few of these to make the set of characters that I would like to produce in a password. To me, the 'printable' set seems a bit, well, difficult for the person typing a password, so I'll stick with the following: validchars = string.ascii_letters + string.digits + string.punctuation series = list( validchars ) : passwd = [] : p = input("Enter the length you want your password to be: ") : # length of password Maybe you could make the function 'new_pass' take as an argument the number of characters. That way, your function would not need to read input from anyplace else (the console). It could generate passwords of any length regardless of whether it was called from a CGI or command-line or even used from a bulk password generation system. : for i in range(p): : r = random.randint(0, 94) Uh-oh! You had already counted and hard-coded the length of your variable 'series'! What happens if I want to add a few characters at the end? Like maybe the ?, the ? or the ?. I am currently obsessed with (con)currency. If you were to let Python count the elements in your variable 'series', then you would not have to have counted all 94 elements yourself. So, think about why this might be better (more maintainable): : passwd = [] : for i in range(p): : r = random.randint(0, len(series)) : passwd.append(series[r]) # Append a random char from series[] to passwd Now, in the (admittedly, revised loop, above), you generate a single random.randint() for each of the elements that you wish to extract. Chances are that somebody has already implemented a feature to do this sort of thing. Doesn't it seem like a pretty rational sort of thing to have a compute do? Select a bunch of elements randomly from an input set? So, let's try this one of two different ways. Using option A, you can mix up your data and repeatedly pull out the same result for the N items: random.shuffle(series) ''.join(series[0:p]) In option B, you would get a different result each time: ''.join(random.sample(validchars,p)) So, I would rewrite your function to be (substituting 'charcount' for 'p'): #! /usr/bin/env python import string import random def new_pass(charcount): validchars = string.ascii_letters + string.digits + string.punctuation series = list( validchars ) random.shuffle(series) print ''.join(series[0:charcount]) if __name__ == '__main__': new_pass(int(input("Enter the length you want your password to be: "))) Two others have already suggested that you look at the string and random modules. Here's just one example of how you could use them together. Now, let's see what you do with MD5 and SHA. (You are looking at 'hashlib', correct?) Good luck, -Martin -- Martin A. Brown http://linux-ip.net/ From modulok at gmail.com Wed May 25 20:54:58 2011 From: modulok at gmail.com (Modulok) Date: Wed, 25 May 2011 12:54:58 -0600 Subject: [Tutor] Clunky Password maker In-Reply-To: References: Message-ID: On 5/25/11, Wolf Halton wrote: > Is there a less clunky way to do this? > [code] > def new_pass(): > series = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', > '=', \ > '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', > '+', \ > 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', > '\\', \ > 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', > '|', \ > 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "'", \ > 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', \ > 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', \ > 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?'] > passwd = [] > p = input("Enter the length you want your password to be: ") > # length of password > for i in range(p): > r = random.randint(0, 94) > passwd.append(series[r]) # Append a random char from series[] to > passwd > #print passwd > #print passwd[0], passwd[1], passwd[2], passwd[3] > print "" > print "".join(map(str, passwd)), " is your new password. \n" > [/code] > > [output] >>>> > Enter 1 to run a MD5 hash on your password > Enter 2 to run a SHA1 hash on your password > Enter 3 to run a SHA224 hash on your password > Enter 9 to get a new randomy password > Enter 10 to run away... he he he > > Enter your choice here> 9 > Enter the length you want your password to be: 4 > > !bnR is your new password. >>>> > [/output] Depending on what your passwords are going to be protecting, be aware that the default generator in the random module is: "...completely unsuitable for cryptographic purposes." Instead, create an instance of the 'SystemRandom' class. You also don't need to create a list of all of your values. A simple string will do. You should also look into the 'string' module, as it defines 'letters', 'digits' and 'punctuation' characters for you. Thus, your code be something like: import random import string passlen = 10 # How long should it be? r = random.SystemRandom() chars = string.letters + string.digits + string.punctuation passwd = "" for i in range(passlen): passwd += r.choice(chars) print passwd -Modulok- From alan.gauld at btinternet.com Wed May 25 21:45:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 May 2011 20:45:30 +0100 Subject: [Tutor] Clunky Password maker References: Message-ID: "Wolf Halton" wrote > Is there a less clunky way to do this? > def new_pass(): > series = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', > '-', > '=', \ > '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', > '_', > '+', \ > 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', > ']', > '\\', \ > 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', > '}', > '|', \ > 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "'", > \ > 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', > \ > 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', \ > 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?'] You don't need a list here a simple string would do and be easier to type and use. You can index a string as easily as a list. > passwd = [] > p = input("Enter the length you want your password to be: ") > # length of password > for i in range(p): > r = random.randint(0, 94) > passwd.append(series[r]) # Append a random char from series[] > to > passwd You could do this with a list comprehension and using the choice() function from the whrandom module. passwd = [whrandom.choice(series) for n in range(p)] > print "".join(map(str, passwd)), " is your new password. \n" You might want to return the string rather than print it. Then you can print with new_p = new_pass() print new_p, 'is your new password' I'd also move the length question out of the function and make it a parameter so your final code looks like: ln = raw_input("Length of password?") np = new_pass(ln) print np, 'is your new password' For extra points make the alphabet a parameter with a default value so you can use it for non latin alphabets too... klingon = "......." ln = raw_input(klingon_phrases['length']) np = new_pass(ln, klingon) print np, klingon_phrases['new'] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From adam.jtm30 at gmail.com Wed May 25 22:05:36 2011 From: adam.jtm30 at gmail.com (Adam Bark) Date: Wed, 25 May 2011 21:05:36 +0100 Subject: [Tutor] Clunky Password maker In-Reply-To: References: Message-ID: <4DDD6110.7000409@gmail.com> On 25/05/11 19:54, Modulok wrote: > Depending on what your passwords are going to be protecting, be aware that the > default generator in the random module is: > > "...completely unsuitable for cryptographic purposes." If he's just planning on making a few passwords I think the period of 2**19937-1 of the Mersenne twister is plenty large enough not to worry about. From ramit.prasad at jpmchase.com Wed May 25 22:49:10 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 25 May 2011 16:49:10 -0400 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4425B22@EMARC112VS01.exchad.jpmchase.net> >> Having lots of += hanging around is a perfect example of a code smell (i.e. something in this code stinks, and we should change >>it). Part of being a good programmer is learning to recognize those bad smells and getting rid of them. Turns out, Python has a lot >>of nice built-in functions for the elimination of code smells. In this case, it's the enumerate function: What happens if you are trying to write to an excel document with several different sections and need to keep track of things like last written row / current row? I could keep track of enumerations and then save them to a local variable and then append it but that seems about as funky. Is there a better way? # pseudocode-ish # Is this better? blah = enumerate(raw_data) For enumerate_value, data in blah: sheet.write (base_row + enumerate_value , column, data) base_row = blah[-1][0] Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolf.halton at gmail.com Wed May 25 23:02:22 2011 From: wolf.halton at gmail.com (Wolf Halton) Date: Wed, 25 May 2011 17:02:22 -0400 Subject: [Tutor] Clunky Password maker In-Reply-To: <4DDD6110.7000409@gmail.com> References: <4DDD6110.7000409@gmail.com> Message-ID: Now I see. I am going to go woodshed this. Thanks y'all for all the cool ideas! Wolf On May 25, 2011 4:05 PM, "Adam Bark" wrote: > On 25/05/11 19:54, Modulok wrote: >> Depending on what your passwords are going to be protecting, be aware that the >> default generator in the random module is: >> >> "...completely unsuitable for cryptographic purposes." > If he's just planning on making a few passwords I think the period of > 2**19937-1 of the Mersenne twister is plenty large enough not to worry > about. > _______________________________________________ > 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 arcejaeger at gmail.com Wed May 25 23:04:20 2011 From: arcejaeger at gmail.com (Rachel-Mikel ArceJaeger) Date: Wed, 25 May 2011 14:04:20 -0700 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4425B22@EMARC112VS01.exchad.jpmchase.net> References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4425B22@EMARC112VS01.exchad.jpmchase.net> Message-ID: <519EF4AB-B15E-47E5-98C4-F9BD43DF5271@gmail.com> I'm not quite certain I understand. When you say sections, do you mean different worksheets? If so, you should finish writing on one worksheet first, and then move to another. If you're talking about writing to row 5, and then jumping to row 50, enumerate lets you do that by allowing you to determine where to start indexing. btw, my improved code is below. Maybe it will offer some clarification? Rachel --------------- import xlwt as excel import random import copy # Note: When python takes in arguments to a function, it passes in the entire # object, so any modifications made to that object will be retained after the # function terminates without you having to explicity return the object. You # only have to return an object if it wasn't passed in as an argument to the # function and you need to use in in another function. def getTitleList(): """ Makes a list of all the lines in a file """ filename = raw_input("Name and Extension of File: ") myFile = open( filename ) dictOfTitles = {} for title in myFile: if title not in ["\n",""]: dictOfTitles[title] = [] return dictOfTitles def rank( randomizedTitles, dictOfTitles ): """ Gets a user-input ranking (0-10) for each line of text. Returns those rankings """ for title in randomizedTitles: while True: rank = raw_input(title + " ") if not rank.isdigit(): continue elif ( int(rank) > 10 ): continue dictOfTitles[title].append(rank) break def rankRandom( dictOfTitles ): """ Takes a list of titles, puts them in random order, gets ranks, and then returns the ranks to their original order (so that the rankings always match the correct titles). """ randomizedTitles = dictOfTitles.keys() random.shuffle(randomizedTitles) # Shuffle works in-place. rank(randomizedTitles, dictOfTitles) def writeToExcel(dictOfTitles): """ Writes the titles and ranks to Excel """ # Open new workbook mydoc = excel.Workbook() # Add a worksheet mysheet = mydoc.add_sheet("Ranks") # Make header style header_font = excel.Font() # Make a font object header_font.bold = True header_font.underline = True header_style = excel.XFStyle(); header_style.font = header_font # Write headers and ranks to Excel. Indexing is 0-based # write( row, col, data, style ) for col, title in enumerate(dictOfTitles): mysheet.write(0, col, title, header_style) for row, rank in enumerate( dictOfTitles[title], 1 ): mysheet.write(row, col, rank) # Save file. You don't have to close it like you do with a file object mydoc.save("r.xls") def main(): dictOfTitles = getTitleList() done = "" while done.lower() != "y": rankRandom( dictOfTitles ) done = raw_input("Done? (y/[n]): ") writeToExcel(dictOfTitles) if __name__ == "__main__" : main() On May 25, 2011, at 1:49 PM, Prasad, Ramit wrote: > >> Having lots of += hanging around is a perfect example of a code smell (i.e. something in this code stinks, and we should change >>it). Part of being a good programmer is learning to recognize those bad smells and getting rid of them. Turns out, Python has a lot >>of nice built-in functions for the elimination of code smells. In this case, it's the enumerate function: > > What happens if you are trying to write to an excel document with several different sections and need to keep track of things like last written row / current row? I could keep track of enumerations and then save them to a local variable and then append it but that seems about as funky. Is there a better way? > > # pseudocode-ish > # Is this better? > blah = enumerate(raw_data) > For enumerate_value, data in blah: > sheet.write (base_row + enumerate_value , column, data) > base_row = blah[-1][0] > > Ramit > > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer tohttp://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. > R.M. ArceJaeger Author/Publisher, Platypus Press Contact: arcejaeger at gmail.com Website: http://rmarcejaeger.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Thu May 26 00:47:54 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 25 May 2011 18:47:54 -0400 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: <519EF4AB-B15E-47E5-98C4-F9BD43DF5271@gmail.com> References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4425B22@EMARC112VS01.exchad.jpmchase.net> <519EF4AB-B15E-47E5-98C4-F9BD43DF5271@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4425D9A@EMARC112VS01.exchad.jpmchase.net> >>> I'm not quite certain I understand. When you say sections, do you mean different worksheets? If so, you should finish writing on one worksheet first, and then move to another. If you're talking about writing to row 5, and then jumping to row 50, enumerate lets you do that by allowing you to determine where to start indexing. I really mean neither, but jumping is a good enough analogy. I meant from different sections in my code. The enumerate function would work, but still not as helpful since I have to keep track of the last enumeration. Or rewrite so that there is only one entry point for writing to excel and it only gets called once per sheet, but that seems like a more annoying limitation than keeping track of the row manually. Why is enumerate more pythonic? Is it really faster or just easier to read? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu May 26 01:54:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 May 2011 00:54:39 +0100 Subject: [Tutor] Python Variables Changing in Other Functions References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com><0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4425B22@EMARC112VS01.exchad.jpmchase.net> <519EF4AB-B15E-47E5-98C4-F9BD43DF5271@gmail.com> Message-ID: "Rachel-Mikel ArceJaeger" wrote I'm not sure I like this one much... def rank( randomizedTitles, dictOfTitles ): """ Gets a user-input ranking (0-10) for each line of text. Returns those rankings """ for title in randomizedTitles: while True: rank = raw_input(title + " ") if not rank.isdigit(): continue elif ( int(rank) > 10 ): continue I'd have made the while test do the checking: rank = '' while (not rank.isdigit() ) or ( int(rank) > 10 ): rank = raw_input(....) And I'd have put the next line outside the while dictOfTitles[title].append(rank) And you then don't need the break break Just an opinion though, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Thu May 26 03:29:17 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 25 May 2011 20:29:17 -0500 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: <8242D8E3-509F-4BF9-9A8E-C4B1842F4343@gmail.com> References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> <8242D8E3-509F-4BF9-9A8E-C4B1842F4343@gmail.com> Message-ID: On Wed, May 25, 2011 at 3:59 PM, Rachel-Mikel ArceJaeger < arcejaeger at gmail.com> wrote: > Thank you so much for taking the time to comment this all out. It was very > very helpful and showed me improvements to some coding styles I have been > doing for years. I have a couple of questions, though: > > 1. I tried the following line: titles = [title in myFile if title not in > ["\n",""]] > as you suggested, but I'm getting a syntax error pointing to the last ]. > Later on I ended up changed titles from a list to a dict, so I'm not sure if > this is even applicable anymore, but since I use this sort of structure a > lot, I'm curious as to why it is not working. > You'll have to copy/paste the traceback, and the code snippet - otherwise it's just a guess! > 2. I am curious as to how the amended for-loop (for titles in myFile) knows > to assign title to a line of text. I can see that it does, but I'm not sure > why it acts that way. > It's magic! Well, not really. In C-style languages, your for loop usually takes the form of for(int x = 0; x < sizeOfSomething; x++){ somehow_use(something[x]); } But x is usually unused - what you really want to say is "for each item in this collection, do something with that item". So Guido Van Rossum, in his Dutch-y wisdom, blessed us with this type called an iterable. Which is basically anything that you can think of in separate parts. Letters in a string, lines in a file, items in a list, and so on and so forth. Rather than wasting the extra "int x = 0; x < size; x++", you simply have to tell the loop what variable you want to use, and what iteratble you want to iterate over, and Python takes care of the details. Iterables really allow for some super neat programming. > 3. I've never used zip before and I'm a little confused about why your > amended for-loop works the way it does. As far as I can tell, > > a = [1,2,3] > b = ['a','b','c'] > d = zip(a,b) > > means d is [(1, 'a'), (2, 'b'), (3, 'c')] > > So how is it that if I say > > for c,d in zip(a,b): > ... print [c,d] > > I get: > > [1, 'a'] > [2, 'b'] > [3, 'c'] > > It seems to me we should have to unzip the zipped list or something to get > the tuple first, but it immediately gets the elements of the tuple. Why? > This looks like magic, but it really isn't. Consider the following: >>> a = (1,2) >>> x, y = a >>> x 1 >>> y 2 >>> b = [(4,5), (6,7)] >>> x, y = b[0] >>> x 4 >>> y 5 Python has this nifty little feature called unpacking, that allows you to use a collection of data on the right side and a collection of variables on the left side, and if the numbers of arguments match, then assignment happens. As for what happens when the numbers don't match up, I'll leave that experiment to you ;) > > 4. Regarding my previous question about passing in arguments, is the > following surmise correct?: When python takes in arguments to a function, it > passes in the entire object, so any modifications made to that object will > be retained after the function terminates without you having to explicity > return the object. You only have to return an object if it wasn't passed in > as an argument to the function and you need to use in in another function. > No. It might appear that way at times, but that surmise is based on an incorrect premise. If you read this paper: http://effbot.org/zone/python-objects.htm it explains what Python objects really are. Then read http://effbot.org/zone/call-by-object.htm and it explains how Python passes arguments. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From arcejaeger at gmail.com Thu May 26 05:17:22 2011 From: arcejaeger at gmail.com (Rachel-Mikel ArceJaeger) Date: Wed, 25 May 2011 20:17:22 -0700 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> <8242D8E3-509F-4BF9-9A8E-C4B1842F4343@gmail.com> Message-ID: <3B1474AA-58EB-4041-A2AF-F747D0FB0FB7@gmail.com> You asked for the traceback. All I get is this: --------------------- python a2.py File "a2.py", line 20 titles = [title in myFile if title not in ["\n",""]] ^ SyntaxError: invalid syntax ---------------------- (In case the spaces don't come through in this email, the carrot ^ is pointing to the last ]) The function was this: ---------------------- def getTitleList(): """ Makes a list of all the lines in a file """ filename = raw_input("Name and Extension of File: ") myFile = open( filename ) titles = [title in myFile if title not in ["\n",""]] return titles ---------------------- Rachel On May 25, 2011, at 6:29 PM, Wayne Werner wrote: > On Wed, May 25, 2011 at 3:59 PM, Rachel-Mikel ArceJaeger wrote: > Thank you so much for taking the time to comment this all out. It was very very helpful and showed me improvements to some coding styles I have been doing for years. I have a couple of questions, though: > > 1. I tried the following line: titles = [title in myFile if title not in ["\n",""]] > as you suggested, but I'm getting a syntax error pointing to the last ]. Later on I ended up changed titles from a list to a dict, so I'm not sure if this is even applicable anymore, but since I use this sort of structure a lot, I'm curious as to why it is not working. > > You'll have to copy/paste the traceback, and the code snippet - otherwise it's just a guess! > > 2. I am curious as to how the amended for-loop (for titles in myFile) knows to assign title to a line of text. I can see that it does, but I'm not sure why it acts that way. > > It's magic! Well, not really. In C-style languages, your for loop usually takes the form of > > for(int x = 0; x < sizeOfSomething; x++){ > somehow_use(something[x]); > } > > But x is usually unused - what you really want to say is "for each item in this collection, do something with that item". So Guido Van Rossum, in his Dutch-y wisdom, blessed us with this type called an iterable. Which is basically anything that you can think of in separate parts. Letters in a string, lines in a file, items in a list, and so on and so forth. Rather than wasting the extra "int x = 0; x < size; x++", you simply have to tell the loop what variable you want to use, and what iteratble you want to iterate over, and Python takes care of the details. > > Iterables really allow for some super neat programming. > > 3. I've never used zip before and I'm a little confused about why your amended for-loop works the way it does. As far as I can tell, > > a = [1,2,3] > b = ['a','b','c'] > d = zip(a,b) > > means d is [(1, 'a'), (2, 'b'), (3, 'c')] > > So how is it that if I say > > for c,d in zip(a,b): > ... print [c,d] > > I get: > > [1, 'a'] > [2, 'b'] > [3, 'c'] > > It seems to me we should have to unzip the zipped list or something to get the tuple first, but it immediately gets the elements of the tuple. Why? > > This looks like magic, but it really isn't. Consider the following: > >>> a = (1,2) > >>> x, y = a > >>> x > 1 > >>> y > 2 > >>> b = [(4,5), (6,7)] > >>> x, y = b[0] > >>> x > 4 > >>> y > 5 > > Python has this nifty little feature called unpacking, that allows you to use a collection of data on the right side and a collection of variables on the left side, and if the numbers of arguments match, then assignment happens. As for what happens when the numbers don't match up, I'll leave that experiment to you ;) > > > 4. Regarding my previous question about passing in arguments, is the following surmise correct?: When python takes in arguments to a function, it passes in the entire object, so any modifications made to that object will be retained after the function terminates without you having to explicity return the object. You only have to return an object if it wasn't passed in as an argument to the function and you need to use in in another function. > > No. It might appear that way at times, but that surmise is based on an incorrect premise. If you read this paper: http://effbot.org/zone/python-objects.htm it explains what Python objects really are. Then read http://effbot.org/zone/call-by-object.htm and it explains how Python passes arguments. > > HTH, > Wayne R.M. ArceJaeger Author/Publisher, Platypus Press Contact: arcejaeger at gmail.com Website: http://rmarcejaeger.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu May 26 05:34:21 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 25 May 2011 22:34:21 -0500 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: <3B1474AA-58EB-4041-A2AF-F747D0FB0FB7@gmail.com> References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> <8242D8E3-509F-4BF9-9A8E-C4B1842F4343@gmail.com> <3B1474AA-58EB-4041-A2AF-F747D0FB0FB7@gmail.com> Message-ID: On Wed, May 25, 2011 at 10:17 PM, Rachel-Mikel ArceJaeger < arcejaeger at gmail.com> wrote: > You asked for the traceback. All I get is this: > --------------------- > > python a2.py > File "a2.py", line 20 > titles = [title in myFile if title not in ["\n",""]] > > ^ > SyntaxError: invalid syntax > Ahah. You're missing the important part: titles = [title for title in myFile if title not in ["\n",""]] you're missing the "title for" part. That should fix it. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From merrickdav at gmail.com Thu May 26 06:21:01 2011 From: merrickdav at gmail.com (David Merrick) Date: Thu, 26 May 2011 16:21:01 +1200 Subject: [Tutor] PI Message-ID: How do I can access to the math module to use PI? area = math.pi * pow(3,2) Traceback (most recent call last): File "", line 1, in area = math.i * pow(3,2) NameError: name 'math' is not defined -- Dave Merrick merrickdav at gmail.com Ph 03 3423 121 Cell 027 3089 169 -------------- next part -------------- An HTML attachment was scrubbed... URL: From memilanuk at gmail.com Thu May 26 06:36:35 2011 From: memilanuk at gmail.com (memilanuk) Date: Wed, 25 May 2011 21:36:35 -0700 Subject: [Tutor] PI In-Reply-To: References: Message-ID: <4DDDD8D3.9070203@gmail.com> On 05/25/2011 09:21 PM, David Merrick wrote: > How do I can access to the math module to use PI? > > area = math.pi * pow(3,2) > Traceback (most recent call last): > File "", line 1, in > area = math.i * pow(3,2) > NameError: name 'math' is not defined > try 'import math' first... From naheedcse at gmail.com Thu May 26 07:12:16 2011 From: naheedcse at gmail.com (naheed arafat) Date: Thu, 26 May 2011 11:12:16 +0600 Subject: [Tutor] Clunky Password maker In-Reply-To: References: Message-ID: On Wed, May 25, 2011 at 11:25 PM, Wolf Halton wrote: > Is there a less clunky way to do this? > [code] > def new_pass(): > series = ['', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', > '=', \ > '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', > '+', \ > 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', > '\\', \ > 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', > '|', \ > 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "'", \ > 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', \ > 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', \ > 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?'] > > > well. i would have made the series list as follows: >>> a=[chr(i) for i in range(33,127)] >>> a ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_' , '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o' , 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~'] -------------- next part -------------- An HTML attachment was scrubbed... URL: From kty1104 at gmail.com Thu May 26 10:12:38 2011 From: kty1104 at gmail.com (=?UTF-8?B?6rmA7YOc7Jyk?=) Date: Thu, 26 May 2011 17:12:38 +0900 Subject: [Tutor] aubio usage in python Message-ID: hello I am new to python I want to detect pitch in portion of some sound there are pretty good tutorials for ctype but I can't find any document for "aubio" library my platform is windows xp sp3 I want to know what function are there and how to use it could somebody tell me how? thanks in advanced! From alan.gauld at btinternet.com Thu May 26 10:37:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 May 2011 09:37:24 +0100 Subject: [Tutor] aubio usage in python References: Message-ID: "???" wrote > I am new to python > I want to detect pitch in portion of some sound Since you specifically spell aubio with a 'b' I assume you are trying to use the aubio library/module. http://aubio.org/doc/index.html This list is for helping people learn Python and any support for third party modules is pot luck depending on whether anyone else uses it. Given the web page says: "This software is under development. It needs debugging and optimisations. See bugs and todo lists. " And has no documentation or tutorial links it doesn't look like this is exactly mainstream or even mature yet. As such you will have to be a bit experimental and figure out how it works yourself. Possibly by looking at the C code, which is available on the site. Once you do you could then write a tutorial for other users... Alternatively try to find some other more established audio processing liobrary... although its not an area I'm familiar with so cannot give any recommendations. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 26 10:39:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 May 2011 09:39:19 +0100 Subject: [Tutor] aubio usage in python References: Message-ID: "???" wrote > but I can't find any document for "aubio" library OK, I spoke too soon, I found the doc page. http://aubio.org/documentation It has a page on extracting pitch information wioth python. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From delegbede at dudupay.com Thu May 26 11:35:44 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Thu, 26 May 2011 09:35:44 +0000 Subject: [Tutor] PI In-Reply-To: References: Message-ID: <1671995899-1306402521-cardhu_decombobulator_blackberry.rim.net-855395920-@b1.c12.bise7.blackberry> Do import math first I.e type import math You could also do from math import pi Provided pi is the only function u need in the math module. from math import * This imports every function of the math module. HTH Sent from my BlackBerry wireless device from MTN -----Original Message----- From: David Merrick Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Thu, 26 May 2011 16:21:01 To: Subject: [Tutor] PI _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From arcejaeger at gmail.com Thu May 26 15:57:36 2011 From: arcejaeger at gmail.com (Rachel-Mikel ArceJaeger) Date: Thu, 26 May 2011 06:57:36 -0700 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> <8242D8E3-509F-4BF9-9A8E-C4B1842F4343@gmail.com> <3B1474AA-58EB-4041-A2AF-F747D0FB0FB7@gmail.com> Message-ID: Yes it does! Thank you. Rachel On May 25, 2011, at 8:34 PM, Wayne Werner wrote: > On Wed, May 25, 2011 at 10:17 PM, Rachel-Mikel ArceJaeger wrote: > You asked for the traceback. All I get is this: > --------------------- > > python a2.py > File "a2.py", line 20 > titles = [title in myFile if title not in ["\n",""]] > ^ > SyntaxError: invalid syntax > > Ahah. You're missing the important part: > > titles = [title for title in myFile if title not in ["\n",""]] > > you're missing the "title for" part. That should fix it. > > HTH, > Wayne R.M. ArceJaeger Author/Publisher, Platypus Press Contact: arcejaeger at gmail.com Website: http://rmarcejaeger.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu May 26 17:22:54 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 26 May 2011 11:22:54 -0400 Subject: [Tutor] Python Extensions in C Message-ID: Hello All: As an intellectual exercise, I wanted to try my hand at writing some extensions in C. I was wondering if you all could look over my code and give some feedback. Here is the link for the code: http://pastebin.com/jw3ihfsN I have zero experience coding in C (and not much more coding in Python!). Being a kinetic learner, I thought this would be a good exercise to teach me some of the underpinnings of Python, how it works, why it works the way it does, and as an added bonus, skills to actually write my own extensions if I ever wanted to. I had to learn about pointers to do this, and I'm still not 100% on if I used them correctly herein. I am also very concerned with memory management because I am not sure when I should be calling the memory allocation macros to decref or incref when needed. I would also like to get feedback on how I am constructing C algorithms. As far as the module itself goes, I was able to compile and use it on a windows machine compiling with mingw (I use distutils to do the work, so for me I do "python setup.py build" in my CMD. There are three functions, stats.mean, stats.var, stats.stdev (and they do what you would expect). One thing though, these are the "population" statistics and not "sample" in case you want to test it out. Also, anything else that you think would be worthwile pointing out, tips and tricks, common pitfalls, etc. Thanks in advance for you feedback. -------------- next part -------------- An HTML attachment was scrubbed... URL: From arcejaeger at gmail.com Thu May 26 17:46:35 2011 From: arcejaeger at gmail.com (Rachel-Mikel ArceJaeger) Date: Thu, 26 May 2011 08:46:35 -0700 Subject: [Tutor] Python Extensions in C In-Reply-To: References: Message-ID: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> A couple small things that will help improve memory management Rather than avg = sumall / count; return avg; Just return sumall/count instead. Then you don't have to waste a register or assignment operation. Division is expensive. Avoid it when you can. Here, for (a=0; a != count; a++) { temp = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); sumall += temp; Again, save variables and operations. Write this as: for (a=0; a != count; a++) { sumall += PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); Similar corrections in var() It's cheaper when you're using powers of two to just right or left-shift: >> or <<. Since you want to increase by a power of two, do: (avg - PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a) << 1; // This means (...)^(2^1) Division by powers of two is >>. Note that these only works for powers of two. Now I haven't worked with pointers in a long time and didn't fully trace this out so I'm probably wrong, but it doesn't seem like you ever have your pointers in stat_avg() point to an object. Therefore wouldn't they always be Null? R.M. ArceJaeger Author/Publisher, Platypus Press Contact: arcejaeger at gmail.com Website: http://rmarcejaeger.com On May 26, 2011, at 8:22 AM, James Reynolds wrote: > Hello All: > > As an intellectual exercise, I wanted to try my hand at writing some extensions in C. > > I was wondering if you all could look over my code and give some feedback. > > Here is the link for the code: http://pastebin.com/jw3ihfsN > > I have zero experience coding in C (and not much more coding in Python!). Being a kinetic learner, I thought this would be a good exercise to teach me some of the underpinnings of Python, how it works, why it works the way it does, and as an added bonus, skills to actually write my own extensions if I ever wanted to. > > I had to learn about pointers to do this, and I'm still not 100% on if I used them correctly herein. > > I am also very concerned with memory management because I am not sure when I should be calling the memory allocation macros to decref or incref when needed. > > I would also like to get feedback on how I am constructing C algorithms. > > As far as the module itself goes, I was able to compile and use it on a windows machine compiling with mingw (I use distutils to do the work, so for me I do "python setup.py build" in my CMD. > > There are three functions, stats.mean, stats.var, stats.stdev (and they do what you would expect). One thing though, these are the "population" statistics and not "sample" in case you want to test it out. > > Also, anything else that you think would be worthwile pointing out, tips and tricks, common pitfalls, etc. > > Thanks in advance for you feedback. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Thu May 26 18:10:22 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 26 May 2011 18:10:22 +0200 Subject: [Tutor] Python Extensions in C In-Reply-To: References: Message-ID: James Reynolds, 26.05.2011 17:22: > As an intellectual exercise, I wanted to try my hand at writing some > extensions in C. This is fine for en exercise, and I hope you had fun doing this. However, for real code, I suggest you use Cython instead. Your module would have been substantially simpler and likely also faster. http://cython.org Stefan From alan.gauld at btinternet.com Thu May 26 19:24:48 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 May 2011 18:24:48 +0100 Subject: [Tutor] Python Extensions in C References: Message-ID: "James Reynolds" wrote > I was wondering if you all could look over my code and give some > feedback. > > Here is the link for the code: http://pastebin.com/jw3ihfsN Some style issues, the indentation is inconsistent. Also the braces positioning is one of the worst for comprehension (See the book Code Complete for better styles!) Lots of little issues. You need to be more careful on error checking than in Python,. For example consider what happens in avg_func() if count is zero. Also what happens in the loop if a is greater than count? Also, can PyFloat_AsDouble fail? If so what does temp become? And what does that do to sumall? (I don't know the answers BTW so don't read too much into these questions. They are just examples of the pathalogical approach you need to take when writing C!) I don't know how the Python libraries handle memory but there seems to be implicit memory allocation taking place but no deallocation. I assume DECREF actually does more than decrements the refernce count but actually deallocates the memory when it gets to zero? Finally, always, always check pointers passed as parameters before use. Trying to use a NULL pointer is probably the number one source of errors in production C code. A case where you don't is in avg_func(). It may be OK and seq is being set by PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); but the fact it says ...GET_ITEM suggests to me that it probably isn't and expects a valid object reference. Just some thoughts based on a very quick read. And my C is very rusty, I haven't written any real C for at least 10 years! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu May 26 19:40:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 May 2011 18:40:13 +0100 Subject: [Tutor] Python Extensions in C References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> Message-ID: "Rachel-Mikel ArceJaeger" wrote > avg = sumall / count; > return avg; > Just return sumall/count instead. > Then you don't have to waste a register or assignment operation. Readibility counts in C too. And premature optimisation is even more of an evil since C is harder to read to start with.... This code doesn't need to be saving microseconds (the Python object creation will likely consume far more resource and speed than these tweaks). > Division is expensive. Avoid it when you can. That is entirely dependant on your processor. Even on an Intel chip with a math processor it's only very slightly more expensive than the other operators, compared to memory allocation it's lightning fast. And readability counts. > for (a=0; a != count; a++) { > temp = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); > sumall += temp; > Again, save variables and operations. Write this as: > > for (a=0; a != count; a++) { > sumall += > PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); Again the two Python calls will vastly outweigh the savings. And in combining the lines you lose a debug and instrumentation opportunity and the chance to introduce a safety check of the return values. Reliable code beats fast code. > It's cheaper when you're using powers of two to just > right or left-shift: >> or <<. Since you want to increase > by a power of two, do: > > (avg - PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a) << 1; While this is sufficiently idiomatic to be understood by most C programmers it's still likely to be swamped in effect by the Python calls. Readibility still counts, make the code express the algorithm not the workings of the CPU. C can be tweaked to be unreadable or it can be made as clear as most other 3GLs. The more unreadable it is the more likely it is to harbour bugs. If there is a genuine need to be as small and fast as possible then optimise, but hide those optimisations in a function if possible. If there is no need to optimise at the expense of readability or reliability then don't. Consider these the ravings of an ex maintenance programmer who spent far too much of his life deciphering other folks "clever" C code... It wasn't clever and it wasn't working! Alan G. From ramit.prasad at jpmchase.com Thu May 26 19:34:49 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 26 May 2011 13:34:49 -0400 Subject: [Tutor] Python Interview Questions.. In-Reply-To: <4DDC3648.2080809@iandouglas.com> References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> > When giving an interview, I ask interviewees to write samples of code. Would you ask your code samples for a python (or XXX language) position do you have them code it in...C or actually code it in Python (or XXX language)? > Another favorite of mine was asking a candidate to write a piece of code that took a paragraph of text as a parameter, and while maintaining the order of the sentences, reverse the order of the words in each sentence. I ask because this would be fairly easy in Python (admitted my interview solution would have problems with handling punctuations), but probably a lot more complex in something like C. Is C still the standard interviewing basis for the computer science basics (e.g. data structures, algorithms, etc)? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of ian douglas Sent: Tuesday, May 24, 2011 5:51 PM To: Neha P Cc: tutor at python.org Subject: Re: [Tutor] Python Interview Questions.. To expand on Martin's questions, when I've interviewed in the past, I've asked (or been asked as an interviewee) questions that investigate critical thinking, like those silly-sounding questions of "how many golf balls would fit in a bus" or "how many windows are there in Seattle". Those kinds of questions are meant to gauge how you think through a problem, not necessarily coming up with the correct answer. When giving an interview, I ask interviewees to write samples of code. A popular one is to write the Fibonacci algorithm in code, or how to write a quick-sort or merge-sort algorithm. Being familiar with some of these computer science principles will show your familiarity with lower level understandings of how software works. It also helps identify people who are self-taught and only know higher level operations, and those who have gone to college/university for computer science or formal software development training. Another favorite of mine was asking a candidate to write a piece of code that took a paragraph of text as a parameter, and while maintaining the order of the sentences, reverse the order of the words in each sentence. So "The sky was blue. The grass was green." would become "blue was sky The. green was grass The." Good luck on your interviewing. -id On 05/24/2011 03:11 PM, Martin A. Brown wrote: Hi there, : Hey I'll be appearing for Job Interviews and wondering if anybody : of you appeared for a Python Interview?Or if on the other end as : an interviewer. ? Can you please share the questions asked? ? : That will be of great help :) I would point out that there are many types of interviews. There's the technical screen, which is what it sounds like you are asking about, but there are other types of interviews that tend to focus on drawing out your approach to problems or your mindset. With the latter type of interview, I would only suggest that you know yourself. If however, you are worried about the technical content of an interview, it is possible that having my list of questions may help you. It may also hinder you, because the set of questions that I ask may differ dramatically from another technical interviewer. We are a fickle lot, prone to ask questions we (think we) know the answers to, which may differ from what you know [0]. With that said, here's a subset of the questions that I commonly use when interviewing candidates for a technical screen--I would rarely ask all of these. * What's your favorite stdlib module? (And, why?) * Distinguish a dict() and a set(). When would I use which? * Distinguish a tuple() and a list(). When would I use which? * What's the risk of 't = sys.stdin.readlines()'? * What's an iterator? Why would I care? * When should I use 'with'? Is there any advantage? * What's a regex? Why not just use string matching? * What does os.stat() return? For what is this useful? * What's WSGI? Why would I use it? * What are ElementTree and lxml? * What's a decorator? * What (unit) testing tools exist and how would I use them? * What does 'raise' do? What does 'pass' do? * Describe Python's inheritance model. And, some others that are geared more toward those who have written network (or SQL) applications: * What's a file descriptor? * What's a socket? * How do I create a listening socket in Python? * What's a signal? * How do I talk to a SQL DB from Python? Any other DBs? * What tools are available for calling an external process? * What's a queue? * What's a thread? Are there any (special) concerns about threads I should have as a Python programmer? If you have some familiarity with Python (particularly in a Unix-like environment) many of these questions would be familiar to you. I would get some idea of your facility with the language and the underlying operating system from the accuracy and comfort with which you answered. You might also find one or two of these (mis)leading and might want to tell me about corner cases that you as a developer have faced. That would also be interesting to me as a technical interviewer. -Martin [0] http://www.quotationspage.com/quote/12220.html _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From patty at cruzio.com Thu May 26 19:52:17 2011 From: patty at cruzio.com (Patty) Date: Thu, 26 May 2011 10:52:17 -0700 Subject: [Tutor] Python Extensions in C References: Message-ID: ----- Original Message ----- From: "Stefan Behnel" To: Sent: Thursday, May 26, 2011 9:10 AM Subject: Re: [Tutor] Python Extensions in C > James Reynolds, 26.05.2011 17:22: >> As an intellectual exercise, I wanted to try my hand at writing some >> extensions in C. > > This is fine for en exercise, and I hope you had fun doing this. > > However, for real code, I suggest you use Cython instead. Your module > would have been substantially simpler and likely also faster. > > http://cython.org > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Hello James - I saw in your email 'Being a kinetic learner' and I had to look that up - is there a difference between the words 'kinetic' and 'kinesthetic'? When I googled it, I am sure I am a kinetic learner also and I come up with programming exercises for myself as well. I am originally a C programmer and now I really like Python. I don't know what it will be like for you to learn these languages the other way around, I am not the teacher-type. And thanks to Rachel-Mikel for that really nice piece of code to save for the future. Regards, Patty From ian.douglas at iandouglas.com Thu May 26 20:15:12 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Thu, 26 May 2011 11:15:12 -0700 Subject: [Tutor] Python Interview Questions.. In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4DDE98B0.3070705@iandouglas.com> If I were interviewing for a Perl or PHP position, then yes. However, if I just wanted to see if they knew the algorithm, I'd let them use whatever language they were most comfortable in, provided those of us interviewing also knew the language. I think C++ is more common now for data structures and algorithms. -id On 05/26/2011 10:34 AM, Prasad, Ramit wrote: >> When giving an interview, I ask interviewees to write samples of code. > Would you ask your code samples for a python (or XXX language) position do you have them code it in...C or actually code it in Python (or XXX language)? > >> Another favorite of mine was asking a candidate to write a piece of code that took a paragraph of text as a parameter, and while maintaining the order of the sentences, reverse the order of the words in each sentence. > I ask because this would be fairly easy in Python (admitted my interview solution would have problems with handling punctuations), but probably a lot more complex in something like C. > > Is C still the standard interviewing basis for the computer science basics (e.g. data structures, algorithms, etc)? > > > Ramit > -------------- next part -------------- An HTML attachment was scrubbed... URL: From patty at cruzio.com Thu May 26 20:40:18 2011 From: patty at cruzio.com (Patty) Date: Thu, 26 May 2011 11:40:18 -0700 Subject: [Tutor] Python Extensions in C References: Message-ID: "Alan Gauld" wrote in message news:irm3ae$vpl$1 at dough.gmane.org... > "Rachel-Mikel ArceJaeger" wrote > > > Consider these the ravings of an ex maintenance programmer > who spent far too much of his life deciphering other folks > "clever" C code... It wasn't clever and it wasn't working! > > Alan G. > Yikes! Patty From stefan_ml at behnel.de Thu May 26 20:55:50 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 26 May 2011 20:55:50 +0200 Subject: [Tutor] Python Extensions in C In-Reply-To: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> Message-ID: Rachel-Mikel ArceJaeger, 26.05.2011 17:46: > A couple small things that will help improve memory management > > Rather than avg = sumall / count; return avg; Just return sumall/count > instead. Then you don't have to waste a register or assignment > operation. > > Division is expensive. Avoid it when you can. > > Here, for (a=0; a != count; a++) { temp = > PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); sumall += temp; > Again, save variables and operations. Write this as: > > for (a=0; a != count; a++) { sumall += > PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); > > Similar corrections in var() > > It's cheaper when you're using powers of two to just right or > left-shift:>> or<<. Since you want to increase by a power of two, do: > > (avg - PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)<< 1; // This > means (...)^(2^1) > > Division by powers of two is>>. Note that these only works for powers of > two. Oh please! You are seriously insulting my C compiler here. Believe me, it's a *lot* smarter than this. None of this is even faintly necessary. Stefan From stefan_ml at behnel.de Thu May 26 21:07:53 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 26 May 2011 21:07:53 +0200 Subject: [Tutor] Python Extensions in C In-Reply-To: References: Message-ID: Stefan Behnel, 26.05.2011 18:10: > James Reynolds, 26.05.2011 17:22: >> As an intellectual exercise, I wanted to try my hand at writing some >> extensions in C. > > This is fine for en exercise, and I hope you had fun doing this. > > However, for real code, I suggest you use Cython instead. Your module would > have been substantially simpler and likely also faster. > > http://cython.org Oh, and one more thing: it makes it easier to write safe, portable and versatile code. As others have pointed out, your code has unnecessary bugs. It also doesn't compile in Python 3 and lacks the ability to calculate the averages of a set or deque, for example. Instead, it only handles tuples and lists. That reduces the usefulness of your implementation. Stefan From eire1130 at gmail.com Thu May 26 21:19:22 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 26 May 2011 15:19:22 -0400 Subject: [Tutor] Python Extensions in C In-Reply-To: References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> Message-ID: Thank you Rachel and Alan for the feedback. Oddly enough, I had created an exception between the time I sent this and your response to catch occasions when the list is empty (I will need to test a few other things, like what if the list holds items other than strictly numbers?) I did utilize some of the suggestions that Rachel suggested because that is how I generally code in Python in any event, the extra variables were more for my personal readability, but now that I understand the flow a little I eliminated some of them (especially the ones that go directly to return without doing much else) Interestingly, I ran this through the profiler comparing it to similar Python algorithms and the stats.mean is twice as slow as just staying in Python. But, stats.var and stats.stdev are 4-5X faster. As far as the null point goes, it shouldn't be null at all once it gets to the point Alan pointed out. The pointer is set in (for example) stat_avg seq = PySequence_Fast(obj, "Expected a Sequence"); if the point is NULL it won't make it to that, because of: if (seq == NULL) return NULL; But maybe I am missing something that you have seen? I'm going to try to force it to fail in some of the ways you pointed out, and maybe some others. I look forward to more feedback from you all! I'll look into your suggestion regarding comprehension (i'm not sure what that means in a programing sense, but I'm sure I'll find out!) On Thu, May 26, 2011 at 2:55 PM, Stefan Behnel wrote: > Rachel-Mikel ArceJaeger, 26.05.2011 17:46: > > A couple small things that will help improve memory management >> >> Rather than avg = sumall / count; return avg; Just return sumall/count >> instead. Then you don't have to waste a register or assignment >> operation. >> >> Division is expensive. Avoid it when you can. >> >> Here, for (a=0; a != count; a++) { temp = >> PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); sumall += temp; >> Again, save variables and operations. Write this as: >> >> for (a=0; a != count; a++) { sumall += >> PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); >> >> Similar corrections in var() >> >> It's cheaper when you're using powers of two to just right or >> left-shift:>> or<<. Since you want to increase by a power of two, do: >> >> (avg - PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)<< 1; // This >> means (...)^(2^1) >> >> Division by powers of two is>>. Note that these only works for powers of >> two. >> > > Oh please! You are seriously insulting my C compiler here. Believe me, it's > a *lot* smarter than this. > > None of this is even faintly necessary. > > Stefan > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu May 26 21:20:59 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 26 May 2011 15:20:59 -0400 Subject: [Tutor] Python Extensions in C In-Reply-To: References: Message-ID: Someone once told me I was a "kinetic learner" and it seemed to fit with my learning habbits, I wasn't aware there is an entire branch of education theory revolving around "learning specialties", which was interesting to learn about. On Thu, May 26, 2011 at 1:52 PM, Patty wrote: > > ----- Original Message ----- From: "Stefan Behnel" > To: > Sent: Thursday, May 26, 2011 9:10 AM > Subject: Re: [Tutor] Python Extensions in C > > > > James Reynolds, 26.05.2011 17:22: >> >>> As an intellectual exercise, I wanted to try my hand at writing some >>> extensions in C. >>> >> >> This is fine for en exercise, and I hope you had fun doing this. >> >> However, for real code, I suggest you use Cython instead. Your module >> would have been substantially simpler and likely also faster. >> >> http://cython.org >> >> Stefan >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > Hello James - > > I saw in your email 'Being a kinetic learner' and I had to look that up - > is there a difference between > the words 'kinetic' and 'kinesthetic'? When I googled it, I am sure I am a > kinetic learner also and I come > up with programming exercises for myself as well. I am originally a C > programmer and now I really like > Python. I don't know what it will be like for you to learn these > languages the other way around, I am not > the teacher-type. > > And thanks to Rachel-Mikel for that really nice piece of code to save for > the future. > > Regards, > > Patty > > > > _______________________________________________ > 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 ramit.prasad at jpmchase.com Thu May 26 21:22:15 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 26 May 2011 15:22:15 -0400 Subject: [Tutor] nested / concatenated function docstrings? Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA44B0CAE@EMARC112VS01.exchad.jpmchase.net> Module 1: Def first(arg1,arg2, *args, **kwargs): # some code that wraps around second(*args, **kwargs) Module 2: Def second(...): # some code here Function first is basically a wrapper around second. Both are generators but first is more refined/selective about what it yields. I would like to have the docstring for function first also contain the docstring for second because it should support/pass any argument second contains. I do not want to copy/paste because second is more likely to be updated with more options than first and this would lead to first's docstring being outdated. Is there a way to concatenate or nest the docstrings so they are automatically updated together? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From eire1130 at gmail.com Thu May 26 21:34:06 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 26 May 2011 15:34:06 -0400 Subject: [Tutor] Python Extensions in C In-Reply-To: References: Message-ID: On Thu, May 26, 2011 at 3:07 PM, Stefan Behnel wrote: > Stefan Behnel, 26.05.2011 18:10: > > James Reynolds, 26.05.2011 17:22: >> >>> As an intellectual exercise, I wanted to try my hand at writing some >>> extensions in C. >>> >> >> This is fine for en exercise, and I hope you had fun doing this. >> >> However, for real code, I suggest you use Cython instead. Your module >> would >> have been substantially simpler and likely also faster. >> >> http://cython.org >> > > Oh, and one more thing: it makes it easier to write safe, portable and > versatile code. As others have pointed out, your code has unnecessary bugs. > It also doesn't compile in Python 3 and lacks the ability to calculate the > averages of a set or deque, for example. Instead, it only handles tuples and > lists. That reduces the usefulness of your implementation. > > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Stefan, Thank you for point out the above. Could you kindly please point out some of those unnecessary bugs? I'm not sure that it matters that it won't work in sets and deque's, so long as the documentation is clear, no? (Which I'm still not sure how to do, just yet) But, I did test it for sets and deque and it works just fine. setx = set([]) print type(setx) for i in r: setx.add(random.choice(r)) print stats.mean(setx) dequex = deque([]) print type(dequex) for i in r: dequex.append(random.choice(r)) print stats.mean(dequex) I'll see what I can do about making it work with P3k, I think the only thing that would need to be changed would be "PyMODINIT_FUNC initstats(void)" I believe. Please correct me if I'm wrong though. Thank you again for the feedback. -------------- next part -------------- An HTML attachment was scrubbed... URL: From 0101amt at gmail.com Thu May 26 21:36:08 2011 From: 0101amt at gmail.com (amt) Date: Thu, 26 May 2011 22:36:08 +0300 Subject: [Tutor] Non programmer wanting to become programmer Message-ID: First of all, hello! I want to start learning programming. I'm looking into becoming more than a hobbyist programmer. I searched a lot on Google on what programming language should I learn first and I see a lot of good words about Python so I decided to go for it but have some questions: 1)What book should I start with? ( I have checked Python for non programmers but there are a lot of titles there, what should I pick first?I was thinking about Invent your own computer games with Python.) 2)Version 2 or version 3? What should I go for as a beginner and why? ( I ask because some books in the Python for non programmers section are for python 2, Invent your own computer games with Python is version 3.) 3)Algorithms, memory management, data structures, when is the right time to learn them? Regards, amt. -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Thu May 26 21:49:12 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Fri, 27 May 2011 01:19:12 +0530 Subject: [Tutor] Non programmer wanting to become programmer In-Reply-To: References: Message-ID: Hello amt, Please find my responses below - On Fri, May 27, 2011 at 1:06 AM, amt <0101amt at gmail.com> wrote: > First of all, hello! I want to start learning programming. I'm looking > into becoming more than a hobbyist programmer. I searched a lot on Google on > what programming language should I learn first and I see a lot of good words > about Python so I decided to go for it but have some questions: > > 1)What book should I start with? ( I have checked Python for non > programmers but there are a lot of titles there, what should I pick first?I > was thinking about Invent your own computer games with Python.) > >> I think Learning Python and Core Python Programming are good books. > Please also have a look at Learn Python the Hard Way. > > 2)Version 2 or version 3? What should I go for as a beginner and why? ( I > ask because some books in the Python for non programmers section are for > python 2, Invent your own computer games with Python is version 3.) > >> I would start with version 2 first as I think there are more resources > available on that. > > 3)Algorithms, memory management, data structures, when is the right time to > learn them? > >> :) . The two things go hand in hand. It is like pieces of a jigsaw. Now is the right time in my opinion. But you should be able to map the data structures with the programming concepts. For some data structures C/C++ may be better options to consider. I consider myself as a student only and this is my personal approach. May be there is a better way. Regards, Sumod > > > Regards, amt. > > _______________________________________________ > 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 kb1pkl at aim.com Thu May 26 22:01:01 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 26 May 2011 16:01:01 -0400 Subject: [Tutor] Non programmer wanting to become programmer In-Reply-To: References: Message-ID: <4DDEB17D.3050703@aim.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/26/2011 03:36 PM, amt wrote: > First of all, hello! I want to start learning programming. I'm looking into > becoming more than a hobbyist programmer. I searched a lot on Google on what > programming language should I learn first and I see a lot of good words > about Python so I decided to go for it but have some questions: > > 1)What book should I start with? ( I have checked Python for non > programmers but there are a lot of titles there, what should I pick first?I > was thinking about Invent your own computer games with Python.) > I used Alan Gauld's tutor when I was first learning to program, it's at: http://www.alan-g.me.uk/tutor/index.htm Many of the other books listed on that wiki are great too, I've heard good things about Python the Hard Way and How to think like a Computer Scientist. > > 2)Version 2 or version 3? What should I go for as a beginner and why? ( I > ask because some books in the Python for non programmers section are for > python 2, Invent your own computer games with Python is version 3.) > For now, I'd say 2. It has more libraries available, and you won't be missing much. Once you know python using the other version should take you about 30ish minutes to figure out. See http://wiki.python.org/moin/Python2orPython3 > > 3)Algorithms, memory management, data structures, when is the right time to > learn them? > Python does memory management for you, so you don't need to worry about that. As for data structures, there's not much complex that you need to know about that in python either, unless you are doing more advanced things (like graphs!) Algorithms are good to learn too, but don't worry about them right away. For things like this I would recommend getting very familiar with Python, and then picking up a bit of C. - -- Corey Richardson -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.17 (GNU/Linux) iQEcBAEBAgAGBQJN3rF9AAoJEAFAbo/KNFvp0nYH/jUAx53mZD/jmKw5YbGbKXFq lkSW/nWSftAle7oKtuBDOMjpK32/K/bYWXfPkJrrZicqt57mbT6xyeIFQmbplwrf jpjEpNtbI/jSjrm9Na4mjuzRUIkJRUk4PgTT1Mk376eQKWfZo5OejWRiSF+BgMfH 6SSOkB/h+cWLDnAJ/mH46iLrxfrcM4ArPydEK/zxcm/JMSIgixG3RvbyF3l4y3Nr ZV8yzKXeHedQpRns3a3/zUX4YsZ8izrMD2NQz0zDfXKpBhtjiSKXVi1/OUnYs+zY TtwBbVCwFbFcHNenXNeXfK7cCqlw8HP3Xj87QmoXAj8X/OfRBV7AtZNtXqIQJe4= =8uJL -----END PGP SIGNATURE----- From jigenbakuda at yahoo.com Thu May 26 22:01:12 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Thu, 26 May 2011 13:01:12 -0700 (PDT) Subject: [Tutor] Non programmer wanting to become programmer In-Reply-To: References: Message-ID: <786334.25188.qm@web130202.mail.mud.yahoo.com> I am a beginner so I can relate with you, although python is my first programming language, it sounds as if you are coming from another language. Either way, here are some sites I'll collected that have tutorials and are free. Alan's tutorial (alan is a very active member here) http://www.freenetpages.co.uk/hp/alan.gauld/ How to think like a computer scientist (uses python) http://openbookproject.net/thinkcs/python/english2e/index.html Learn python the hard way http://p2pu.org/webcraft/learn-python-hard-way The official python tutorial (2.7) (all the versions are available) http://docs.python.org/tutorial/index.html If you happen to be a visual / audio learner try these Lec 1 | MIT 6.00 Introduction to Computer Science and Programming, Fall 2008 http://www.youtube.com/watch?v=k6U-i4gXkLM Bucky's youtube tutorial http://www.youtube.com/user/thenewboston#p/c/EA1FEF17E1E5C0DA/0/4Mf0h3HphEA Lecture 1A | MIT 6.001 Structure and Interpretation, 1986 (uses scheme, but the concepts are highly transferable) http://www.youtube.com/watch?v=2Op3QLzMgSY If you are planning to go into video game development, I recommend this tutorial http://inventwithpython.com/chapters/ These are just a fraction of the info out there, I found all these links in my journey to get better at programming, so if these links don't suit you, don't be scared to go out there and look. ? ---- What is it about you... that intrigues me so? ________________________________ From: amt <0101amt at gmail.com> To: tutor at python.org Sent: Thursday, May 26, 2011 3:36 PM Subject: [Tutor] Non programmer wanting to become programmer First of all, hello!? I want to start learning programming. I'm looking into becoming more than a hobbyist programmer. I searched a lot on Google on what programming language should I learn first and I see a lot of good words about Python so I decided to go for it but have some questions: 1)What book should I start with?? ( I have checked Python for non programmers but there are a lot of titles there, what should I pick first?I was thinking about Invent your own computer games with Python.) 2)Version 2 or version 3? What should I go for as a beginner and why? ( I ask because some books in the Python for non programmers section are for python 2, Invent your own computer games with Python is version 3.) 3)Algorithms, memory management, data structures, when is the right time to learn them? Regards, amt. _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Thu May 26 23:28:47 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 26 May 2011 23:28:47 +0200 Subject: [Tutor] Python Extensions in C In-Reply-To: References: Message-ID: James Reynolds, 26.05.2011 21:34: > On Thu, May 26, 2011 at 3:07 PM, Stefan Behnel wrote: >> Stefan Behnel, 26.05.2011 18:10: >> James Reynolds, 26.05.2011 17:22: >>> >>>> As an intellectual exercise, I wanted to try my hand at writing some >>>> extensions in C. >>> >>> This is fine for en exercise, and I hope you had fun doing this. >>> >>> However, for real code, I suggest you use Cython instead. Your module >>> would have been substantially simpler and likely also faster. >>> >>> http://cython.org >> >> Oh, and one more thing: it makes it easier to write safe, portable and >> versatile code. As others have pointed out, your code has unnecessary bugs. >> It also doesn't compile in Python 3 and lacks the ability to calculate the >> averages of a set or deque, for example. Instead, it only handles tuples and >> lists. That reduces the usefulness of your implementation. > > Thank you for point out the above. Could you kindly please point out some of > those unnecessary bugs? Alan gave a good response here. For example, PyFloat_AsDouble() can fail, you need to handle that. Your code also does not correctly sum up floating point numbers. See math.fsum() for that. Here's a possible Cython version of the variance() function: from math import fsum def variance(seq): "Calculate the variance of all FP numbers in a sequence." cdef double value, dsum cdef Py_ssize_t count = len(seq) dsum = fsum(seq) average = dsum / count return fsum([(average - value) ** 2 for value in seq]) / count You can avoid the list comprehension (read: creation) in the second call by using a generator expression (remove the angular brackets). However, this is likely to run slower (and requires Cython 0.15 ;), so we are trading memory for speed here. If you want this implementation to run faster, you need to unfold and inline fsum's algorithm, which you can look up in the CPython sources. For comparison, here is a less accurate version that does not use fsum() but your own algorithm: def variance(seq): cdef double value, dsum, sqsum cdef Py_ssize_t count = len(seq) dsum = 0.0 for value in seq: dsum += value average = dsum / count sqsum = 0.0 for value in seq: sqsum += (average - value) ** 2 return sqsum / count Note that both implementations cannot work with iterators as input as they iterate twice. If you want to support that, you can add seq = list(seq) at the start, which will let us trade memory for this feature. An additional type test condition for seq not being a list or tuple will give you more or less what PySequence_Fast() does. > I'm not sure that it matters that it won't work in sets and deque's, so long > as the documentation is clear, no? It will matter to the users of your code at some point. > (Which I'm still not sure how to do, just yet) What do you mean? Doc strings? You can just add them to the module function struct: http://docs.python.org/py3k/extending/extending.html#the-module-s-method-table-and-initialization-function > But, I did test it for sets and deque and it works just fine. > > setx = set([]) > print type(setx) > for i in r: > setx.add(random.choice(r)) > print stats.mean(setx) > dequex = deque([]) > print type(dequex) > for i in r: > dequex.append(random.choice(r)) > print stats.mean(dequex) Right. I keep forgetting that PySequence_Fast() actually has a fallback that copies the iterable into a tuple. So you are also trading memory here to make it work for all iterable types. Personally, I'd never use the PySequence_Fast*() API because it isn't really all that fast. It's just faster than normal Python iteration for tuples and lists and also avoids copying in that case. All other cases are worse than generic iteration, and it's not faster than Cython's looping code. > I'll see what I can do about making it work with P3k, I think the only thing > that would need to be changed would be "PyMODINIT_FUNC initstats(void)" I > believe. Please correct me if I'm wrong though. You need to create a module struct and use a different name for the init function. Another thing that Cython code doesn't have to care about. Stefan From wolf.halton at gmail.com Thu May 26 23:45:57 2011 From: wolf.halton at gmail.com (Wolf Halton) Date: Thu, 26 May 2011 17:45:57 -0400 Subject: [Tutor] Clunky Password maker In-Reply-To: References: Message-ID: I have a 0.2 version [code] def new_pass(p): valchars = string.ascii_letters + string.digits + string.punctuation series = list(valchars) pp = int(raw_input("Enter the length you want your password to be:[%i] " % (p)) or p) # length of password chosen or default length rr = random.sample(series, pp) print "\nYour New Password is: \n" print "".join(rr), "\n" [/code] Now I am looking at how to make it have an admin function to set the valid characters, and have a way to output the password into main() The modules for finding the hashes produce many unreadable characters: [code] def md_five(): print "Enter a password and find the MD5 hash" passwd = raw_input("Enter your password for testing: ") m = hashlib.md5() m.update(passwd) print "\nThe password", passwd, " is ", m.digest(), "\nand that hash in hex is | ", m.hexdigest() print "" [/code] [output] Enter 1 to run a MD5 hash on your password Enter 2 to run a SHA1 hash on your password Enter 3 to run a SHA224 hash on your password Enter 9 to get a new randomy password Enter 10 to run away... he he he Enter your choice here> 1 Enter a password and find the MD5 hash Enter your password for testing: bad_password The password bad_password is "vM?U< ??W???"W and that hash in hex is | 22764da5553c20cc80cc579db5bd2257 [/output] -- This Apt Has Super Cow Powers - http://sourcefreedom.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From arcejaeger at gmail.com Thu May 26 23:47:48 2011 From: arcejaeger at gmail.com (Rachel-Mikel ArceJaeger) Date: Thu, 26 May 2011 14:47:48 -0700 Subject: [Tutor] Python Extensions in C In-Reply-To: References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> Message-ID: <22D05560-CCB6-47F8-994C-50CF2FA1FAA3@gmail.com> I suppose it's up to the programmer. Personally, I find something like this: variable += something a lot easier to read than temp = something variable += temp For me, it's just another variable I have to worry about allocating/deallocating/seeing if it's used anywhere else/accidentally using when I shouldn't. And I'm sure you're right and the memory tweaks I mentioned aren't that necessary. I only brought them up because James asked about memory management and depending on the program you're using and the size of your inputs, it actually can make a difference. I recall one program I wrote where changing things little things like division and eliminating extra variables that we don't think of as being time-expensive drastically lessened the runtime. Rachel On May 26, 2011, at 10:40 AM, Alan Gauld wrote: > "Rachel-Mikel ArceJaeger" wrote > >> avg = sumall / count; >> return avg; >> Just return sumall/count instead. >> Then you don't have to waste a register or assignment operation. > > Readibility counts in C too. And premature optimisation is even > more of an evil since C is harder to read to start with.... > This code doesn't need to be saving microseconds (the Python > object creation will likely consume far more resource and > speed than these tweaks). > >> Division is expensive. Avoid it when you can. > > That is entirely dependant on your processor. > Even on an Intel chip with a math processor it's > only very slightly more expensive than the other operators, > compared to memory allocation it's lightning fast. > And readability counts. > >> for (a=0; a != count; a++) { >> temp = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); >> sumall += temp; >> Again, save variables and operations. Write this as: >> >> for (a=0; a != count; a++) { >> sumall += PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a)); > > Again the two Python calls will vastly outweigh the savings. > And in combining the lines you lose a debug and instrumentation > opportunity and the chance to introduce a safety check of > the return values. Reliable code beats fast code. > >> It's cheaper when you're using powers of two to just >> right or left-shift: >> or <<. Since you want to increase >> by a power of two, do: >> >> (avg - PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq,a) << 1; > > While this is sufficiently idiomatic to be understood by > most C programmers it's still likely to be swamped in effect > by the Python calls. Readibility still counts, make the > code express the algorithm not the workings of the CPU. > > C can be tweaked to be unreadable or it can be made as > clear as most other 3GLs. The more unreadable it is the > more likely it is to harbour bugs. If there is a genuine need > to be as small and fast as possible then optimise, but hide > those optimisations in a function if possible. If there is no > need to optimise at the expense of readability or reliability > then don't. > > Consider these the ravings of an ex maintenance programmer > who spent far too much of his life deciphering other folks > "clever" C code... It wasn't clever and it wasn't working! > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor R.M. ArceJaeger Author/Publisher, Platypus Press Contact: arcejaeger at gmail.com Website: http://rmarcejaeger.com From ian.douglas at iandouglas.com Thu May 26 23:53:46 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Thu, 26 May 2011 14:53:46 -0700 Subject: [Tutor] Clunky Password maker In-Reply-To: References: Message-ID: <4DDECBEA.6000609@iandouglas.com> On 05/26/2011 02:45 PM, Wolf Halton wrote: > Now I am looking at how to make it have an admin function to set the > valid characters, and have a way to output the password into main() > > Simple, just learn to use the 'return' statement: [code] def new_pass(p): pp = int(raw_input("Enter the length you want your password to be:[%i] " % (p)) or p) # length of password chosen or default length new_password = generate_new_pass(pp) print "\nYour New Password is: %s\n" % new_password return new_password def generate_new_pass(userlength): valchars = string.ascii_letters + string.digits + string.punctuation series = list(valchars) rr = random.sample(series, userlength) return join(rr) def main(): my_new_password = new_pass(default_length) [/code] From alan.gauld at btinternet.com Fri May 27 01:34:33 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 27 May 2011 00:34:33 +0100 (BST) Subject: [Tutor] Python Extensions in C In-Reply-To: <22D05560-CCB6-47F8-994C-50CF2FA1FAA3@gmail.com> References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> <22D05560-CCB6-47F8-994C-50CF2FA1FAA3@gmail.com> Message-ID: <467120.90962.qm@web86706.mail.ird.yahoo.com> > I suppose it's up to the programmer. It is, provided the programmer is remembering that the audience is not him/herself buty the many other programmers who will have to read and maintain the code over the years to follow. So if the programmer genuinely believes that one form is clearer then its fine, or if there is a real need to optimise. > Personally, I find something like this: > > variable += something > > a lot easier to read than Fine if the something is a constant (or at least fixed at the time of assignment) but if its really: variable += something() and something() might return a NULL or non numeric value then you have a much harder bug to find than if you split it. > For me, it's just another variable I have to worry about > allocating/deallocating/seeing if it's used anywhere > else/accidentally using when I shouldn't. If its not a pointer you don;t need to worry about allocation. As for usage, yes that's an issue but a well chosen name helps prevent misuse (unless you have psychopathically destructive programmers!). Unless you are programming a microcontroller the amount of memory taken up by an int or long in C is hardly ever an issue. > ...James asked about memory management Yes, but specifically about dynamic memory(pointers) not static. > ...depending on the program you're using and the size > of your inputs, it actually can make a difference. Absolutely, and as I said, you can optimise C to the point of obscurity but you should only do so once you have proved that there really is a need and after trying other techniques like redesigning your data structures and algorithms. Fine tuning code should be the last resort not the first. And often it's better to drop into assembler for the critical section. Clear assembler is much easier to maintain than obscure C. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri May 27 01:37:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 00:37:46 +0100 Subject: [Tutor] Python Interview Questions.. References: <143576.33767.qm@web121816.mail.ne1.yahoo.com><4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: "Prasad, Ramit" wrote > Is C still the standard interviewing basis for the computer > science basics (e.g. data structures, algorithms, etc)? In the UK at least it is almost universally Java nowadays. C (and C++) are still yused in industrial settings, especially in embedded systems, but Java has come to dominate academia and busness applications. Alan g. From alan.gauld at btinternet.com Fri May 27 01:44:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 00:44:40 +0100 Subject: [Tutor] Python Extensions in C References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> Message-ID: "James Reynolds" wrote > I'll look into your suggestion regarding comprehension (i'm not sure > what > that means in a programing sense, but I'm sure I'll find out!) Its the English meaning of the word. Studies have shown that the layout of code (indentation, placement of braces etc) have a big effect on how well readers understand code. Keeping blocks of code at a single level is one of the big plus points. So code that looks like XXXXXXXXXXXXX X XXXXXXXX X is less well understood by readers than the same code that looks like XXXXXXXXXXXXX X XXXXXXXX X Or XXXXXXXXXXXX X XXXXXXXX X Its all to do with the number of levels of complexity perceived by the eye/brain. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri May 27 01:50:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 00:50:39 +0100 Subject: [Tutor] Python Extensions in C References: <1907EE83-B790-42E3-A6C6-0538D29F8035@gmail.com> Message-ID: "James Reynolds" wrote > As far as the null point goes, it shouldn't be null at all once it > gets to > the point Alan pointed out. The pointer is set in (for example) > stat_avg > > seq = PySequence_Fast(obj, "Expected a Sequence"); Can the function fail? If so what does it return? That was my point. Can seq ever still be NULL after the function call? For example if the function is allocating memory it could fail to grab enough and then return a NULL.... But it depends on how reliable the Python function is in its return value... > But maybe I am missing something that you have seen? Don't rely on functio returns being valid values. It is common practice in industrial strength C to return a NULL and expect the user to check. Manyb of the standard library functions work that way too. So you often see code like if (foo = someFunction() ){ // notice it is an assignment not equality test process(foo); } HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri May 27 02:04:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 01:04:49 +0100 Subject: [Tutor] Non programmer wanting to become programmer References: Message-ID: "amt" <0101amt at gmail.com> wrote > 1)What book should I start with? ( I have checked Python for non > programmers but there are a lot of titles there, what should I pick > first?I > was thinking about Invent your own computer games with Python.) Tutorials are a matter of taste. Take a look at a few, find one that seems clear to you and stick with it. Try the examples out don't just read them. If you get stuck try reading about the same topic in another tutorial. If still stuck ask here. > 2)Version 2 or version 3? What should I go for as a beginner and > why? It doesn't make a lot of difference. Version 3 is still lacking support for some important modules so if you had a specific task in mind I'd say stick with v2. But as a complete beginner you are unlikely to be affected by that and hopefully the module providers will have caught up by the time you are ready for them. If you like the look of the v3 tutor then go for it. > 3)Algorithms, memory management, data structures, when is the right > time to > learn them? Algorithms are best learned in math class, but since that may not be an option, learn as you go by tackling problems and by reading other peoples code and by researching on Wikipedia etc. memory management is almost irrelevant in Python, the interpreter does it for you. data structures in the traditional sense are likewise largely unnecessary in Python because the ones that come as standard are so powerful you can do most things with them. So again learn about them as you go, and wikipedia is once again your friend. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Fri May 27 02:09:25 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 26 May 2011 17:09:25 -0700 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, May 26, 2011 at 4:37 PM, Alan Gauld wrote: > > "Prasad, Ramit" wrote > > Is C still the standard interviewing basis for the computer science basics >> (e.g. data structures, algorithms, etc)? >> > > In the UK at least it is almost universally Java nowadays. > > C (and C++) are still yused in industrial settings, especially in embedded > systems, but Java has come to dominate academia and busness applications. > > Which, as Joel Spolsky has famously pointed out, is not universally a Good Thing: http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html And, back to the OP's original question, Joel also wrote "The Guerrilla Guide to Interviewing." I'd hate to give the impression that all earthly wisdom flows from Joel, but he makes some excellent points; even if you're the job applicant rather than the person doing the hiring, I definitely recommend reading it: http://www.joelonsoftware.com/articles/GuerrillaInterviewing3.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri May 27 02:07:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 01:07:50 +0100 Subject: [Tutor] Non programmer wanting to become programmer References: <786334.25188.qm@web130202.mail.mud.yahoo.com> Message-ID: "michael scott" wrote Alan's tutorial (alan is a very active member here) http://www.freenetpages.co.uk/hp/alan.gauld/ Note the new site in my sig... It has a lot of buglets fixed for v2 and importantly has a v3 version too (albeit still under construction, but complete enough for beginner purposes) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri May 27 02:19:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 01:19:46 +0100 Subject: [Tutor] nested / concatenated function docstrings? References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA44B0CAE@EMARC112VS01.exchad.jpmchase.net> Message-ID: "Prasad, Ramit" wrote > I would like to have the docstring for function first also > contain the docstring for second because it should > support/pass any argument second contains. You can explicitly set the docstring by assigning to __doc__: >>> def f(): ... '''here is f's doc string ''' ... return 42 ... >>> def g(): ... return f() + 10 ... >>> g.__doc__ = "Here is g's help\n" + f.__doc__ >>> help(g) >>> help(g) Help on function g in module __main__: g() Here is g's help here is f's doc string >>> There may be a more elegant way but that seems to work... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri May 27 02:22:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 01:22:31 +0100 Subject: [Tutor] Python Interview Questions.. References: <143576.33767.qm@web121816.mail.ne1.yahoo.com><4DDC3648.2080809@iandouglas.com><0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: "Marc Tompkins" wrote >> ...Java has come to dominate academia and busness applications. >> >> Which, as Joel Spolsky has famously pointed out, is not universally >> a Good > Thing: Indeed, I personally dislike Java, I think it encourages some very bad programming design habits, especially in the OOP area, but sadly it is the de facto standard... (And increasingly, so are the bad habits! :-( ) Alan g. From marc.tompkins at gmail.com Fri May 27 03:15:55 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 26 May 2011 18:15:55 -0700 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, May 26, 2011 at 5:22 PM, Alan Gauld wrote: > > Indeed, I personally dislike Java, I think it encourages some very bad > programming design habits, especially in the OOP area, but sadly it is the > de facto standard... (And increasingly, so are the bad habits! :-( ) I despise it root and branch... but his point is a little different: Java just isn't a hard enough language to separate great programmers from plodders (neither is Python, for that matter) because pointers and memory allocation are taken care of automagically. When you're hiring programmers, (Joel says) you want people who understand what the computer is actually doing under all the chrome, and you want people who are smart enough to have actually passed classes where they had to do that stuff. I don't want to sound elitist - I wish everybody would learn to program, and I think Python is both a great learner's language AND a great language for Getting Stuff Done - but when you spend your hard-earned money for commercial software, or trust your computing life to an operating system, you want to know that it was written by people who knew what the hell they were doing, rather than people who scraped by in a Java School 'cause the classes weren't too hard. We've all used software that was written by non-programmers - I'm struggling with just such a system at the moment - and life is just too damn short. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Fri May 27 03:20:47 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 26 May 2011 20:20:47 -0500 Subject: [Tutor] Non programmer wanting to become programmer In-Reply-To: References: Message-ID: On Thu, May 26, 2011 at 2:36 PM, amt <0101amt at gmail.com> wrote: > First of all, hello! I want to start learning programming. I'm looking > into becoming more than a hobbyist programmer. I searched a lot on Google on > what programming language should I learn first and I see a lot of good words > about Python so I decided to go for it but have some questions: > > 1)What book should I start with? ( I have checked Python for non > programmers but there are a lot of titles there, what should I pick first?I > was thinking about Invent your own computer games with Python.) > A lot of people have mentioned their favorites, and there are plenty to like about those. If you like books, I would highly recommend this one: http://www.amazon.com/Game-Programming-Line-Express-Learning/dp/0470068221 It's well written and quite helpful, and teaches you programming in the context of game programming. If games are your thing, it's a good one - it points out many of the pitfalls that might catch you, and at the end of each chapter are assignments/questions to help you learn. Other than that, I have nothing more to add - others have given you quite solid advice. Good luck on your path to programming! (also you might be interested in this essay: http://norvig.com/21-days.html ) -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From charlze at sohu.com Fri May 27 06:46:00 2011 From: charlze at sohu.com (charlze at sohu.com) Date: Fri, 27 May 2011 04:46:00 GMT Subject: [Tutor] Could I modify codes and validate immediately without restart program? Message-ID: <1306471560.ff8ca25ab88245c6b57ae5ddf97b3053.charlze@sohu.com> Hi, guys. Here is a demo program like this: aa = 3 bb = 4 cc = 53 dd = 6 print cc I put a breakpoint at the first line, then debug the program. After 'aa' is set to '3', I modify '53' in the 3rd line to '34', then save the source file and run remain codes. As expected, the output is '53'. Does python has the ability to set cc to 34 after file savings without restarting whole program? I heard LISP has this ability and wonder how could it achieve this. Thanks! From alan.gauld at btinternet.com Fri May 27 10:59:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 09:59:25 +0100 Subject: [Tutor] Python Interview Questions.. References: <143576.33767.qm@web121816.mail.ne1.yahoo.com><4DDC3648.2080809@iandouglas.com><0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: "Marc Tompkins" wrote > Java just isn't a hard enough language to separate great programmers > from plodders (neither is Python, for that matter) because pointers > and memory allocation are taken care of automagically. I fundamentally disagree with his stand on this. > When you're hiring programmers, (Joel says) you want people > who understand what the computer is actually doing under > all the chrome, and you want people who are smart enough > to have actually passed classes where they had to do that stuff. I have employed quantum physists and geoligists who had no idea of how computers worked but they were plenty smart and made good programmers. A good programmer is someone who can think logically, analyse and abstract a problem and express it clearly in an implementation language (regardless of what language it is, they will probably use several in their career!) There is a very small set of programming tasks where you need to undertand the machine - developing an OS and device drivers etc - but they are such a small part of the industry that mostly we can be thankful that modern languages hide the machine and let us focus on the really hard stuff - understanding the customers world and translating their requirements into code. Fred Brooks identified this as far back as the 80's with his famous "No Silver Bullet" article. I started out as an electronics engineer, we wrote micro-code, then machine code then assembler and finally Pascal. Then I found C and so on. But I am profoundly grateful that I no longer have to worry about which register to store the result of an addition or which memory mode I need to use in a subroutine call. There are equally complex challenges in higher order programming than there are in programming the machine. There is a role for both, but the macho "I can do it faster in assembler" attitude that sometimes arises is no more than ignorance of the challenges elsewhere. I've worked with highly technical programmers who couldn't understand how a Corporate General Ledger accounting system worked and so couldn't program solutions for it. But they could explain in detail how the multi-threaded kernel in the computer operated. So language preferences are fine if they are based on the language features. Computing and Programming are something else again. > for Getting Stuff Done - but when you spend your hard-earned money > for > commercial software, or trust your computing life to an operating > system, > you want to know that it was written by people who knew what the > hell they > were doing, rather than people who scraped by in a Java School > 'cause the > classes weren't too hard. And this is another matter again. But if you are talking about share dealing systems or traffic control systems or factory automation I'd rather the programmer understood algorithms and the business functions than the difference between page switching and banked memory access. But I definitely want him/her to understand computing, and programming in depth. I want them to have studied the subject deeply and have a wealth of experience. Studying computing because its an easy option is not an option because its never easy. And anyone who starts down that road will be weeded out very quickly. > We've all used software that was written by non-programmers > - I'm struggling with just such a system at the moment - and > life is just too damn short. Software can only be written by programmers, its the definition of the term. The issue is about whether the programmer was trained in computing/engineering or whether it was someone who just knew a programming language. Comp Sci was originally a branch of math, and many of the best programmers I've worked with came straight into the industry from math - but they had to learn about defensive programming etc. But their algorithm design often meant they had less to defend! Seems to be my week for ranting... :-) Alan G. From alan.gauld at btinternet.com Fri May 27 11:09:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 10:09:55 +0100 Subject: [Tutor] Could I modify codes and validate immediately withoutrestart program? References: <1306471560.ff8ca25ab88245c6b57ae5ddf97b3053.charlze@sohu.com> Message-ID: wrote > Hi, guys. Here is a demo program like this: > aa = 3 > bb = 4 > cc = 53 > dd = 6 > print cc > > I put a breakpoint at the first line, then debug the program. > After 'aa' is set to '3', I modify '53' in the 3rd line to '34', > then > save the source file and run remain codes. As expected, > the output is '53'. Correct because the interpreter and debugger are running the original unmodified source file, it gets loaded into memory when the interpreer started. To do what you want it would have to read each line from the file as it went which would be horrifically slow. It also would prevent the interpreter compiling the code in memory which would add to the slowdown. > Does python has the ability to set cc to 34 after file > savings without restarting whole program? No, and I don;t know of any language than can unless you explicitly reload the code. But that is usually a feature of the debugger/interpreter rather than the language. For example I worked ona C++ IDE a few years ago that allowed you to change code and reload and continue running. I've seen debuggers that let you step through code in reverse. All very clever but nothing to do with the language. And of course you could change the value of your variable in the debugger by setting a breakpoint immediately after the assignment. But that doesn't change the source code. > I heard LISP has this ability and wonder how could it > achieve this. Lisp a a language does not, but some Lisp interpreters or debuggers may well be able to reload a program in-flight. It's not in the language it's in the tools. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri May 27 11:15:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 10:15:11 +0100 Subject: [Tutor] Python Interview Questions.. References: <143576.33767.qm@web121816.mail.ne1.yahoo.com><4DDC3648.2080809@iandouglas.com><0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: "Alan Gauld" wrote > of the term. The issue is about whether the programmer was > trained in computing/engineering or whether it was someone > who just knew a programming language. And I meant to add that this includes learning about the virtual machine - the execution environment, the differences between interpreted and compiled code etc. Also understanding OS concepts like scheduling and file systems etc are necessary. It's just the low level memory management/register access type stuff that I don't believe is necessary. And I do agree that we are seeing "programmers" who don't understand the basics of computing even at a user level and that is not good in an industry concept. It's fine for hobbyists but not for industrial grade programming. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Fri May 27 11:34:19 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 27 May 2011 17:34:19 +0800 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: May I direct the interview question to another direction? are there some tests (I mean, just like the examination test) of python for beginner? which asked some basic but important questions (I do not want to learn python all of the stuff, it might be so huge for me.) and most important those practice gave answers. I learned it on and off and hard to achieve something (I mean practice in daily working). But got a wish to learn. so any advice will be highly appreciated. Thanks, On Fri, May 27, 2011 at 5:15 PM, Alan Gauld wrote: > > "Alan Gauld" wrote >> >> of the term. The issue is about whether the programmer was >> trained in computing/engineering or whether it was someone >> who just knew a programming language. > > And I meant to add that this includes learning about the virtual machine - > the execution environment, the differences between interpreted and compiled > code etc. Also understanding OS concepts like scheduling and file systems > etc are necessary. It's just the low level memory management/register access > type stuff that I don't believe is necessary. > > And I do agree that we are seeing "programmers" who don't understand the > basics of computing even at a user level > and that is not good in an industry concept. It's fine for hobbyists but not > for industrial grade programming. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Best Regards, lina From wprins at gmail.com Fri May 27 12:31:36 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 27 May 2011 11:31:36 +0100 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 27 May 2011 09:59, Alan Gauld wrote: > "Marc Tompkins" wrote > >> Java just isn't a hard enough language to separate great programmers >> >> from plodders (neither is Python, for that matter) because pointers >> and memory allocation are taken care of automagically. >> > > I fundamentally disagree with his stand on this. > > Not sure what you're saying here Alan -- are you saying you consider Java "hard enough language to seperate great programmers from plodders" or are you saying that you don't agree with the distinction drawn (that some programmers are plodders and others are not) or what? > > When you're hiring programmers, (Joel says) you want people >> who understand what the computer is actually doing under >> all the chrome, and you want people who are smart enough >> to have actually passed classes where they had to do that stuff. >> > > I have employed quantum physists and geoligists who had no > idea of how computers worked but they were plenty smart and > made good programmers. > > A good programmer is someone who can think logically, > analyse and abstract a problem and express it clearly in > an implementation language (regardless of what language > it is, they will probably use several in their career!) > > Well, FWIW I would tend to side with Joel/Marc on this one (depending on interpretation of what you're both saying -- maybe I fall somewhere in the middle... whatever...) To try and clarify, I'd perhaps rephrase/paraphrase their view as, "you want people who have some understanding of how the code you've written will actually ends up being executed by the computer in terms of the effective time and space complexity (as well as other potentially problematic aspects) of the code." To me that seems to be a largely isomorphic expression of what they're saying and perhaps closer to what they're actually trying to get at. Either way, the point I'm trying to make is that even if you have for example some awareness of the /apparent/ time/space complexity of *your* code, it's still very easy to fall into a "Schlemiel painter's" type algorithm by not really having an understanding of how (for example) some of the libraries or basic functionality of the language you're using are implemented. To belabor the point: The same pseudocode/algorithm realised in 2 different languages can have wildly different performance characteristics depending on the nature of the underlying languages and the exact form of the realisation. And you as programmer will never even know unless you have a more than superficial understanding of the language you program in and have some awareness that these types of issues exist and what the different performance characteristics of various algorithm classes are. And yet, many programmers don't apparently have even a superficial awareness of attributes of the code that they write, never mind how a such a superficial analysis (e.g. ignoring the platform/language) may differ from what really happens when executed, and why such a difference exists. Anyway, best regards and have a good weekend all, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri May 27 13:46:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 27 May 2011 21:46:27 +1000 Subject: [Tutor] Clunky Password maker In-Reply-To: References: Message-ID: <201105272146.27560.steve@pearwood.info> On Thu, 26 May 2011 05:45:30 am Alan Gauld wrote: [...] > using > the choice() function from the whrandom module. > > passwd = [whrandom.choice(series) for n in range(p)] whrandom was deleted in Python 2.5! I'm not sure when it was formally deprecated, but the recommended way of getting random numbers has been the random module all the way back to version 1.5! Since version 2.3, Python has been using the Mersenne Twister as the default random number generator, instead of Wichmann-Hill. Mersenne Twister is *much* better and stronger than WH. -- Steven D'Aprano From 0101amt at gmail.com Fri May 27 13:51:05 2011 From: 0101amt at gmail.com (amt) Date: Fri, 27 May 2011 14:51:05 +0300 Subject: [Tutor] Non programmer wanting to become programmer In-Reply-To: References: Message-ID: Thank you all for the replies. They helped me a lot. Have a great weekend! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri May 27 13:54:20 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 27 May 2011 21:54:20 +1000 Subject: [Tutor] Cherrypy In-Reply-To: <4DDD0F25.4050302@tznic.or.tz> References: <4DDD0F25.4050302@tznic.or.tz> Message-ID: <201105272154.21059.steve@pearwood.info> On Thu, 26 May 2011 12:16:05 am Bryton wrote: > Is anyone having a step by step tutorial of cherrypy(or book title).I > have used the tutorial in their site as well as the book (cherrypy > essentials) and I would like to have a one that is a bit more step by > step...Please help... Sorry Bryton, I don't know any. Have you googled to see what is available? -- Steven D'Aprano From steve at pearwood.info Fri May 27 14:06:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 27 May 2011 22:06:01 +1000 Subject: [Tutor] Python Variables Changing in Other Functions In-Reply-To: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> References: <0C68398F-F930-4628-9103-FAED6D58FB13@gmail.com> Message-ID: <4DDF93A9.5030002@pearwood.info> Rachel-Mikel ArceJaeger wrote: > Hello, > > I am having trouble with determining when python is passing by reference and by value Others have already discussed this, but at the risk of blowing my own trumpet, I'd like to point you at an earlier discussion on this list: http://mail.python.org/pipermail/tutor/2010-December/080505.html -- Steven From ajarncolin at gmail.com Fri May 27 15:41:24 2011 From: ajarncolin at gmail.com (col speed) Date: Fri, 27 May 2011 20:41:24 +0700 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 27 May 2011 17:31, Walter Prins wrote: > > > I find this thread very interesting. > I've been learning Python on and off for the past 3 years, as a hobby. I am over 50 years old, so will never be a programmer. However: 1/ I've done a bit in Project Euler and have found many algorithms to get prime numbers. There is one that is 10 times faster than any other that I have found, it uses numpy. Unfortunately, I don't understand it at all. However, neither would I understand Python's sort method, but I still use it. 2/ I used be able to take a car to pieces and put it back together. Today, I wouldn't stand a chance. I suppose that what I'm trying to say is that there will always be a need for "experts" that know different OS's and how a computer works inside, and there will also be a need for coders who code a programme that is needed at a certain time. Is there really a time that knowing that "list" is interpreted as "10010001000100010010000100010010" is important these days? Please flame me -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From sulinet at postafiok.hu Fri May 27 15:52:09 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Fri, 27 May 2011 15:52:09 +0200 Subject: [Tutor] Creating a dictionary Message-ID: Hi, I think I am new to here, as far as I remember. :-) http://docs.python.org/dev/library/stdtypes.html#dict says: we can create a dictionary with - dict({'one': 1, 'two': 2}) What is the adventage of this form to simply writing d = {'one': 1, 'two': 2}? Is there any difference? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Fri May 27 16:05:20 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Fri, 27 May 2011 19:35:20 +0530 Subject: [Tutor] Creating a dictionary In-Reply-To: References: Message-ID: The first approach does not really give you any variable (in easy form) to operate upon. The second approach returns a dict object that you can later reuse in easier form. So one advantage is certainly that ease of object reuse and also object modification. If you want to add, remove, update anything in the dict object, the second syntax is easier. You can also make it part of a class or module. You can pass it to a function as well. Regards SWP 2011/5/27 V?las P?ter > Hi, > I think I am new to here, as far as I remember. :-) > > http://docs.python.org/dev/library/stdtypes.html#dict says: > we can create a dictionary with > > - dict({'one': 1, 'two': 2}) > > What is the adventage of this form to simply writing d = {'one': 1, 'two': 2}? > Is there any difference? > > Thanks > > _______________________________________________ > 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 sulinet at postafiok.hu Fri May 27 16:19:08 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Fri, 27 May 2011 16:19:08 +0200 Subject: [Tutor] Creating a dictionary In-Reply-To: References: Message-ID: Sorry, I am afraid, I was not clear enough. So what is the difference between d = dict({'one': 1, 'two': 2}) and d = {'one': 1, 'two': 2} ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Fri May 27 16:31:24 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Fri, 27 May 2011 20:01:24 +0530 Subject: [Tutor] Creating a dictionary In-Reply-To: References: Message-ID: I think the way - d = dict({'one': 1, 'two': 2}) can be used to created dictionary using list comprehension. e.g. >>> d = dict((i,i**2) for i in range(10)) >>> d {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} I do not think the second approach can be used in this fashion. >From python documentation - http://docs.python.org/tutorial/datastructures.html The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key-value list. I am not an expert. So may be someone can explain it better. Regards SWP 2011/5/27 V?las P?ter > Sorry, I am afraid, I was not clear enough. So what is the difference > between > d = dict({'one': 1, 'two': 2}) > and > d = {'one': 1, 'two': 2} > ? > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri May 27 16:34:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 May 2011 00:34:00 +1000 Subject: [Tutor] Creating a dictionary In-Reply-To: References: Message-ID: <4DDFB658.9020309@pearwood.info> V?las P?ter wrote: > Hi, > I think I am new to here, as far as I remember. :-) > > http://docs.python.org/dev/library/stdtypes.html#dict says: > we can create a dictionary with > > - dict({'one': 1, 'two': 2}) > > What is the adventage of this form to simply writing d = {'one': 1, 'two': 2}? > Is there any difference? dict() is a function (technically, a type) that creates new dictionaries from whatever argument you pass to it. { ... } is syntax for creating literal dictionaries. Think of this as similar to the difference between a mathematical expression: x = 2*9-1 and a number literal: x = 17 HOWEVER, in the above example with dict(), the form shown is redundant. dict({'one': 1, 'two': 2}) does these four steps: (a) Python creates a dictionary using the "dict literal" syntax {'one': 1, 'two': 2} (b) That dictionary is then passed to the dict() function (c) The dict() function makes a copy of that dictionary and returns it (d) Python's garbage collector deletes the original dictionary. Never put a lone dict literal {...} inside a call to dict(), that's just a waste of time. Just use the literal on its own. dict() *can* be very useful, just not in the example shown. You can use it to make copies of other dicts: first_dict = {'one': 1, 'two': 2} second_dict = dict(first_dict) That's not very interesting, as you can easily make a copy with first_dict.copy() instead. But it gets more interesting if you want to add new items to the dictionary: third_dict = dict(first_dict, three=3, four=4) You can even leave out the original dict: fourth_dict = dict(a=1, b=2, c=3) or instead use a list of (key, value) pairs: items = [('a', 1), ('b', 2), ('c', 3)] fifth_dict = dict(items, d=4) -- Steven From delegbede at dudupay.com Fri May 27 16:36:15 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Fri, 27 May 2011 14:36:15 +0000 Subject: [Tutor] Creating a dictionary In-Reply-To: References: Message-ID: <400064096-1306506950-cardhu_decombobulator_blackberry.rim.net-736302600-@b1.c12.bise7.blackberry> The first instance is more keystrokes while the second saves u that. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: V?las P?ter Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Fri, 27 May 2011 16:19:08 To: Cc: Subject: Re: [Tutor] Creating a dictionary _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From sulinet at postafiok.hu Fri May 27 16:36:29 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Fri, 27 May 2011 16:36:29 +0200 Subject: [Tutor] Creating a dictionary In-Reply-To: References: Message-ID: 2011. m?jus 27. 16:31 ?rta, : > I think the way - d = dict({'one': 1, 'two': 2}) can be used to created > dictionary using list comprehension. > e.g. > >>> d = dict((i,i**2) for i in range(10)) > > I think this is not the same syntax, there are no braces in. dict({'one': 1, 'two': 2}) rather seems to me as a converting function that creates a dictionary from a dictionary. Thank you anyway! -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Fri May 27 16:37:45 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 27 May 2011 15:37:45 +0100 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: Hi Colin, On 27 May 2011 14:41, col speed wrote: > I've been learning Python on and off for the past 3 years, as a hobby. > I am over 50 years old, so will never be a programmer. However: > Well just because you're 50 years old doesn't mean you will never be a programmer ;) > 1/ I've done a bit in Project Euler and have found many algorithms to get > prime numbers. There is one that is 10 times faster than any other that I > have found, it uses numpy. Unfortunately, I don't understand it at all. > However, neither would I understand Python's sort method, but I still use > it. > It's this awareness (that you clearly already have0 that I submit is often (sadly) lacking in many programmers. So there mere fact that you're pointing this out tells me that you already have, at least, a feel/awareness that not all algorithms are equal, regardless of whether you understand why/how. > I suppose that what I'm trying to say is that there will always be a need > for "experts" that know different OS's and how a computer works inside, and > there will also be a need for coders who code a programme that is needed at > a certain time. > > Is there really a time that knowing that "list" is interpreted as > "10010001000100010010000100010010" is important these days? > No, but that wasn't IMHO the point being made. It's more about how (for example) lists in general behave (e.g. having at least a feel for the cost of various operations etc) and (by contrast) also how **Python's** list implementation behaves (which is not the same as a classical linked list. Python lists (CPython at least) are IIRC actually implemented as dynamic arrays of pointers, which means that some operations don't cost as much as they would do with a "true" nodular linked list implementation, while other operations cost more etc. etc.) Best wishes (hoping this was not perceived as a flame as it wasn't intended as one!) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Fri May 27 16:40:24 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Fri, 27 May 2011 14:40:24 +0000 Subject: [Tutor] Creating a dictionary In-Reply-To: References: Message-ID: <1618618823-1306507208-cardhu_decombobulator_blackberry.rim.net-2042539239-@b1.c12.bise7.blackberry> Nice observation Spawgi. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: spawgi at gmail.com Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Fri, 27 May 2011 20:01:24 To: V??las P??ter Cc: Subject: Re: [Tutor] Creating a dictionary _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Fri May 27 16:40:54 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 May 2011 16:40:54 +0200 Subject: [Tutor] Creating a dictionary References: Message-ID: V?las P?ter wrote: > I think I am new to here, as far as I remember. :-) > > http://docs.python.org/dev/library/stdtypes.html#dict says: > we can create a dictionary with > > - dict({'one': 1, 'two': 2}) > > What is the adventage of this form to simply writing d = {'one': 1, 'two': > 2}? Is there any difference? That is meant to illustrate that you can create a dictionary from another one by passing the existing dictionary to dict(). A more realistic example is >>> friends = {"Jim": 42, "Jack": 18} >>> family = {"Sue": 7, "Eli": 30} >>> friends_and_family = dict(friends) >>> friends_and_family.update(family) >>> friends_and_family {'Eli': 30, 'Sue': 7, 'Jim': 42, 'Jack': 18} From sulinet at postafiok.hu Fri May 27 16:47:58 2011 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Fri, 27 May 2011 16:47:58 +0200 Subject: [Tutor] Creating a dictionary In-Reply-To: <4DDFB658.9020309@pearwood.info> References: <4DDFB658.9020309@pearwood.info> Message-ID: 2011/5/27 Steven D'Aprano > Never put a lone dict literal {...} inside a call to dict(), that's just a > waste of time. Just use the literal on its own. > That's what I thought about this, I just didn't want to believe that docs.python.org wrote a redundant example. > third_dict = dict(first_dict, three=3, four=4) > > Thank you, these were useful examples! P. -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Fri May 27 16:47:55 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Fri, 27 May 2011 20:17:55 +0530 Subject: [Tutor] Creating a dictionary In-Reply-To: <4DDFB658.9020309@pearwood.info> References: <4DDFB658.9020309@pearwood.info> Message-ID: Thanks for the detailed explanation Steve. That was very helpful. On Fri, May 27, 2011 at 8:04 PM, Steven D'Aprano wrote: > V?las P?ter wrote: > >> Hi, >> I think I am new to here, as far as I remember. :-) >> >> http://docs.python.org/dev/library/stdtypes.html#dict says: >> we can create a dictionary with >> >> - dict({'one': 1, 'two': 2}) >> >> What is the adventage of this form to simply writing d = {'one': 1, 'two': >> 2}? >> Is there any difference? >> > > dict() is a function (technically, a type) that creates new dictionaries > from whatever argument you pass to it. { ... } is syntax for creating > literal dictionaries. Think of this as similar to the difference between a > mathematical expression: > > x = 2*9-1 > > and a number literal: > > x = 17 > > > HOWEVER, in the above example with dict(), the form shown is redundant. > dict({'one': 1, 'two': 2}) does these four steps: > > (a) Python creates a dictionary using the "dict literal" syntax > {'one': 1, 'two': 2} > (b) That dictionary is then passed to the dict() function > (c) The dict() function makes a copy of that dictionary and returns it > (d) Python's garbage collector deletes the original dictionary. > > Never put a lone dict literal {...} inside a call to dict(), that's just a > waste of time. Just use the literal on its own. > > dict() *can* be very useful, just not in the example shown. You can use it > to make copies of other dicts: > > > first_dict = {'one': 1, 'two': 2} > second_dict = dict(first_dict) > > > That's not very interesting, as you can easily make a copy with > first_dict.copy() instead. But it gets more interesting if you want to add > new items to the dictionary: > > > third_dict = dict(first_dict, three=3, four=4) > > > You can even leave out the original dict: > > > fourth_dict = dict(a=1, b=2, c=3) > > > or instead use a list of (key, value) pairs: > > > items = [('a', 1), ('b', 2), ('c', 3)] > fifth_dict = dict(items, d=4) > > > > -- > Steven > > > _______________________________________________ > 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 marc.tompkins at gmail.com Fri May 27 18:51:34 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 27 May 2011 09:51:34 -0700 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Fri, May 27, 2011 at 1:59 AM, Alan Gauld wrote: > > I want them to have studied the subject deeply and have a wealth of > experience. Studying computing because its an easy option is not an option > because its never easy. That was the point that Joel and I were making. The CS programs that have become Java schools now make the curriculum as easy as possible because they used to flunk lots of students, or lose them to other majors - they obviously saw that as a Bad Thing, but it actually wasn't. A degree from a school that flunks a lot of students actually means something; a degree from a school where everybody passes is about as meaningful as a Participation trophy. > And anyone who starts down that road will be weeded out very quickly. Not quickly enough! They should be weeded out IN SCHOOL, or before they even commit to a computer-science track. It's cruel to students, inefficient for business, and disastrous for consumers if they don't get weeded out until they're already employed as programmers. > Software can only be written by programmers, its the definition of the > term. You knew what I meant; don't be coy. Anybody with a wrench and some pipe is a plumber. Doesn't mean I'm letting him work on my dishwasher. The point I was trying to make, which apparently I didn't state clearly enough, was: Professional programmers - I really supported the effort, years back, to protect the term "software engineer" - should be familiar with the ins and outs of computers, not just with the quirks of the language they are employed to use. To use my dishwasher analogy from a moment ago, I'm sure we've all been visited by the appliance repairman (or auto mechanic, or whatever) who only knows how to replace a single component, and who therefore sees every malfunction as requiring a new control board. I don't want him either! I want the guy who's worked on lots of appliances - not just dishwashers, not just my model - because he's going to have a better idea of how it all works when it's working, and what can go wrong when it's not. At the same time - coming back to the theme of this group - I'm enthusiastic about the idea of people learning to fix their own dishwashers, and - if they love it, and get really good at it - becoming employed as appliance repair professionals. I have now officially over-worked this analogy. There were a couple of other points I wanted to answer, but I'm out of time. It does seem that we mostly agree - certainly we agree that Java stinks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Fri May 27 19:24:17 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Fri, 27 May 2011 13:24:17 -0400 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Fri, May 27, 2011 at 12:51 PM, Marc Tompkins wrote: > That was the point that Joel and I were making.? The CS programs that have > become Java schools now make the curriculum as easy as possible because they The concept that knowledge/ability to use a language doesn't indicate quality is one I agree with. however: > enough, was: Professional programmers - I really supported the effort, years > back, to protect the term "software engineer" - should be familiar with the > ins and outs of computers, not just with the quirks of the language they are > employed to use.? To use my dishwasher analogy from a moment ago, I'm sure Here I disagree. A certain level of base knowledge beyond the requirements of your language is required, true, but a) I think that can be taken too far. I suspect a ton of truly great programmers have never have to memalloc() and they are still good. b) I think this is placing the cart before the horse. To expand on that second point, I see a good programmer as someone that thinks abstractly, that can bounce between big picture and details, that considers concepts like reuse and flexibility without extra effort. They are lazy enough to want to take advantage of existing libraries and diligent enough to fix things the first time. They have curiosity and insight. A person like that will, in time, learn enough about the environment and foundations of their tools to reap all possible benefit from it. Studying those foundations will not make you one of those people, nor will testing for knowledge of those foundations necessarily find you one of those people. And, frankly, I suspect a great many of those people will never wrestle with when exactly their compiler performs tail call elimination. But that's just my suspicion. > There were a couple of other points I wanted to answer, but I'm out of > time.? It does seem that we mostly agree - certainly we agree that Java > stinks! One issue I've not seen discussed is some of the specific habits the language encourages. I've never been one to trash a language, believing it's a poor workman that blames his tools, and that almost all tools have their strengths, but having worked with Java (and Java developers) for a while now I've really come to dislike some of the practices that are becoming common: Stacked patterns without understanding the purpose, premature and excessive abstraction, elimination of verbs, and horrendous naming habits. I'm curious to see if any of these habits change if/when Java adds functions as first-class objects. -- Brett Ritter / SwiftOne swiftone at swiftone.org From ramit.prasad at jpmchase.com Fri May 27 19:36:13 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Fri, 27 May 2011 13:36:13 -0400 Subject: [Tutor] Could I modify codes and validate immediately withoutrestart program? In-Reply-To: References: <1306471560.ff8ca25ab88245c6b57ae5ddf97b3053.charlze@sohu.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA44B1A4B@EMARC112VS01.exchad.jpmchase.net> >> Does python has the ability to set cc to 34 after file >> savings without restarting whole program? >No, and I don;t know of any language than can unless >you explicitly reload the code. But that is usually a >feature of the debugger/interpreter rather >than the language. It is not quite the same, but there are debuggers (not sure about for Python) that will let you change the *in memory* value of cc on the fly. Of course, any code change will still not work. Eclipse's Java debugger will let you do small changes "on the fly" while paused; it will restart from the beginning of the function, but more often than not it will say "could not replace" because the criteria that is allowed for "on the fly" changes is *very* narrow. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From ramit.prasad at jpmchase.com Fri May 27 19:45:53 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Fri, 27 May 2011 13:45:53 -0400 Subject: [Tutor] nested / concatenated function docstrings? In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA44B0CAE@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA44B1A8D@EMARC112VS01.exchad.jpmchase.net> I knew I could set the docstring (and played with it) but I did not realize that would work when the function is imported from a module! Thank you, Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Alan Gauld Sent: Thursday, May 26, 2011 7:20 PM To: tutor at python.org Subject: Re: [Tutor] nested / concatenated function docstrings? "Prasad, Ramit" wrote > I would like to have the docstring for function first also > contain the docstring for second because it should > support/pass any argument second contains. You can explicitly set the docstring by assigning to __doc__: >>> def f(): ... '''here is f's doc string ''' ... return 42 ... >>> def g(): ... return f() + 10 ... >>> g.__doc__ = "Here is g's help\n" + f.__doc__ >>> help(g) >>> help(g) Help on function g in module __main__: g() Here is g's help here is f's doc string >>> There may be a more elegant way but that seems to work... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From alan.gauld at btinternet.com Fri May 27 19:51:44 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 27 May 2011 18:51:44 +0100 (BST) Subject: [Tutor] nested / concatenated function docstrings? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA44B1A8D@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA44B0CAE@EMARC112VS01.exchad.jpmchase.net> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA44B1A8D@EMARC112VS01.exchad.jpmchase.net> Message-ID: <104618.34406.qm@web86706.mail.ird.yahoo.com> > I knew I could set the docstring (and played with it) but I did > not realize that would work when the function is imported > from a module! You are changing the doc string of the function in the same module, you couldn't change the docstring of a function in another module - or at least not permanently. Thank you, Ramit -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri May 27 20:08:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 19:08:31 +0100 Subject: [Tutor] Python Interview Questions.. References: <143576.33767.qm@web121816.mail.ne1.yahoo.com><4DDC3648.2080809@iandouglas.com><0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: "Walter Prins" wrote >>> Java just isn't a hard enough language to separate great >>> programmers >>> from plodders (neither is Python, for that matter) because >>> pointers >>> and memory allocation are taken care of automagically. >> >> I fundamentally disagree with his stand on this. >> > Not sure what you're saying here Alan -- are you saying you consider > Java > "hard enough language to seperate great programmers from plodders" Yes, I'm saying the language just isn't that significant. > you saying that you don't agree with the distinction drawn (that > some > programmers are plodders and others are not) or what? No, there are plodders and greats, but I'm disagreeing about what constitutes great. >> When you're hiring programmers, (Joel says) you want people >>> who understand what the computer is actually doing under >>> all the chrome, Thats where I disagree, you might occasionally need a few of those, but not often and not many. > you want people who are smart enough to have actually > passed classes where they had to do that stuff. And I do want them to have studied the subject and be qualified - either by exam or by experience. > their view as, "you want people who have some understanding of how > the code > you've written will actually ends up being executed by the computer > in terms > of the effective time and space complexity (as well as other > potentially > problematic aspects) of the code." The efficiency of an algorithm is one thing. The way a computer executes it? That's much harder to guess since much depends on the compiler/interpreter. A good algorithm is usually independant of those things. (So an algorithm that creates zillions of objects in memory is a bad algorithm and you need to be aware of the impact, but you don't usually need to be aware of how the computer is creating those in memory.) > point: The same pseudocode/algorithm realised in 2 different > languages can > have wildly different performance characteristics depending on the > nature of > the underlying languages and the exact form of the realisation. I would say slight differences depending on language, the same algorithm will generally have the same *relative* performance regardless of language. The quality of the optimiser is likely to be far more important. And in most real world scenarios the quality of data structure design and database choice and network usage are far more likely to cause performance issues than the code. I'd rather have someone who can design a good code structure than someone who can write "tight" code any day. > programmer will never even know unless you have a more > than superficial understanding of the language you program > in and have some awareness that these types of issues exist I'd have agreed with that 10-15 years ago. Nowadays thats rarely an issue. I haven't had to deal with those kind of issues in a project for at least 10 years. I've had lots of performamce issues to resolve, but the code is the last place I look. > what the different performance characteristics of various > algorithm classes are. Here we agree. Redesigning the algorithm (and the data structures) are far more likely to solve a performance issue than tightening the code to suit the CPU characteristics. Tightening code can save a few seconds tightening the algorithm/data will save minutes or even hours. Alan G. From alan.gauld at btinternet.com Fri May 27 20:16:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 19:16:07 +0100 Subject: [Tutor] Clunky Password maker References: <201105272146.27560.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote > whrandom was deleted in Python 2.5! Well, I'm using 2.5 but I confess I didn't try it, I looked up my O'Reilly Python standard Library book because I already had it to hand. It obviously predates 2.5! :-) Alan G. From alan.gauld at btinternet.com Fri May 27 20:18:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 May 2011 19:18:13 +0100 Subject: [Tutor] Could I modify codes and validateimmediately withoutrestart program? References: <1306471560.ff8ca25ab88245c6b57ae5ddf97b3053.charlze@sohu.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA44B1A4B@EMARC112VS01.exchad.jpmchase.net> Message-ID: "Prasad, Ramit" wrote > It is not quite the same, but there are debuggers > (not sure about for Python) that will let you change the > *in memory* value of cc on the fly. Yes Pythons debugger can set a variable value during a break. But the OP wanted to do it in the source file not in memory. > Of course, any code change will still not work. And that was the problem. And a reload() would restart the code from the start. Alan G. From steve at pearwood.info Sat May 28 05:38:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 May 2011 13:38:06 +1000 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4DE06E1E.7010704@pearwood.info> Marc Tompkins wrote: >> And anyone who starts down that road will be weeded out very quickly. > > Not quickly enough! They should be weeded out IN SCHOOL, or before they > even commit to a computer-science track. It's cruel to students, > inefficient for business, and disastrous for consumers if they don't get > weeded out until they're already employed as programmers. I'd like to point out a blog post by Jeff Atwood asking why programmers can't program. Not program well, but program *at all*. http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html Actually, the blog post title is provocatively wrong, since Jeff isn't *actually* saying that 99.5% of working programmers can't program, but that 99.5% of applicants for programming jobs can't write a simple beginner program. Or sometimes even a single line of code. (The correct figure for working programmers is more like 80% *wink*) Hilariously, about half the people writing in to say they easily solved the FizzBuzz problem actually *got it wrong*. One commenter defended the can't-program-programmers by saying: "The people who couldn't solve the fizzbuzz test you describe in your article, might be great at solving well defined problems." Presumably he meant well-defined problems *except* the fizzbuzz problem. Follow the links in Jeff's post for more controversy, hilarity and/or analysis of the problem of finding good programmers. >> Software can only be written by programmers, its the definition of the >> term. > > > You knew what I meant; don't be coy. Anybody with a wrench and some pipe is > a plumber. Doesn't mean I'm letting him work on my dishwasher. Not here in Australia you're not. You can only call yourself a plumber if you are properly licensed and certified. That usually means having gone through *at least* a five(?) year apprenticeship and that they at least know that water flows downhill. > The point I was trying to make, which apparently I didn't state clearly > enough, was: Professional programmers - I really supported the effort, years > back, to protect the term "software engineer" - should be familiar with the > ins and outs of computers, not just with the quirks of the language they are Well, that depends on what you mean by "familiar". I like to think that any good programmer should understand that there *are* hardware issues to consider, even if they don't actually know how to consider them. They should know about Big Oh notation, and be able to explain in general terms why bubblesort is so slow and quicksort is usually fast but sometimes becomes slow. If they can actually calculate the best/worst/ average Big Oh running times for a function, that's a bonus. A good programmer should be aware that hardware caches invalidation will make your code run slow, even in a high-level language like Python. A *great* programmer will be able to tell you exactly which code will invalidate the hardware cache, and what to do to stop it. But let's not mistake ignorance with stupidity. An ignorant programmer may have merely never learned about the difference between O(1) and O(2**n) running times, by some accident of education and work experience, but still be a good programmer. A stupid programmer still writes Shlemiel the painter's algorithms even after having them pointed out again and again. http://www.joelonsoftware.com/articles/fog0000000319.html > employed to use. To use my dishwasher analogy from a moment ago, I'm sure > we've all been visited by the appliance repairman (or auto mechanic, or > whatever) who only knows how to replace a single component, and who > therefore sees every malfunction as requiring a new control board. I don't > want him either! Not such a good analogy, since modern consumer goods are getting to the point where they are almost unrepairable except by replacing the control board. It often costs you *more* to fix a broken widget than to throw the machine away and buy a new one, e.g. monitors, TVs, DVD players... That's also often the case with computers unless you value your time very low. In my day job, if I have the choice in paying one of my junior techs more than 4 hours to diagnose a flaky piece of hardware, I'd rather just hit it with a hammer and replace the likely suspects (memory, motherboard... whatever is likely to be causing the symptoms). Obviously its a sliding scale -- I don't replace a$14,000 server because a hard drive is broken, but neither do I spend three days trying to be absolutely 100% sure that a $60 power supply is flaky before replacing it. Coming back to programming, sometimes the right answer is to throw more memory at a problem rather than to write better code. A GB of RAM costs, what,$100? That's like what, 1-3 hours of developer time? If it takes you three hours to lower your application's memory requirements by half a gig, you might be throwing money away. That's partly why we program in Python: use a relatively heavyweight language environment (at least compared to C or assembly) that allows us to be 10-30 times as productive for the cost of 10 times slower code and twice as much memory. -- Steven From steve at pearwood.info Sat May 28 06:25:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 28 May 2011 14:25:45 +1000 Subject: [Tutor] Python Interview Questions.. In-Reply-To: References: <143576.33767.qm@web121816.mail.ne1.yahoo.com><4DDC3648.2080809@iandouglas.com><0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4DE07949.6040309@pearwood.info> Alan Gauld wrote: > "Walter Prins" wrote > >>>> Java just isn't a hard enough language to separate great programmers >>>> from plodders (neither is Python, for that matter) because pointers >>>> and memory allocation are taken care of automagically. >>> >>> I fundamentally disagree with his stand on this. >>> >> Not sure what you're saying here Alan -- are you saying you consider Java >> "hard enough language to seperate great programmers from plodders" > > Yes, I'm saying the language just isn't that significant. Sorry Alan, you confuse me. Do you mean Java isn't that *insignificant*? >>> When you're hiring programmers, (Joel says) you want people >>>> who understand what the computer is actually doing under >>>> all the chrome, > > Thats where I disagree, you might occasionally need a few > of those, but not often and not many. I think that depends on what you mean by "understand". If you mean, should all programmers be like Mel: http://www.catb.org/jargon/html/story-of-mel.html then Hell No!!! But I do believe that all programmers should understand the limitations of the machines they're running on (in Python's case, there's a virtual machine plus the real one), or at least understand that those limitations exist, so they can avoid making silly mistakes or at least recognise it when they do so. I'm not talking about them knowing how to write assembly code, but little things like knowing why the recursive versions of factorial function and the Fibonacci sequence are so damn slow. This is often harder than it sounds in Python, because the C built-in functions are so fast compared to those written in pure Python that for any reasonable amount of data it often is faster to use a O(n**2) function using built-ins than O(n) code in pure Python. -- Steven From marc.tompkins at gmail.com Sat May 28 07:32:03 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 27 May 2011 22:32:03 -0700 Subject: [Tutor] Python Interview Questions.. In-Reply-To: <4DE06E1E.7010704@pearwood.info> References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DDC3648.2080809@iandouglas.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2DA4426882@EMARC112VS01.exchad.jpmchase.net> <4DE06E1E.7010704@pearwood.info> Message-ID: On Fri, May 27, 2011 at 8:38 PM, Steven D'Aprano wrote: > Not such a good analogy, since modern consumer goods are getting to the > point where they are almost unrepairable except by replacing the control > board. It often costs you *more* to fix a broken widget than to throw the > machine away and buy a new one, e.g. monitors, TVs, DVD players... > I kept going way, way too long with the dishwasher analogy, but the actual incident that was stuck in my mind was automotive: a few years ago, my brakes started pulsing whenever I tried to stop, and the brake light was constantly lit. I took it to the dealership; they took a look, and said "You need a new anti-lock brake computer. That'll be $1000." That seemed a bit steep to me, so I took it to Midas Brake and Muffler. They took a look, and said "You need a new right-front anti-lock brake sensor; that'll be$600." That seemed more reasonable, but when you have two clocks that don't agree you should consult a third, so I went to my regular mechanic (where I should have started in the first place!) He said "A stone from the road cut the wire from the right front sensor to the computer. We spliced the wire, wrapped it in heat-shrink tubing and sealed it. That'll be $15." Now, try to re-imagine my analogy with those three mechanics in the place of programmers. Which one should I hire? > That's also often the case with computers unless you value your time very > low. In my day job, if I have the choice in paying one of my junior techs > more than 4 hours to diagnose a flaky piece of hardware, I'd rather just hit > it with a hammer and replace the likely suspects (memory, motherboard... > whatever is likely to be causing the symptoms). Obviously its a sliding > scale -- I don't replace a$14,000 server because a hard drive is broken, > but neither do I spend three days trying to be absolutely 100% sure that a > $60 power supply is flaky before replacing it. > > Coming back to programming, sometimes the right answer is to throw more > memory at a problem rather than to write better code. A GB of RAM costs, > what,$100? That's like what, 1-3 hours of developer time? If it takes you > three hours to lower your application's memory requirements by half a gig, > you might be throwing money away. > This approach may be acceptable for in-house development, or a case where you and three other people use your program. When Microsoft and Apple adopt this philosophy, it makes me incredibly angry - multiply that $100 by all the computers running their crap software, and eventually it adds up to real money. I truly think that one of the tragedies of modern software is that the developers at places like MS, Apple, Adobe, etc. get their computers replaced on a shorter lifecycle than most of the rest of us. I mean, really - have you used Outlook or iTunes, or FSM help us Acrobat, recently? Makes me want to open a vein. And that gets to the point I was trying to make. I am ALL FOR hobbyist and part-time programming - I would not describe myself as a genius programmer, so it's a good thing that it's not my full-time job (although it's my favorite part of my job!) BUT: I damn well want geniuses, and nobody else, working on the software that I have to use to make my living. It pisses me off beyond belief to have to use some Schlemiel's efforts when I'm trying to put food on my family.* And that is why, if I were hiring developers, I would be strongly tempted to skip the resumes from Java schools (even if, FSM help me, my shop actually developed in Java) - there may very well be great programmers who went to those schools, but someone else can find them; I want the ones who've been pre-sifted for me. > That's partly why we program in Python: use a relatively heavyweight > language environment (at least compared to C or assembly) that allows us to > be 10-30 times as productive for the cost of 10 times slower code and twice > as much memory. > At no time have I advocated developing in assembler. I think that programmers should Get their Stuff Done in the most efficient manner possible. BUT: if you work for me, I want you to have sprained your brain learning how the flippin' machine works. Then, when you come to work for me, I will be ever-so happy to let you work in Python - because I know it's the best way to harness your talent. But (although I love this list, and wish everybody on it well) I would never hire a programmer who had only ever used Python, even if I ran a Python shop. Full disclosure: I am currently cranky on the subject of crap software (and the crap programmers who produce it) because, in one of my non-Python gigs, I've been struggling to update some templates in an Electronic Health Record system (which shall remain nameless.) The template editor was clearly written by a loosely-affiliated team of mental defectives, and it raises my blood pressure every time I get near it. So I may be a little unreasonable on the subject of quality software... * pace G.W. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lisi.reisz at gmail.com Sat May 28 09:20:19 2011 From: lisi.reisz at gmail.com (Lisi) Date: Sat, 28 May 2011 08:20:19 +0100 Subject: [Tutor] Python Interview Questions.. In-Reply-To: <4DE07949.6040309@pearwood.info> References: <143576.33767.qm@web121816.mail.ne1.yahoo.com> <4DE07949.6040309@pearwood.info> Message-ID: <201105280820.19889.lisi.reisz@gmail.com> On Saturday 28 May 2011 05:25:45 Steven D'Aprano wrote: > >> Not sure what you're saying here Alan -- are you saying you consider > >> Java "hard enough language to seperate great programmers from plodders" > > > > Yes, I'm saying the language just isn't that significant. > > Sorry Alan, you confuse me. Do you mean Java isn't that *insignificant*? Surely he is saying that it doesn't make much difference to this which language you are using? Lisi From merrickdav at gmail.com Sat May 28 22:08:48 2011 From: merrickdav at gmail.com (David Merrick) Date: Sun, 29 May 2011 08:08:48 +1200 Subject: [Tutor] Tutor Digest, Vol 87, Issue 114 In-Reply-To: References: Message-ID: As a new user of Pytrhon and previous user of Java,C(+),Php. There is very little difference. In some cases Python might be slower but I don't think it would mnake that much difference. The major differnce is the syntax of how you write and layout your code. Chreers Dave On Sat, May 28, 2011 at 10:00 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Python Interview Questions.. (Steven D'Aprano) > 2. Re: Python Interview Questions.. (Marc Tompkins) > 3. Re: Python Interview Questions.. (Lisi) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 28 May 2011 14:25:45 +1000 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Python Interview Questions.. > Message-ID: <4DE07949.6040309 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Alan Gauld wrote: > > "Walter Prins" wrote > > > >>>> Java just isn't a hard enough language to separate great programmers > >>>> from plodders (neither is Python, for that matter) because pointers > >>>> and memory allocation are taken care of automagically. > >>> > >>> I fundamentally disagree with his stand on this. > >>> > >> Not sure what you're saying here Alan -- are you saying you consider > Java > >> "hard enough language to seperate great programmers from plodders" > > > > Yes, I'm saying the language just isn't that significant. > > Sorry Alan, you confuse me. Do you mean Java isn't that *insignificant*? > > > >>> When you're hiring programmers, (Joel says) you want people > >>>> who understand what the computer is actually doing under > >>>> all the chrome, > > > > Thats where I disagree, you might occasionally need a few > > of those, but not often and not many. > > I think that depends on what you mean by "understand". > > If you mean, should all programmers be like Mel: > > http://www.catb.org/jargon/html/story-of-mel.html > > then Hell No!!! > > But I do believe that all programmers should understand the limitations > of the machines they're running on (in Python's case, there's a virtual > machine plus the real one), or at least understand that those > limitations exist, so they can avoid making silly mistakes or at least > recognise it when they do so. > > I'm not talking about them knowing how to write assembly code, but > little things like knowing why the recursive versions of factorial > function and the Fibonacci sequence are so damn slow. > > This is often harder than it sounds in Python, because the C built-in > functions are so fast compared to those written in pure Python that for > any reasonable amount of data it often is faster to use a O(n**2) > function using built-ins than O(n) code in pure Python. > > > > -- > Steven > > > ------------------------------ > > Message: 2 > Date: Fri, 27 May 2011 22:32:03 -0700 > From: Marc Tompkins > To: tutor at python.org > Subject: Re: [Tutor] Python Interview Questions.. > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > On Fri, May 27, 2011 at 8:38 PM, Steven D'Aprano >wrote: > > > Not such a good analogy, since modern consumer goods are getting to the > > point where they are almost unrepairable except by replacing the control > > board. It often costs you *more* to fix a broken widget than to throw the > > machine away and buy a new one, e.g. monitors, TVs, DVD players... > > > > I kept going way, way too long with the dishwasher analogy, but the actual > incident that was stuck in my mind was automotive: a few years ago, my > brakes started pulsing whenever I tried to stop, and the brake light was > constantly lit. I took it to the dealership; they took a look, and said > "You need a new anti-lock brake computer. That'll be$1000." That seemed > a > bit steep to me, so I took it to Midas Brake and Muffler. They took a > look, > and said "You need a new right-front anti-lock brake sensor; that'll be > $600." That seemed more reasonable, but when you have two clocks that > don't > agree you should consult a third, so I went to my regular mechanic (where I > should have started in the first place!) He said "A stone from the road > cut > the wire from the right front sensor to the computer. We spliced the wire, > wrapped it in heat-shrink tubing and sealed it. That'll be$15." > Now, try to re-imagine my analogy with those three mechanics in the place > of > programmers. Which one should I hire? > > > > That's also often the case with computers unless you value your time very > > low. In my day job, if I have the choice in paying one of my junior techs > > more than 4 hours to diagnose a flaky piece of hardware, I'd rather just > hit > > it with a hammer and replace the likely suspects (memory, motherboard... > > whatever is likely to be causing the symptoms). Obviously its a sliding > > scale -- I don't replace a $14,000 server because a hard drive is broken, > > but neither do I spend three days trying to be absolutely 100% sure that > a > >$60 power supply is flaky before replacing it. > > > > Coming back to programming, sometimes the right answer is to throw more > > memory at a problem rather than to write better code. A GB of RAM costs, > > what, $100? That's like what, 1-3 hours of developer time? If it takes > you > > three hours to lower your application's memory requirements by half a > gig, > > you might be throwing money away. > > > > This approach may be acceptable for in-house development, or a case where > you and three other people use your program. When Microsoft and Apple > adopt > this philosophy, it makes me incredibly angry - multiply that$100 by all > the computers running their crap software, and eventually it adds up to > real > money. I truly think that one of the tragedies of modern software is that > the developers at places like MS, Apple, Adobe, etc. get their computers > replaced on a shorter lifecycle than most of the rest of us. I mean, > really > - have you used Outlook or iTunes, or FSM help us Acrobat, recently? Makes > me want to open a vein. > > And that gets to the point I was trying to make. I am ALL FOR hobbyist and > part-time programming - I would not describe myself as a genius programmer, > so it's a good thing that it's not my full-time job (although it's my > favorite part of my job!) > BUT: > I damn well want geniuses, and nobody else, working on the software that I > hav