From steve at pearwood.info Sat Feb 1 01:32:48 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 1 Feb 2014 11:32:48 +1100 Subject: [Tutor] is an alias a variable In-Reply-To: References: Message-ID: <20140201003248.GN3799@ando> On Fri, Jan 31, 2014 at 09:36:13PM +0000, Alan Gauld wrote: > On 31/01/14 09:57, Ian D wrote: > > >import longModuleName as lmn > > > >or > > > >lmn = longModuleName > > > >creating an alias or assigning to a variable..... or both? > > variables in Python are just names. > There is no concept of an alias as such, its just another > name referring to the same object. Sounds like an alias to me :-) Informally, an alias in programming could mean one of two things: (1) A second name for the same object, which is what Python gives us. The important factor is that when you operate on the object in-place, say append to a list, it doesn't matter which name you use: py> a = [] # "a" is a name for the object [] py> b = a # an alias for the *object* named "a" py> b.append(23) # modify the list in place py> a [23] (2) A sort of "meta-name", where the alias refers to the name itself, rather than it's contents. Python does *not* have this functionality, but it is quite similar to (for example) "pass by reference" variables in Pascal. If Python had this sort of alias, modifying the object would work the same way as it currently does: py> a = [] py> b = a # an "alias" for the *name* "a", not the object py> b.append(23) py> a [23] but in addition assignments to the alias would be like assignments to the original name. This does *not* happen in Python: py> b = 42 # assign a new value to (alias) b py> a 42 If you try this in Python, instead the name "b" gets the value 42, while the name "a" continues to refer to the list [23] as before. -- Steven From denis.spir at gmail.com Sat Feb 1 09:55:10 2014 From: denis.spir at gmail.com (spir) Date: Sat, 01 Feb 2014 09:55:10 +0100 Subject: [Tutor] creating Turtle() object using 2 different ways In-Reply-To: References: Message-ID: <52ECB66E.2090205@gmail.com> On 01/31/2014 10:38 PM, Alan Gauld wrote: > If you want multiple turtles you should use > the first version. Yes, the turtle module has a global turtle that can be used by people playing with a single turtle, and prefere conventional procedural programming style, rather than object-oriented (OO). If you need multiple turtle or prefere OO, then you need to first create an OO turtle as you did, using turtle.Turtle(). (It's all explained in the docs: http://docs.python.org/3/library/turtle.html : << The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. >> ) d From wprins at gmail.com Sat Feb 1 11:05:38 2014 From: wprins at gmail.com (Walter Prins) Date: Sat, 1 Feb 2014 10:05:38 +0000 Subject: [Tutor] Code runs in interpreter but won't output to stdout In-Reply-To: <52EC1CAC.4070202@gmail.com> References: <52E97F97.8080705@gmail.com> <52EC1CAC.4070202@gmail.com> Message-ID: Hi Bob, On 31 January 2014 21:59, bob gailer wrote: > On 1/29/2014 8:59 PM, scurvy scott wrote: > I signed up at Dogehouse. What the heck is it? There is no explanation as to > what it does or what I'd do with it! I don't know if you're familiar with BitCoin and the concept of the "pooled mining", but Dogehouse appears to be a bitcoin mining pool. Basically instead of mining for bitcoins directly alone by yourself, you pool your mining efforts with a pool of others and then share the return with the pool: https://en.bitcoin.it/wiki/Pooled_mining https://en.bitcoin.it/wiki/Why_pooled_mining Also, I'm not entirely sure if you were being facetious with your "import requests" comment -- I suspect you were and if so I should not be commenting on that ;) (and in thaat case please ignore this entire paragraph), but in case not -- it's a third party module for doing web interaction that's actually been mentioned a couple of times on this list: http://docs.python-requests.org/en/latest/ Scurvy Scott: There's nothing really special about printing stuff, so there's something you're not telling us or that you're not aware of that's causing your program to behave differently between running it "in the interpreter" and otherwise (from the command line, presumably.) Do you for example have multiple versions of Python installed? Are you sure for example you're using the same version of Python interpreter? (print syntax changed between Python 2.x and 3.x.) How are you running it from the command line exactly? Best regards, Walter From hind_fathallah at yahoo.com Sat Feb 1 05:55:03 2014 From: hind_fathallah at yahoo.com (hind fathallah) Date: Fri, 31 Jan 2014 20:55:03 -0800 (PST) Subject: [Tutor] help me Message-ID: <1391230503.91752.YahooMailNeo@web162106.mail.bf1.yahoo.com> hi can you answer this question for me plz ? Modify the Guess My number program from this chapter so that the player has only five guesses. If the player run out of guess, the program should end the game and display an appropriately chastising message.? -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Feb 1 15:33:56 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Feb 2014 14:33:56 +0000 Subject: [Tutor] help me In-Reply-To: <1391230503.91752.YahooMailNeo@web162106.mail.bf1.yahoo.com> References: <1391230503.91752.YahooMailNeo@web162106.mail.bf1.yahoo.com> Message-ID: On 01/02/2014 04:55, hind fathallah wrote: > hi can you answer this question for me plz > Modify the Guess My number program from this chapter so that the player > has only five guesses. If the player run out of guess, the program > should end the game and display an appropriately chastising message. > Please give your message a sensible subject. Better still tell us which chapter from which book so that we can help you, or copy the contents here so that we can see them. Your Python version and OS are useful as well. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From dyoo at hashcollision.org Sat Feb 1 19:28:45 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 1 Feb 2014 10:28:45 -0800 Subject: [Tutor] help me In-Reply-To: <1391230503.91752.YahooMailNeo@web162106.mail.bf1.yahoo.com> References: <1391230503.91752.YahooMailNeo@web162106.mail.bf1.yahoo.com> Message-ID: On Fri, Jan 31, 2014 at 8:55 PM, hind fathallah wrote: > hi can you answer this question for me plz [question omitted] Many of us probably could answer this. But this is not a homework-answering mailing list. The problem itself is not interesting to us. What is interesting is why the problem is giving you trouble. We'd rather focus on where you are having difficulty: we'd rather help *you*. Tell us what you've tried, where you're getting stuck, what other kinds of problems you've done that are similar to this one. That is, show us what general problem solving strategies you're using now. Maybe some of those strategies are not working for you. From duxbuz at hotmail.com Sat Feb 1 19:41:10 2014 From: duxbuz at hotmail.com (Ian D) Date: Sat, 1 Feb 2014 18:41:10 +0000 Subject: [Tutor] Best version for novice Message-ID: Hi Is it better to use python 3 as a newcomer who isn't really going to be writing any software as such just using it for learning? Also in 2.7 I use no subprocess by giving my python exe a -n argument, otherwise my canvas program's freeze. Is this needed also in version 3? Ta -------------- next part -------------- An HTML attachment was scrubbed... URL: From stopitscurvy at gmail.com Sat Feb 1 16:21:30 2014 From: stopitscurvy at gmail.com (scurvy scott) Date: Sat, 1 Feb 2014 10:21:30 -0500 Subject: [Tutor] Code runs in interpreter but won't output to stdout In-Reply-To: References: <52E97F97.8080705@gmail.com> <52EC1CAC.4070202@gmail.com> Message-ID: Please always reply to the tutor list so we can all play with your question. --sorry about that Bob, I've now hit reply all. I am stuck at "import requests". Where did you get that module? --requests is a third party webscraping module. I signed up at Dogehouse. What the heck is it? There is no explanation as to what it does or what I'd do with it! --dogehouse.org is a dogecoin mining pool that allows users to pool CPU/GPU resources to make mining cryptocurrency more efficient. Scurvy Scott: There's nothing really special about printing stuff, so there's something you're not telling us or that you're not aware of that's causing your program to behave differently between running it "in the interpreter" and otherwise (from the command line, presumably.) Do you for example have multiple versions of Python installed? Are you sure for example you're using the same version of Python interpreter? (print syntax changed between Python 2.x and 3.x.) How are you running it from the command line exactly? Best regards, Walter --I'm only using Python 2.7 and yes either running the code live in the interpreter, which works just fine, or running from command line using "python programname.py". In this instance, I've named the program dogeScrape.py, so python dogeScrape.py . I've been messing with python for a while and have never had this problem before. I've also tried using the different print syntax for 3.x just to be sure, to no avail. I've also tried running the code without it being in functions, and just running it I guess "straight through" or whatever you'd call it, also to no avail. The site is implementing its own API in the next week or so, so I just figured I'd work out these bugs when that happens and maybe some magical unicorn will cure whatever is ailing me. Thanks for y'alls help. Scott On Sat, Feb 1, 2014 at 5:05 AM, Walter Prins wrote: > Hi Bob, > > On 31 January 2014 21:59, bob gailer wrote: > > On 1/29/2014 8:59 PM, scurvy scott wrote: > > I signed up at Dogehouse. What the heck is it? There is no explanation > as to > > what it does or what I'd do with it! > > I don't know if you're familiar with BitCoin and the concept of the > "pooled mining", but Dogehouse appears to be a bitcoin mining pool. > Basically instead of mining for bitcoins directly alone by yourself, > you pool your mining efforts with a pool of others and then share the > return with the pool: https://en.bitcoin.it/wiki/Pooled_mining > https://en.bitcoin.it/wiki/Why_pooled_mining > > Also, I'm not entirely sure if you were being facetious with your > "import requests" comment -- I suspect you were and if so I should not > be commenting on that ;) (and in thaat case please ignore this entire > paragraph), but in case not -- it's a third party module for doing web > interaction that's actually been mentioned a couple of times on this > list: http://docs.python-requests.org/en/latest/ > > Scurvy Scott: There's nothing really special about printing stuff, so > there's something you're not telling us or that you're not aware of > that's causing your program to behave differently between running it > "in the interpreter" and otherwise (from the command line, > presumably.) Do you for example have multiple versions of Python > installed? Are you sure for example you're using the same version of > Python interpreter? (print syntax changed between Python 2.x and 3.x.) > How are you running it from the command line exactly? > > Best regards, > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 1 21:35:57 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 01 Feb 2014 20:35:57 +0000 Subject: [Tutor] Best version for novice In-Reply-To: References: Message-ID: On 01/02/14 18:41, Ian D wrote: > Is it better to use python 3 as a newcomer who isn't really going to be > writing any software as such just using it for learning? The more important question is which version does your preferred tutorial use? Both versions will teach you a lot about programming and Python, but the tutorial that suits your style of learning best will most likely determine the version you use since its harder to learn when the examples don't work! Although some might argue that fixing them teaches you even more! > Also in 2.7 I use no subprocess by giving my python exe a -n argument, > otherwise my canvas program's freeze. I don;t need to do that in any of my Python versions. Are you by any chance running your code in IDLE? There used to be issues with idle and subprocesses and Tkinter. But I thought they'd all been fixed by 2.7... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sun Feb 2 02:20:53 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 2 Feb 2014 12:20:53 +1100 Subject: [Tutor] Best version for novice In-Reply-To: References: Message-ID: <20140202012053.GS3799@ando> On Sat, Feb 01, 2014 at 06:41:10PM +0000, Ian D wrote: > Hi > > Is it better to use python 3 as a newcomer who isn't really going to > be writing any software as such just using it for learning? Yes, you should use Python 3, with one proviso: many tutorials, especially the older ones, are based on Python 2. That means that you either need to find another tutorial, or mentally adjust from Python 2 to 3 when you read it. That's easy for an experienced user, but perhaps not for a beginner. The differences aren't really that great, no more different than between (say) British English and American English, but it may be disconcerting for somebody who isn't confident with the language. Python 3 is the future of Python. All improvements are going into 3, 2 is only getting bug fixes. If you aren't *required* to stick with Python 2 for some reason, you should use 3. > Also in 2.7 I use no subprocess by giving my python exe a -n argument, > otherwise my canvas program's freeze. I'm afraid that I have no idea what you are talking about here, Python doesn't accept a -n argument: [steve at ando ~]$ python2.7 -n Unknown option: -n usage: python2.7 [option] ... [-c cmd | -m mod | file | -] [arg] ... Try `python -h' for more information. Regards, -- Steven From eryksun at gmail.com Sun Feb 2 06:41:55 2014 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Feb 2014 00:41:55 -0500 Subject: [Tutor] Best version for novice In-Reply-To: <20140202012053.GS3799@ando> References: <20140202012053.GS3799@ando> Message-ID: On Sat, Feb 1, 2014 at 8:20 PM, Steven D'Aprano wrote: > > I'm afraid that I have no idea what you are talking about here, Python > doesn't accept a -n argument: -n is an IDLE option: If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. With respect to Tkinter, using -n allows your widgets to piggyback on IDLE's main loop. I looked into this a bit: In a terminal you usually don't have to manually `update` [1] the embedded Tcl interpreter's event queue. What happens is the _tkinter extension module sets the global function pointer PyOS_InputHook to a function that calls Tcl_DoOneEvent [2]. The readline module calls this hook about 10 times per second while waiting for input. However, readline isn't used for IDLE's child process, which gets code from a socket in a background thread. [1] http://www.tcl.tk/man/tcl8.5/TclCmd/update.htm [2] http://www.tcl.tk/man/tcl8.5/TclLib/DoOneEvent.htm From rdole1 at cogeco.ca Sun Feb 2 13:48:34 2014 From: rdole1 at cogeco.ca (rick) Date: Sun, 02 Feb 2014 07:48:34 -0500 Subject: [Tutor] how do (or do I) do a list of variable names? Message-ID: <52EE3EA2.8050103@cogeco.ca> Hello Everyone, I think my approach is all wrong, but here goes. var1 = []; var2 = []; var3 = []; . . . ~50 lists each variable would be a list of two digit integers, or two digit integers stored as strings (I don't need to do any math, I just need to know which integers are in which variable) container = [var1,var2,var3 . . . ] I'd like to be able to iterate over container or pick out one or more of my lists to write out an input (text) file for an external program. The thing is, assigning all those lists to a list gives me a list of lists, not a list of my variable names. Worse, I may or may not be able to have changes to a list show up in my list of lists, depending on how & when I do it. Really kludgy, but it is a one off that will likely never be used again. TIA, Rick -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 230 bytes Desc: OpenPGP digital signature URL: From __peter__ at web.de Sun Feb 2 14:19:44 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Feb 2014 14:19:44 +0100 Subject: [Tutor] how do (or do I) do a list of variable names? References: <52EE3EA2.8050103@cogeco.ca> Message-ID: rick wrote: > Hello Everyone, > > I think my approach is all wrong, but here goes. > > var1 = []; var2 = []; var3 = []; . . . ~50 lists > > > each variable would be a list of two digit integers, or two digit > integers stored as strings (I don't need to do any math, I just need to > know which integers are in which variable) > > container = [var1,var2,var3 . . . ] > > I'd like to be able to iterate over container or pick out one or more of > my lists to write out an input (text) file for an external program. > > The thing is, assigning all those lists to a list gives me a list of > lists, not a list of my variable names. Worse, I may or may not be able > to have changes to a list show up in my list of lists, depending on how > & when I do it. > > Really kludgy, but it is a one off that will likely never be used again. You typically don't make 50 variables in Python, you use a dict: >>> container = { ... "foo": [10, 20], ... "bar": [30, 40], ... "baz": [40, 50], ... #... ... } you can then look up the "foo" list with >>> print(container["foo"]) [10, 20] If you want to know all the keys that 40 is associated with you can either iterate through the items every time >>> print([k for k, v in container.items() if 40 in v]) ['bar', 'baz'] or build the reverse dict once >>> for k, values in container.items(): ... for v in values: ... value_to_key.setdefault(v, set()).add(k) ... and then profit from fast lookup >>> print(value_to_key[40]) {'bar', 'baz'} >>> print(value_to_key[10]) {'foo'} until you make changes to the original `container` dict. From asanch505 at hotmail.com Sun Feb 2 04:08:25 2014 From: asanch505 at hotmail.com (adrian) Date: Sat, 1 Feb 2014 20:08:25 -0700 Subject: [Tutor] sorting and writing to data file Message-ID: Hello community, Newbie here. I have a data (.dat) file with integers (2,9,1,5,7,3,9) in it just as shown. My instructions are to sort the numbers and rewrite them back to the data file. *here is my code:** * lab3int=[2,9,1,5,7,3,9] lab3int.sort() print(lab3int) lab3int=open('lab3int.dat','w') lab3int.write() lab3int.close() *here is my error message:* [1, 2, 3, 5, 7, 9, 9] Traceback (most recent call last): File "lab3int.py", line 5, in lab3int.write() TypeError: function takes exactly 1 argument (0 given) I know that it is telling me that my error is in line #5. If I put anything in the () for lab3int.write function, then that appears in my data file. however, I am looking to just put the re-sorted integers back into the data file without having to manually type each integer manually. Is there something that i can put into the lab3int.write() to make that happen? Hope my problem is clear, Thanks people ATS -------------- next part -------------- An HTML attachment was scrubbed... URL: From duxbuz at hotmail.com Sun Feb 2 09:25:16 2014 From: duxbuz at hotmail.com (Ian D) Date: Sun, 2 Feb 2014 08:25:16 +0000 Subject: [Tutor] most useful ide Message-ID: Hi Are there any recommendations for python ide's currently I am using idle, which seems pretty decent but am open to any suggestions cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From gb.gabrielebrambilla at gmail.com Sun Feb 2 03:11:25 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Sat, 1 Feb 2014 21:11:25 -0500 Subject: [Tutor] strange errors Message-ID: Hi, sometimes when I try to run a program in Python I obtain some errors. The strange thing is that sometimes when I run it a second time or when I turn off the pc and I restart later to try to make it works it gives different errors. How could I avoid this problem? I think that it is because it "remember" some variables that I have used... Thanks Gabriele -------------- next part -------------- An HTML attachment was scrubbed... URL: From hind_fathallah at yahoo.com Sun Feb 2 00:40:10 2014 From: hind_fathallah at yahoo.com (hind fathallah) Date: Sat, 1 Feb 2014 15:40:10 -0800 (PST) Subject: [Tutor] help me In-Reply-To: References: <1391230503.91752.YahooMailNeo@web162106.mail.bf1.yahoo.com> Message-ID: <1391298010.33542.YahooMailNeo@web162102.mail.bf1.yahoo.com> thank you so much because I got it :)? On Saturday, February 1, 2014 1:28 PM, Danny Yoo wrote: On Fri, Jan 31, 2014 at 8:55 PM, hind fathallah wrote: > hi can you answer this question for me plz [question omitted] Many of us probably could answer this. But this is not a homework-answering mailing list.? The problem itself is not interesting to us.? What is interesting is why the problem is giving you trouble.? We'd rather focus on where you are having difficulty: we'd rather help *you*. Tell us what you've tried, where you're getting stuck, what other kinds of problems you've done that are similar to this one.? That is, show us what general problem solving strategies you're using now. Maybe some of those strategies are not working for you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From leamhall at gmail.com Sat Feb 1 21:52:29 2014 From: leamhall at gmail.com (Leam Hall) Date: Sat, 01 Feb 2014 15:52:29 -0500 Subject: [Tutor] Best version for novice In-Reply-To: References: Message-ID: <52ED5E8D.4030606@gmail.com> On 02/01/2014 03:35 PM, Alan Gauld wrote: > On 01/02/14 18:41, Ian D wrote: > >> Is it better to use python 3 as a newcomer who isn't really going to be >> writing any software as such just using it for learning? > > The more important question is which version does your > preferred tutorial use? And are you targeting a specific platform or just for yourself? Some platforms, like Red Hat/CentOS, are still 2.x. The most current RHEL is 2.6 and the upcoming RHEL 7 is still Python 2.7. If you're doing this for yourself, or for a start-up that can use newer versions, use 3.x if your tutorial supports it. You might note in Alan's signature is a like to his site, which happens to have a nice tutorial. :) http://www.alan-g.me.uk/ Leam -- http://31challenge.net http://31challenge.net/insight From alan.gauld at btinternet.com Sun Feb 2 15:10:16 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Feb 2014 14:10:16 +0000 Subject: [Tutor] sorting and writing to data file In-Reply-To: References: Message-ID: On 02/02/14 03:08, adrian wrote: > Newbie here. I have a data (.dat) file with integers (2,9,1,5,7,3,9) in > it just as shown. In your code below you use a hard coded list not a data file? > lab3int=[2,9,1,5,7,3,9] > lab3int.sort() > print(lab3int) So far so good. > lab3int=open('lab3int.dat','w') But now you've reassigned lab3int to the file object so you threw away all your data. You need a separate variable to store the file pointer. Lets call it intFile... > lab3int.write() Would now become intfile.write() But your data is a sorted list of integers so you need to convert that to a string before you can write it to a text file. You need a loop such as for item in lab3int: intFile.write( str(item) ) If you had a lot of data you might want to think about adding some newlines when you write too... hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sun Feb 2 15:13:38 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Feb 2014 14:13:38 +0000 Subject: [Tutor] strange errors In-Reply-To: References: Message-ID: On 02/02/14 02:11, Gabriele Brambilla wrote: > sometimes when I try to run a program in Python I obtain some errors. How are you running the program? doubly clicking in a file manager/explorer? Running from an OS command line? Importing from the Python >>> prompt? Or using some kind of IDE? (Which?) The answer to your question depends a lot on the way you run the code. A sample error and your OS and Python version will help too. > How could I avoid this problem? I think that it is because it "remember" > some variables that I have used... Could be. If you import a module then change that module then reimporting alone is not enough. But if you run the code from the OS that shouldn't be an issue. So how do you run the code? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Sun Feb 2 15:18:38 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Feb 2014 15:18:38 +0100 Subject: [Tutor] sorting and writing to data file References: Message-ID: Alan Gauld wrote: > You need a loop such as > > for item in lab3int: > intFile.write( str(item) ) You also need to separate the values, with a space, a newline or whatever. So: for item in lab3int: intFile.write(str(item)) intFile.write("\n") This can be simplified to for item in lab3int: print(item, file=intFile) From alan.gauld at btinternet.com Sun Feb 2 15:17:10 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 02 Feb 2014 14:17:10 +0000 Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: On 02/02/14 08:25, Ian D wrote: > Are there any recommendations for python ide's Lots depending who you ask... > currently I am using idle, which seems pretty decent but am open to any > suggestions If it works for you then use it. The thing about IDEs is that they ae very personal. Some people swear by emacs, others swear at it. Some love Netbeans, or Eclipse, others hate them both. If you are a Mac user you may prefer XCode... There are lots of specialized Pyhon IDS too. And many Linux users prefer to let Linux be their IDE and just run multiple Windows to do the same job. (I'm in this camp FWIW...) A lot will also depend on whether you have used IDEs in the past, since that might sway your preferences. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From pasokan at talentsprint.com Sun Feb 2 16:43:19 2014 From: pasokan at talentsprint.com (Asokan Pichai) Date: Sun, 2 Feb 2014 21:13:19 +0530 Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: On Sun, Feb 2, 2014 at 1:55 PM, Ian D wrote: > Hi > > Are there any recommendations for python ide's > > currently I am using idle, which seems pretty decent but am open to any > suggestions > cheers > While not an IDE in the usual sense I have found IPython a great addition to my toolkit. YMMV Asokan Pichai -------------- next part -------------- An HTML attachment was scrubbed... URL: From stopitscurvy at gmail.com Sun Feb 2 17:08:28 2014 From: stopitscurvy at gmail.com (scurvy scott) Date: Sun, 2 Feb 2014 11:08:28 -0500 Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: Hi Are there any recommendations for python ide's currently I am using idle, which seems pretty decent but am open to any suggestions cheers I personally prefer the Linux interpreter. Since you're asking. Scott On Sun, Feb 2, 2014 at 10:43 AM, Asokan Pichai wrote: > > > > On Sun, Feb 2, 2014 at 1:55 PM, Ian D wrote: > >> Hi >> >> Are there any recommendations for python ide's >> > >> currently I am using idle, which seems pretty decent but am open to any >> suggestions >> cheers >> > > While not an IDE in the usual sense I have found IPython a great addition > to my toolkit. > YMMV > > Asokan Pichai > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 2 18:56:29 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 2 Feb 2014 17:56:29 +0000 (GMT) Subject: [Tutor] strange errors In-Reply-To: References: Message-ID: <1391363789.67566.YahooMailNeo@web186003.mail.ir2.yahoo.com> forwarding to list... Please use reply-all when responding to the list. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos >________________________________ > From: Gabriele Brambilla >To: Alan Gauld >Sent: Sunday, 2 February 2014, 17:31 >Subject: Re: [Tutor] strange errors > > > >I use windows 7 command prompt. doing > > >python .py > > >the errors are various...when I will get them again I will write them! > > >thanks > > >Gabriele > > > >2014-02-02 Alan Gauld : > >On 02/02/14 02:11, Gabriele Brambilla wrote: >> >> >>sometimes when I try to run a program in Python I obtain some errors. >>> >> How are you running the program? >> >>doubly clicking in a file manager/explorer? >>Running from an OS command line? >>Importing from the Python >>> prompt? >>Or using some kind of IDE? (Which?) >> >>The answer to your question depends a lot on the way you >>run the code. >> >>A sample error and your OS and Python version will help too. >> >> >> >>How could I avoid this problem? I think that it is because it "remember" >>>some variables that I have used... >>> >> Could be. If you import a module then change that module then >>reimporting alone is not enough. But if you run the code from the OS that shouldn't be an issue. So how do you run the code? >> >>-- >>Alan G >>Author of the Learn to Program web site >>http://www.alan-g.me.uk/ >>http://www.flickr.com/photos/alangauldphotos >> >>_______________________________________________ >>Tutor maillist ?- ?Tutor at python.org >>To unsubscribe or change subscription options: >>https://mail.python.org/mailman/listinfo/tutor >> > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sun Feb 2 18:56:44 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 2 Feb 2014 09:56:44 -0800 (PST) Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: <1391363804.77253.YahooMailNeo@web163801.mail.gq1.yahoo.com> >Subject: Re: [Tutor] most useful ide > >On 02/02/14 08:25, Ian D wrote: > >> Are there any recommendations for python ide's > >Lots depending who you ask... If you ask me: Spyder (free) or PyCharm (free for open source projects) ;-) From kfiresmith at gmail.com Sun Feb 2 19:16:52 2014 From: kfiresmith at gmail.com (Kodiak Firesmith) Date: Sun, 2 Feb 2014 13:16:52 -0500 Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: Pycharm is nice for bigger projects (since tou can collapse any section); but it's crazy resource intensive. For Linux Gedit can be made very nice for python, and of course vim in the shell is very nice with the right ~/.vimrc. On Feb 2, 2014 11:20 AM, "scurvy scott" wrote: > Hi > > Are there any recommendations for python ide's > > currently I am using idle, which seems pretty decent but am open to any > suggestions > > > cheers > > > I personally prefer the Linux interpreter. Since you're asking. > Scott > > > On Sun, Feb 2, 2014 at 10:43 AM, Asokan Pichai wrote: > >> >> >> >> On Sun, Feb 2, 2014 at 1:55 PM, Ian D wrote: >> >>> Hi >>> >>> Are there any recommendations for python ide's >>> >> >>> currently I am using idle, which seems pretty decent but am open to any >>> suggestions >>> cheers >>> >> >> While not an IDE in the usual sense I have found IPython a great addition >> to my toolkit. >> YMMV >> >> Asokan Pichai >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pierre.dagenais at ncf.ca Sun Feb 2 21:10:52 2014 From: pierre.dagenais at ncf.ca (Pierre Dagenais) Date: Sun, 02 Feb 2014 15:10:52 -0500 Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: <52EEA64C.7020409@ncf.ca> On 14-02-02 01:16 PM, Kodiak Firesmith wrote: > Pycharm is nice for bigger projects (since tou can collapse any section); > but it's crazy resource intensive. For Linux Gedit can be made very nice I prefer Geany as it will run my code with a click of the mouse. > for python, and of course vim in the shell is very nice with the right > ~/.vimrc. > On Feb 2, 2014 11:20 AM, "scurvy scott" wrote: > >> Hi >> >> Are there any recommendations for python ide's From oscar.j.benjamin at gmail.com Sun Feb 2 21:31:20 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 2 Feb 2014 20:31:20 +0000 Subject: [Tutor] most useful ide In-Reply-To: <52EEA64C.7020409@ncf.ca> References: <52EEA64C.7020409@ncf.ca> Message-ID: On Feb 2, 2014 8:17 PM, "Pierre Dagenais" wrote: > > > > On 14-02-02 01:16 PM, Kodiak Firesmith wrote: > > Pycharm is nice for bigger projects (since tou can collapse any section); > > but it's crazy resource intensive. For Linux Gedit can be made very nice > > I prefer Geany as it will run my code with a click of the mouse. I prefer vim so that I never have to use the mouse. :) Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From pierre.dagenais at ncf.ca Sun Feb 2 21:36:19 2014 From: pierre.dagenais at ncf.ca (Pierre Dagenais) Date: Sun, 02 Feb 2014 15:36:19 -0500 Subject: [Tutor] Best version for novice In-Reply-To: <20140202012053.GS3799@ando> References: <20140202012053.GS3799@ando> Message-ID: <52EEAC43.8010708@ncf.ca> On 14-02-01 08:20 PM, Steven D'Aprano wrote: > On Sat, Feb 01, 2014 at 06:41:10PM +0000, Ian D wrote: >> Hi >> >> Is it better to use python 3 as a newcomer who isn't really going to >> be writing any software as such just using it for learning? > > Yes, you should use Python 3, with one proviso: many tutorials, > especially the older ones, are based on Python 2. That means that you Steven is not a newbie, but I am. I suppose that makes me the expert on tutorials, LOL. I find that most useful tut are now for Python 3, when you find a Python 2 tutorial you need to convert the print statement, the tkinter import statement, and ignore any references to cPickle. In my experience everything else works as posted. PierreD. > either need to find another tutorial, or mentally adjust from Python 2 > to 3 when you read it. That's easy for an experienced user, but perhaps > not for a beginner. > > The differences aren't really that great, no more different than between > (say) British English and American English, but it may be disconcerting > for somebody who isn't confident with the language. > > Python 3 is the future of Python. All improvements are going into 3, 2 > is only getting bug fixes. If you aren't *required* to stick with Python > 2 for some reason, you should use 3. > > >> Also in 2.7 I use no subprocess by giving my python exe a -n argument, >> otherwise my canvas program's freeze. > > I'm afraid that I have no idea what you are talking about here, Python > doesn't accept a -n argument: > > [steve at ando ~]$ python2.7 -n > Unknown option: -n > usage: python2.7 [option] ... [-c cmd | -m mod | file | -] [arg] ... > Try `python -h' for more information. > > > > Regards, > > > From beachkidken at gmail.com Sun Feb 2 21:43:32 2014 From: beachkidken at gmail.com (Ken G.) Date: Sun, 02 Feb 2014 15:43:32 -0500 Subject: [Tutor] most useful ide In-Reply-To: <52EEA64C.7020409@ncf.ca> References: <52EEA64C.7020409@ncf.ca> Message-ID: <52EEADF4.4010201@gmail.com> On 02/02/2014 03:10 PM, Pierre Dagenais wrote: > > On 14-02-02 01:16 PM, Kodiak Firesmith wrote: >> Pycharm is nice for bigger projects (since tou can collapse any section); >> but it's crazy resource intensive. For Linux Gedit can be made very nice > I prefer Geany as it will run my code with a click of the mouse. > >> for python, and of course vim in the shell is very nice with the right >> ~/.vimrc. >> On Feb 2, 2014 11:20 AM, "scurvy scott" wrote: >> >>> Hi >>> >>> Are there any recommendations for python ide's I, too, use Geany to run my Python programs. Ken From pywkm at wukaem.pl Sun Feb 2 21:44:57 2014 From: pywkm at wukaem.pl (Wiktor Matuszewski) Date: Sun, 02 Feb 2014 21:44:57 +0100 Subject: [Tutor] most useful ide In-Reply-To: <1391363804.77253.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1391363804.77253.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <52EEAE49.9090209@wukaem.pl> W dniu 2014-02-02 18:56, Albert-Jan Roskam pisze: >> On 02/02/14 08:25, Ian D wrote: >> >>> Are there any recommendations for python ide's >> >> Lots depending who you ask... > > If you ask me: Spyder (free) or PyCharm (free for open source projects) ;-) There is also PyCharm Community Edition. Free for all projects. And if you'd ask me, it would be my answer. :) -- Best regards, Wiktor Matuszewski From kip at kdream.com Sun Feb 2 21:46:38 2014 From: kip at kdream.com (Kipton Moravec) Date: Sun, 02 Feb 2014 14:46:38 -0600 Subject: [Tutor] Traversing lists or getting the element you want. Message-ID: <1391373998.2058.53975.camel@Red> I am new to Python, and I do not know how to traverse lists like I traverse arrays in C. This is my first program other than "Hello World". I have a Raspberry Pi and they say Python is the language of choice for that little machine. So I am going to try to learn it. I have data in the form of x, y pairs where y = f(x) and is non linear. It comes from a .csv file. In this case x is an integer from 165 to 660 so I have 495 data sets. I need to find the optimal locations of three values of x to piecewise linear estimate the function. So I need to find i, j, k so 165 < i < j < k < 660 and the 4 line segments [(165, f(165)), (i, f(i))], [(i, f(i)), (j, f(j))], [(j, f(j), (k, f(k))], [(k, f(k)), (660, f(660))]. The value I need to minimize is the square of the difference between the line estimate and the real value at each of the 495 points. I can do this in C. To keep it simple to understand I will assume the arrays x[] and y[] and minsum, mini, minj, and mink are global. I have not tested this but this is what I came up with in C. Assuming x[] and y[] are already filled with the right values. int x[495]; double y[495]; max_elements = 495; double minsum; int mini, minj, mink void minimize(int max_elements) { minsum = 9999999999999.0; // big big number for (i=2; i References: <1391373998.2058.53975.camel@Red> Message-ID: On Sun, Feb 2, 2014 at 3:46 PM, Kipton Moravec wrote: > I am new to Python, and I do not know how to traverse lists like I > traverse arrays in C. This is my first program other than "Hello World". > I have a Raspberry Pi and they say Python is the language of choice for > that little machine. So I am going to try to learn it. > > > I have data in the form of x, y pairs where y = f(x) and is non linear. > It comes from a .csv file. > > In this case x is an integer from 165 to 660 so I have 495 data sets. > > I need to find the optimal locations of three values of x to piecewise > linear estimate the function. > > > So I need to find i, j, k so 165 < i < j < k < 660 and the 4 line > segments [(165, f(165)), (i, f(i))], [(i, f(i)), (j, f(j))], [(j, f(j), > (k, f(k))], [(k, f(k)), (660, f(660))]. > > So as you iterate through the minimize function below, you want something like this, I believe: if (165 < i) and (i < j) and (j < k) and (k < 660): print 'true' else: print 'false' > The value I need to minimize is the square of the difference between the > line estimate and the real value at each of the 495 points. > > > I can do this in C. To keep it simple to understand I will assume the > arrays x[] and y[] and minsum, mini, minj, and mink are global. > > > I have not tested this but this is what I came up with in C. Assuming > x[] and y[] are already filled with the right values. > > > int x[495]; > double y[495]; > max_elements = 495; > double minsum; > int mini, minj, mink > > #We define some vars before utilizing them x,and y are list comprehension # You said int for x, so it's created in ints, and y is in floats x = [num for num in range(0,496)] # You said double for y, so the it's created in floats, and x is an int list y = [float(num) for num in range(0,496)] i = 0 j = 0 k = 0 max_elements = 495 mini = 0 minj = 0 mink = 0 > void minimize(int max_elements) > > def minimize(max_elements): { > minsum = 9999999999999.0; // big big number > > minsum = float(9999999999999.0) # used float just to show as double > for (i=2; i for (j=i+2; j< max_elements -4; j++) > for (k=j+2; k< max_elements-2;k++) > for i in range(2,max_elements-6): print i for j in range(i+2,max_elements-4): print j for k in range(j+2,max_elements-2): print k > { > sum = error(0,i); > sum += error(i,j); > sum += error(j,k); > sum += error(k,495) > > sum = error(0,i) sum += error(i,j) sum += error(j,k) sum += error(k,495) > if (sum < minsum) > { > minsum = sum; > mini = i; > minj = j; > mink = k; > } > } > } > > if sum < minsum: minsum = sum mini = i minj = j mink = k > > double error(int istart, int iend) > { > > error(int istart, int iend): > // linear interpolation I can optimize but left > // it not optimized for clarity of the function > > int m; > > double lin_estimate; > > double errorsq; > > errorsq = 0; > > int m lin_estimate = errorsq = float(0) #just to show double = float type again errorsq = 0 > for (m=istart; m { > lin_estimate = y[istart] + ((y[iend] - y[istart]) * > ((x[m] - x[istart]) / (x[iend] - x[istart]))); > > errorsq += (lin_estimate - y[m]) * (lin_estimate - y[m]); > } > > return (errorsq); > > } > > > > for iterator in range(istart; iend): lin_estimate = y[istart] + ((y[iend] - y[istart]) * ((x[m] - x[istart]) / (x[iend] - x[istart]))) errorsq += (lin_estimate - y[m]) * (lin_estimate - y[m]) return errorsq > At the end the three values I want are mini, minj, mink; > or x[mini], x[minj], x[mink] > > > So how do I do this (or approach this) in Python? > > Loose Translation > > Kip > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > I'll look at it a little more later on, unless someone' is less rusty in C and Python than I am. -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Mon Feb 3 00:50:27 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 18:50:27 -0500 Subject: [Tutor] Traversing lists or getting the element you want. In-Reply-To: References: <1391373998.2058.53975.camel@Red> Message-ID: On Sun, Feb 2, 2014 at 6:44 PM, David Hutto wrote: > > > > On Sun, Feb 2, 2014 at 3:46 PM, Kipton Moravec wrote: > >> I am new to Python, and I do not know how to traverse lists like I >> traverse arrays in C. This is my first program other than "Hello World". >> I have a Raspberry Pi and they say Python is the language of choice for >> that little machine. So I am going to try to learn it. >> >> >> I have data in the form of x, y pairs where y = f(x) and is non linear. >> It comes from a .csv file. >> >> In this case x is an integer from 165 to 660 so I have 495 data sets. >> >> I need to find the optimal locations of three values of x to piecewise >> linear estimate the function. >> >> >> So I need to find i, j, k so 165 < i < j < k < 660 and the 4 line >> segments [(165, f(165)), (i, f(i))], [(i, f(i)), (j, f(j))], [(j, f(j), >> (k, f(k))], [(k, f(k)), (660, f(660))]. >> >> So as you iterate through the minimize function below, you want something > like this, I believe: > > if (165 < i) and (i < j) and (j < k) and (k < 660): > print 'true' > else: > print 'false' > > >> The value I need to minimize is the square of the difference between the >> line estimate and the real value at each of the 495 points. >> >> >> I can do this in C. To keep it simple to understand I will assume the >> arrays x[] and y[] and minsum, mini, minj, and mink are global. >> >> >> I have not tested this but this is what I came up with in C. Assuming >> x[] and y[] are already filled with the right values. >> >> >> int x[495]; >> double y[495]; >> max_elements = 495; >> double minsum; >> int mini, minj, mink >> >> #We define some vars before utilizing them x,and y are list comprehension > # You said int for x, so it's created in ints, and y is in floats > x = [num for num in range(0,496)] > # You said double for y, so the it's created in floats, and x is an int > list > y = [float(num) for num in range(0,496)] > i = 0 > j = 0 > k = 0 > max_elements = 495 > mini = 0 > minj = 0 > mink = 0 > > >> void minimize(int max_elements) >> >> > def minimize(max_elements): > > { >> minsum = 9999999999999.0; // big big number >> >> > minsum = float(9999999999999.0) # used float just to show as double > > > >> for (i=2; i> for (j=i+2; j< max_elements -4; j++) >> for (k=j+2; k< max_elements-2;k++) >> > > for i in range(2,max_elements-6): > print i > for j in range(i+2,max_elements-4): > print j > for k in range(j+2,max_elements-2): > print k > > >> { >> sum = error(0,i); >> sum += error(i,j); >> sum += error(j,k); >> sum += error(k,495) >> >> > sum = error(0,i) > sum += error(i,j) > sum += error(j,k) > sum += error(k,495) > > >> if (sum < minsum) >> { >> minsum = sum; >> mini = i; >> minj = j; >> mink = k; >> } >> } >> } >> >> > > if sum < minsum: > > minsum = sum > mini = i > minj = j > mink = k > > >> >> double error(int istart, int iend) >> { >> >> > error(int istart, int iend): > > > >> // linear interpolation I can optimize but left >> // it not optimized for clarity of the function >> >> int m; >> >> double lin_estimate; >> >> double errorsq; >> >> errorsq = 0; >> >> > Forgot this part: > m = 0 > > lin_estimate = 0 > > errorsq = float(0) #just to show double = float type again > > errorsq = 0 > > > >> for (m=istart; m> { >> lin_estimate = y[istart] + ((y[iend] - y[istart]) * >> ((x[m] - x[istart]) / (x[iend] - x[istart]))); >> >> errorsq += (lin_estimate - y[m]) * (lin_estimate - y[m]); >> } >> >> return (errorsq); >> >> } >> >> >> >> > > for iterator in range(istart; iend): > > lin_estimate = y[istart] + ((y[iend] - y[istart]) * ((x[m] - > x[istart]) / (x[iend] - x[istart]))) > > errorsq += (lin_estimate - y[m]) * (lin_estimate - y[m]) > > return errorsq > > > > >> At the end the three values I want are mini, minj, mink; >> or x[mini], x[minj], x[mink] >> >> >> So how do I do this (or approach this) in Python? >> >> Loose Translation > >> >> Kip >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > I'll look at it a little more later on, unless someone' is less rusty in C > and Python than I am. > > -- > Best Regards, > David Hutto > *CEO:* *http://www.hitwebdevelopment.com > * > > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Mon Feb 3 01:19:00 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Sun, 2 Feb 2014 19:19:00 -0500 Subject: [Tutor] Traversing lists or getting the element you want. In-Reply-To: References: <1391373998.2058.53975.camel@Red> Message-ID: Kind of sure this is the translation line for line: #We define some vars before utilizing them x,and y are list comprehension # You said int for x, so it's created in ints, and y is in floats x = [num for num in range(0,496)] # You said double for y, so the it's created in floats, and x is an int list y = [float(num) for num in range(0,496)] i = 0 j = 0 k = 0 max_elements = 495 mini = 0 minj = 0 mink = 0 def minimize(max_elements): minsum = float(9999999999999.0) # used float just to show as double for i in range(2,max_elements-6): for j in range(i+2,max_elements-4): for k in range(j+2,max_elements-2): sum = error(0,i) sum += error(i,j) sum += error(j,k) sum += error(k,495) if sum < minsum: minsum = sum mini = i minj = j mink = k def error(istart,iend): m = 0 lin_estimate = 0 errorsq = float(0) #just to show double = float type again errorsq = 0 lin_estimate = y[istart] + ((y[iend] - y[istart]) * ((x[m] - x[istart]) / (x[iend] - x[istart]))) errorsq += (lin_estimate - y[m]) * (lin_estimate - y[m]) #print errorsq # insert print for quick in line debugging by uncommenting return errorsq #Call function minimize minimize(max_elements) Don't forget the tabs , or spaces, and the forced indentation. On Sun, Feb 2, 2014 at 6:44 PM, David Hutto wrote: > > > > On Sun, Feb 2, 2014 at 3:46 PM, Kipton Moravec wrote: > >> I am new to Python, and I do not know how to traverse lists like I >> traverse arrays in C. This is my first program other than "Hello World". >> I have a Raspberry Pi and they say Python is the language of choice for >> that little machine. So I am going to try to learn it. >> >> >> I have data in the form of x, y pairs where y = f(x) and is non linear. >> It comes from a .csv file. >> >> In this case x is an integer from 165 to 660 so I have 495 data sets. >> >> I need to find the optimal locations of three values of x to piecewise >> linear estimate the function. >> >> >> So I need to find i, j, k so 165 < i < j < k < 660 and the 4 line >> segments [(165, f(165)), (i, f(i))], [(i, f(i)), (j, f(j))], [(j, f(j), >> (k, f(k))], [(k, f(k)), (660, f(660))]. >> >> So as you iterate through the minimize function below, you want something > like this, I believe: > > if (165 < i) and (i < j) and (j < k) and (k < 660): > print 'true' > else: > print 'false' > > >> The value I need to minimize is the square of the difference between the >> line estimate and the real value at each of the 495 points. >> >> >> I can do this in C. To keep it simple to understand I will assume the >> arrays x[] and y[] and minsum, mini, minj, and mink are global. >> >> >> I have not tested this but this is what I came up with in C. Assuming >> x[] and y[] are already filled with the right values. >> >> >> int x[495]; >> double y[495]; >> max_elements = 495; >> double minsum; >> int mini, minj, mink >> >> #We define some vars before utilizing them x,and y are list comprehension > # You said int for x, so it's created in ints, and y is in floats > x = [num for num in range(0,496)] > # You said double for y, so the it's created in floats, and x is an int > list > y = [float(num) for num in range(0,496)] > i = 0 > j = 0 > k = 0 > max_elements = 495 > mini = 0 > minj = 0 > mink = 0 > > >> void minimize(int max_elements) >> >> > def minimize(max_elements): > > { >> minsum = 9999999999999.0; // big big number >> >> > minsum = float(9999999999999.0) # used float just to show as double > > > >> for (i=2; i> for (j=i+2; j< max_elements -4; j++) >> for (k=j+2; k< max_elements-2;k++) >> > > for i in range(2,max_elements-6): > print i > for j in range(i+2,max_elements-4): > print j > for k in range(j+2,max_elements-2): > print k > > >> { >> sum = error(0,i); >> sum += error(i,j); >> sum += error(j,k); >> sum += error(k,495) >> >> > sum = error(0,i) > sum += error(i,j) > sum += error(j,k) > sum += error(k,495) > > >> if (sum < minsum) >> { >> minsum = sum; >> mini = i; >> minj = j; >> mink = k; >> } >> } >> } >> >> > > if sum < minsum: > > minsum = sum > mini = i > minj = j > mink = k > > >> >> double error(int istart, int iend) >> { >> >> > error(int istart, int iend): > > > >> // linear interpolation I can optimize but left >> // it not optimized for clarity of the function >> >> int m; >> >> double lin_estimate; >> >> double errorsq; >> >> errorsq = 0; >> >> > > int m > > lin_estimate = > > errorsq = float(0) #just to show double = float type again > > errorsq = 0 > > > >> for (m=istart; m> { >> lin_estimate = y[istart] + ((y[iend] - y[istart]) * >> ((x[m] - x[istart]) / (x[iend] - x[istart]))); >> >> errorsq += (lin_estimate - y[m]) * (lin_estimate - y[m]); >> } >> >> return (errorsq); >> >> } >> >> >> >> > > for iterator in range(istart; iend): > > lin_estimate = y[istart] + ((y[iend] - y[istart]) * ((x[m] - > x[istart]) / (x[iend] - x[istart]))) > > errorsq += (lin_estimate - y[m]) * (lin_estimate - y[m]) > > return errorsq > > > > >> At the end the three values I want are mini, minj, mink; >> or x[mini], x[minj], x[mink] >> >> >> So how do I do this (or approach this) in Python? >> >> Loose Translation > >> >> Kip >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > I'll look at it a little more later on, unless someone' is less rusty in C > and Python than I am. > > -- > Best Regards, > David Hutto > *CEO:* *http://www.hitwebdevelopment.com > * > > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Feb 3 01:22:45 2014 From: davea at davea.name (Dave Angel) Date: Sun, 2 Feb 2014 19:22:45 -0500 (EST) Subject: [Tutor] Traversing lists or getting the element you want. References: <1391373998.2058.53975.camel@Red> Message-ID: Kipton Moravec Wrote in message: > I am new to Python, and I do not know how to traverse lists like I > traverse arrays in C. This is my first program other than "Hello World". > I have a Raspberry Pi and they say Python is the language of choice for > that little machine. So I am going to try to learn it. > > > I have data in the form of x, y pairs where y = f(x) and is non linear. > It comes from a .csv file. > Sounds to me that you've just got a y list; your x list has the implicit assumption of being range (165,660) > In this case x is an integer from 165 to 660 so I have 495 data sets. > > I need to find the optimal locations of three values of x to piecewise > linear estimate the function. > You're making the unspoken assumption that each line starts and ends exactly on a data point. That won't give you the minimum error in general, but perhaps it is an extra oddball restriction in the assignment. > > So I need to find i, j, k so 165 < i < j < k < 660 and the 4 line > segments [(165, f(165)), (i, f(i))], [(i, f(i)), (j, f(j))], [(j, f(j), > (k, f(k))], [(k, f(k)), (660, f(660))]. > > > The value I need to minimize is the square of the difference between the > line estimate and the real value at each of the 495 points. No it appears to be the sum of the squares. > > > I can do this in C. To keep it simple to understand I will assume the > arrays x[] and y[] and minsum, mini, minj, and mink are global. > That may seem to simplify the c but it's not pythonic. If a function calculates 4 values, it should return 4 values, presumably as a tuple. > > I have not tested this but this is what I came up with in C. Assuming > x[] and y[] are already filled with the right values. > > > int x[495]; > double y[495]; > max_elements = 495; > double minsum; > int mini, minj, mink > > > void minimize(int max_elements) > > { > minsum = 9999999999999.0; // big big number > > for (i=2; i for (j=i+2; j< max_elements -4; j++) > for (k=j+2; k< max_elements-2;k++) > { > sum = error(0,i); > sum += error(i,j); > sum += error(j,k); > sum += error(k,495) > > if (sum < minsum) > { > minsum = sum; > mini = i; > minj = j; > mink = k; > } > } > } > > > double error(int istart, int iend) > { > > // linear interpolation I can optimize but left > // it not optimized for clarity of the function > > int m; > > double lin_estimate; > > double errorsq; > > errorsq = 0; > > for (m=istart; m { > lin_estimate = y[istart] + ((y[iend] ??? y[istart]) * > ((x[m] ??? x[istart]) / (x[iend] ??? x[istart]))); > > errorsq += (lin_estimate ??? y[m]) * (lin_estimate ??? y[m]); > } > > return (errorsq); > > } > > > > At the end the three values I want are mini, minj, mink; > or x[mini], x[minj], x[mink] > > > So how do I do this (or approach this) in Python? > > for (i=2; i References: <1391373998.2058.53975.camel@Red> Message-ID: <20140203005713.GT3799@ando> On Sun, Feb 02, 2014 at 02:46:38PM -0600, Kipton Moravec wrote: > I am new to Python, and I do not know how to traverse lists like I > traverse arrays in C. You can do this, but normally shouldn't: data = [2, 4, 8, 16, 32] for i in range(0, len(data)): x = data[i] print(x) That is a more-or-less exact translation of what you might do in a language like C or Pascal. But in Python, it's not considered good form. (Although, if you are doing a direct translation of some C code, it might be acceptable.) Instead, you should iterate directly over the elements of the list: data = [2, 4, 8, 16, 32] for x in data: print(x) (Python's for-loop is what some other languages call "for-each".) If you need the index as well, you can do this: data = [2, 4, 8, 16, 32] for i, x in enumerate(data): print(i, x) The rest of your question seems pretty interesting, unfortunately I don't have time to get into it now. Good luck! -- Steven From denis.spir at gmail.com Mon Feb 3 08:52:44 2014 From: denis.spir at gmail.com (spir) Date: Mon, 03 Feb 2014 08:52:44 +0100 Subject: [Tutor] sorting and writing to data file In-Reply-To: References: Message-ID: <52EF4ACC.90106@gmail.com> On 02/02/2014 04:08 AM, adrian wrote: > Hello community, > > Newbie here. I have a data (.dat) file with integers (2,9,1,5,7,3,9) in it just > as shown. > My instructions are to sort the numbers and rewrite them back to the data file. > > *here is my code:** > * > lab3int=[2,9,1,5,7,3,9] > lab3int.sort() > print(lab3int) > lab3int=open('lab3int.dat','w') > lab3int.write() > lab3int.close() > > *here is my error message:* > > [1, 2, 3, 5, 7, 9, 9] > Traceback (most recent call last): > File "lab3int.py", line 5, in > lab3int.write() > TypeError: function takes exactly 1 argument (0 given) > > > I know that it is telling me that my error is in line #5. If I put anything in > the () for lab3int.write function, then that appears in my data file. however, > I am looking to just put the re-sorted integers back into the data file without > having to manually type each integer manually. Is there something that i can > put into the lab3int.write() to make that happen? > > Hope my problem is clear, Thanks people Do you realise you are calling two different very objects, a list of nums and a file, with the same name 'lab3int'? d From denis.spir at gmail.com Mon Feb 3 08:57:59 2014 From: denis.spir at gmail.com (spir) Date: Mon, 03 Feb 2014 08:57:59 +0100 Subject: [Tutor] most useful ide In-Reply-To: <52EEA64C.7020409@ncf.ca> References: <52EEA64C.7020409@ncf.ca> Message-ID: <52EF4C07.7010602@gmail.com> On 02/02/2014 09:10 PM, Pierre Dagenais wrote: > > > On 14-02-02 01:16 PM, Kodiak Firesmith wrote: >> Pycharm is nice for bigger projects (since tou can collapse any section); >> but it's crazy resource intensive. For Linux Gedit can be made very nice > > I prefer Geany as it will run my code with a click of the mouse. geany is my favorite editor as well I'd use gedit for its simplicity, but cannot survive an editor without the 'duplicate' command (ctrl-d). d From denis.spir at gmail.com Mon Feb 3 08:59:09 2014 From: denis.spir at gmail.com (spir) Date: Mon, 03 Feb 2014 08:59:09 +0100 Subject: [Tutor] most useful ide In-Reply-To: <52EEA64C.7020409@ncf.ca> References: <52EEA64C.7020409@ncf.ca> Message-ID: <52EF4C4D.70206@gmail.com> On 02/02/2014 09:10 PM, Pierre Dagenais wrote: > > > On 14-02-02 01:16 PM, Kodiak Firesmith wrote: >> Pycharm is nice for bigger projects (since tou can collapse any section); >> but it's crazy resource intensive. For Linux Gedit can be made very nice > > I prefer Geany as it will run my code with a click of the mouse. but geany has terrible language-specific settings (and no interface for them) (and you need to find them first somewhere in your filesystem...) d From denis.spir at gmail.com Mon Feb 3 09:28:12 2014 From: denis.spir at gmail.com (spir) Date: Mon, 03 Feb 2014 09:28:12 +0100 Subject: [Tutor] Traversing lists or getting the element you want. In-Reply-To: <1391373998.2058.53975.camel@Red> References: <1391373998.2058.53975.camel@Red> Message-ID: <52EF531C.5050003@gmail.com> On 02/02/2014 09:46 PM, Kipton Moravec wrote: > I am new to Python, and I do not know how to traverse lists like I > traverse arrays in C. This is my first program other than "Hello World". > I have a Raspberry Pi and they say Python is the language of choice for > that little machine. So I am going to try to learn it. Traversing an array of 'n' float item in C, using index instead of pointer, may translate to: float item; uint i; // 0 <= i < n !!! for (i=0 ; i I have data in the form of x, y pairs where y = f(x) and is non linear. > It comes from a .csv file. > > In this case x is an integer from 165 to 660 so I have 495 data sets. > > I need to find the optimal locations of three values of x to piecewise > linear estimate the function. > > > So I need to find i, j, k so 165 < i < j < k < 660 and the 4 line > segments [(165, f(165)), (i, f(i))], [(i, f(i)), (j, f(j))], [(j, f(j), > (k, f(k))], [(k, f(k)), (660, f(660))]. > > > The value I need to minimize is the square of the difference between the > line estimate and the real value at each of the 495 points. > > > I can do this in C. To keep it simple to understand I will assume the > arrays x[] and y[] and minsum, mini, minj, and mink are global. > > > I have not tested this but this is what I came up with in C. Assuming > x[] and y[] are already filled with the right values. > > > int x[495]; > double y[495]; > max_elements = 495; > double minsum; > int mini, minj, mink > > > void minimize(int max_elements) > > { > minsum = 9999999999999.0; // big big number This is more or less a logical error (but one very very frequent). What if the array is empty? This gives: min(nothing_at_all)=9999999999999.0. min(nothing) is undefined, an anomaly or error. You should probably: * refuse an empty array (the caller should not call the func at all) * start with the first item as (temporary) min value (Same for all similar 'reduce' functions.) I understand you're not writing a simple min func here (instead minimising deviations to a hypothetical average) but the thinking pattern is the same. A sane min func may look like --i take the opportuity to show you some python code: def min_nums (nums): n = len(nums) assert n > 0, "are you kidding?" min = nums[0] for i in range(2, n): num = nums[i] if num < min: min = num return min nums = [6,4,5,8,3,1,2,7,8] print(min_nums(nums)) print(min_nums([])) > for (i=2; i for (j=i+2; j< max_elements -4; j++) > for (k=j+2; k< max_elements-2;k++) > { > sum = error(0,i); > sum += error(i,j); > sum += error(j,k); > sum += error(k,495) > > if (sum < minsum) > { > minsum = sum; > mini = i; > minj = j; > mink = k; > } > } > } You could export in a sub-func the detail computation of the minimised element. Then, you could test it apart, and your minimise func would be barely more complicated than the one above (mine). > double error(int istart, int iend) > { > > // linear interpolation I can optimize but left > // it not optimized for clarity of the function > > int m; > > double lin_estimate; > > double errorsq; > > errorsq = 0; > > for (m=istart; m { > lin_estimate = y[istart] + ((y[iend] ? y[istart]) * > ((x[m] ? x[istart]) / (x[iend] ? x[istart]))); > > errorsq += (lin_estimate ? y[m]) * (lin_estimate ? y[m]); > } > > return (errorsq); > > } > > > > At the end the three values I want are mini, minj, mink; > or x[mini], x[minj], x[mink] > > > So how do I do this (or approach this) in Python? > > > Kip Apart for the traversing idiom ('range' or 'for...in') the code is similar. (It also has '+=' and friends). (According to Guido van Rossum, Python was in fact designed to please C/Unix hackers; apart from the indented syntax and some idioms, it is indeed very similar, including a number of "unguessable" terms.) d From duxbuz at hotmail.com Mon Feb 3 11:30:59 2014 From: duxbuz at hotmail.com (Ian D) Date: Mon, 3 Feb 2014 10:30:59 +0000 Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: Thanks for all the responses I was mainly looking for a more user friendly ide in a windows environment with things like command completion etc. Like something a novice might use. I suppose vi is simple and available for windows but I don't suppose there would be command completion even in vim. I don't really use emacs much so not that. I suppose idle will suffice, I just wondered if there was another ide simple like idle but a little more helpful like eclipse, but not eclipse. ha ha. Ok its a poor question.... ps. I know idle has command completion, but just wondered if there is something with a few more bells and whistles. From: duxbuz at hotmail.com To: tutor at python.org Date: Sun, 2 Feb 2014 08:25:16 +0000 Subject: [Tutor] most useful ide Hi Are there any recommendations for python ide's currently I am using idle, which seems pretty decent but am open to any suggestions cheers _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Feb 3 12:37:42 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 3 Feb 2014 11:37:42 +0000 Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: <20140203113739.GD2213@gmail.com> On Mon, Feb 03, 2014 at 10:30:59AM +0000, Ian D wrote: > Thanks for all the responses > > I was mainly looking for a more user friendly ide in a windows environment > with things like command completion etc. Like something a novice might use. > I suppose vi is simple and available for windows but I don't suppose there > would be command completion even in vim. Vim supports all kinds of different completion: http://robots.thoughtbot.com/vim-you-complete-me I've also used jedi. I used it some time ago when it was new and a bit buggy. It started to annoy me after a while so I disabled it but it might be better now: http://jedi.jedidjah.ch/en/latest/ See also: http://sontek.net/blog/detail/turning-vim-into-a-modern-python-ide Vim has a steep learning curve but in my experience if you can get past the initial fight then it's definitely worth it. Another advantage of Vim for me is that it tends to be installed on all of the remote machines that I use so that I can transparently run it over ssh in the terminal. Similarly on Linux I can use it from the virtual terminals which is very handy when you've screwed your computer! Oscar From alan.gauld at btinternet.com Mon Feb 3 13:24:36 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Feb 2014 12:24:36 +0000 Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: On 03/02/14 10:30, Ian D wrote: > I was mainly looking for a more user friendly ide in a windows If you are on windows then look at Pythonwin it's similar to IDLE but much more windows friendly and has some extra tools for working with Windows (eg a COM object inspector) You get it in the winall package or if you download the Activestate Python distro its included (along with much else) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Mon Feb 3 14:35:42 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Feb 2014 14:35:42 +0100 Subject: [Tutor] Traversing lists or getting the element you want. References: <1391373998.2058.53975.camel@Red> Message-ID: Kipton Moravec wrote: > I am new to Python, and I do not know how to traverse lists like I > traverse arrays in C. This is my first program other than "Hello World". > I have a Raspberry Pi and they say Python is the language of choice for > that little machine. So I am going to try to learn it. > > > I have data in the form of x, y pairs where y = f(x) and is non linear. > It comes from a .csv file. > > In this case x is an integer from 165 to 660 so I have 495 data sets. > > I need to find the optimal locations of three values of x to piecewise > linear estimate the function. import itertools def boundaries(n, segments): max_n = n-1 for inner in itertools.combinations(range(n), segments-2): yield (0,) + inner + (max_n,) def minimized(x, y, segments): def total_error(b): return sum(error(x, y, start, end) for start, end in zip(b, b[1:])) return min(boundaries(len(x), segments), key=total_error) def error(x, y, istart, iend): errorsq = 0 for m in range(istart, iend): lin_estimate = y[istart] + ((y[iend] - y[istart]) * ((x[m] - x[istart]) / (x[iend] - x[istart]))) d = lin_estimate - y[m] errorsq += d*d return errorsq if __name__ == "__main__": # generate dataset with N random (x, y) pairs import random N = 100 random.seed(42) # want reproducible result data = [ (random.random()*10, random.random()*100-50.) for _ in range(N)] print minimized([x for x, y in data], [y for x, y in data], 4) As this is mostly number crunching the Python version is probably a lot slower than the C code. I tried to move the inner loop into numpy with import numpy [...] def error(x, y, istart, iend): lin_estimate = y[istart] + ((y[iend] - y[istart]) * ((x[istart:iend] - x[istart]) / (x[iend] - x[istart]))) delta = lin_estimate - y[istart:iend] return (delta*delta).sum() [...] print minimized(numpy.array([x for x, y in data]), numpy.array([y for x, y in data]), 4) but that had no noticeable effect. There may be potential gains for someone willing to put in more work or with better knowledge of numpy. By the way, your method of calculating the error > double error(int istart, int iend) > { > > // linear interpolation I can optimize but left > // it not optimized for clarity of the function > > int m; > double lin_estimate; > double errorsq; > errorsq = 0; > > for (m=istart; m { > lin_estimate = y[istart] + ((y[iend] ? y[istart]) * > ((x[m] ? x[istart]) / (x[iend] ? x[istart]))); > > errorsq += (lin_estimate ? y[m]) * (lin_estimate ? y[m]); > } > return (errorsq); > } (which I adopted) looks odd. With a tried and tested method like "least square fit" which does not require the line (segments) to go through any point of the dataset you should get better fits. PS: Caveat emptor! I did not even plot a graph with the result to check plausibility; there may be embarassing errors. From francois.dion at gmail.com Mon Feb 3 18:26:49 2014 From: francois.dion at gmail.com (Francois Dion) Date: Mon, 3 Feb 2014 12:26:49 -0500 Subject: [Tutor] most useful ide In-Reply-To: References: Message-ID: On Sun, Feb 2, 2014 at 3:25 AM, Ian D wrote: > Are there any recommendations for python ide's > Since you mentionned windows and lightweight and autocompletion, i'd take a look at ninja-ide (http://ninja-ide.org/). It is relatively lightweight. In my case, I use pycharm for larger projects (vcs integration etc), scribes for a graphical editor for one off scripts, vim and bpython (very nice for exploring - autocompletion and autodoc) from the command line, brython console in the web browser and ipython notebook for matlab type "coding" (exploration). Another suggestion would be sublimetext. It is a text editor, but it can handle multiple tabs and it has a folder browser. You can also run the code (ctrl-b) etc. I've used it, but not in the past 6 months. And you might also want to look at pythonxy, canopy and anaconda for a simpler install experience under windows. Francois --- www.pyptug.org - raspberry-python.blogspot.com - @f_dion -------------- next part -------------- An HTML attachment was scrubbed... URL: From premanshu999 at yahoo.co.in Mon Feb 3 16:54:00 2014 From: premanshu999 at yahoo.co.in (premanshu basak) Date: Mon, 3 Feb 2014 23:54:00 +0800 (SGT) Subject: [Tutor] My First Post Message-ID: <1391442840.17586.YahooMailBasic@web195001.mail.sg3.yahoo.com> Hi I am Premanshu. I have recently started learning python programming language and have question. Most of them I have googled out however I still have some which i could not find a satisfactory answer. While searching for a forum i cam across this forum so posting my question. Please guide me to the right place if this is not where i must look for my answer. My question is as below:- while going through a wx python Tutoria to create GUI's I have come across a method "Bind". Basically i created a frame then a file menu in it with a exit button as the content. Further the tutorial explain how to Bind the close method to the Exit button that I created in which it uses a argument EVT_MENU. I would actually want to understand the whole of the Bind method...as in what all arguments it takes and what argument is what in it.... Thank you very much in advance. Regards, Premanshu From alan.gauld at btinternet.com Mon Feb 3 19:47:43 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Feb 2014 18:47:43 +0000 Subject: [Tutor] My First Post In-Reply-To: <1391442840.17586.YahooMailBasic@web195001.mail.sg3.yahoo.com> References: <1391442840.17586.YahooMailBasic@web195001.mail.sg3.yahoo.com> Message-ID: On 03/02/14 15:54, premanshu basak wrote: > I am Premanshu. I have recently started learning python programming language and have question. welcome. We are always happy to try to answer questions although our focus is on the python language and its standard library. If we know about a thitrd party library we may well have a go at that too... > while going through a wx python Tutoria to create GUI's I have come across > a method "Bind". ... > I would actually want to understand the whole of the Bind method... The best place to ask for wxPython help is on the wxPython mailing list. However, some folks here do use wxPython so you may well get an answer. But if you need more depth try the wxPython list. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From gb.gabrielebrambilla at gmail.com Mon Feb 3 19:48:08 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 3 Feb 2014 13:48:08 -0500 Subject: [Tutor] strange errors In-Reply-To: References: Message-ID: an example of errors that I obtain is: I build a matrix (SciPy array) using the same data. I search for the maximum and the minimum with the given function and I insert the two values in a tuple that I print. sometimes it print to me this: (0.0, 3.1926676650124463e-14) sometimes it print to me: (nan, nan) Thanks Gabriele 2014-02-02 Alan Gauld : > On 02/02/14 02:11, Gabriele Brambilla wrote: > > sometimes when I try to run a program in Python I obtain some errors. >> > > How are you running the program? > > doubly clicking in a file manager/explorer? > Running from an OS command line? > Importing from the Python >>> prompt? > Or using some kind of IDE? (Which?) > > The answer to your question depends a lot on the way you > run the code. > > A sample error and your OS and Python version will help too. > > > How could I avoid this problem? I think that it is because it "remember" >> some variables that I have used... >> > > Could be. If you import a module then change that module then > reimporting alone is not enough. But if you run the code from the OS that > shouldn't be an issue. So how do you run the code? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 3 19:53:45 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 3 Feb 2014 18:53:45 +0000 (GMT) Subject: [Tutor] strange errors In-Reply-To: References: Message-ID: <1391453625.52045.YahooMailNeo@web186004.mail.ir2.yahoo.com> >an example of errors that I obtain is: I build a matrix (SciPy array) using the same data. >I search for the maximum and the minimum with the given function and I insert the two values in a tuple that I print. >sometimes it print to me this:?(0.0, 3.1926676650124463e-14) >sometimes it print to me: (nan, nan) > >That looks like in may be a scipy issue rather than core Python. We do have some SciPy users who may be able to help, but it? would be easier if they could see the function and calling code? you are using. Also you may get better help on the scipy mailing list/web fora. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Feb 3 20:12:38 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Feb 2014 20:12:38 +0100 Subject: [Tutor] strange errors References: Message-ID: Gabriele Brambilla wrote: > an example of errors that I obtain is: I build a matrix (SciPy array) > using the same data. > I search for the maximum and the minimum with the given function and I > insert the two values in a tuple that I print. > sometimes it print to me this: (0.0, 3.1926676650124463e-14) > sometimes it print to me: (nan, nan) Are you messing around with byteorder or other lowlevel stuff? Can you provide a small script that shows this behaviour? From gb.gabrielebrambilla at gmail.com Mon Feb 3 20:17:30 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 3 Feb 2014 14:17:30 -0500 Subject: [Tutor] strange errors In-Reply-To: References: Message-ID: No, i'm not using lowlevel stuff...which part of the script do you want to see? thanks Gabriele 2014-02-03 Peter Otten <__peter__ at web.de>: > Gabriele Brambilla wrote: > > > an example of errors that I obtain is: I build a matrix (SciPy array) > > using the same data. > > I search for the maximum and the minimum with the given function and I > > insert the two values in a tuple that I print. > > sometimes it print to me this: (0.0, 3.1926676650124463e-14) > > sometimes it print to me: (nan, nan) > > Are you messing around with byteorder or other lowlevel stuff? > Can you provide a small script that shows this behaviour? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Feb 3 20:29:12 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Feb 2014 20:29:12 +0100 Subject: [Tutor] strange errors References: Message-ID: Gabriele Brambilla wrote: > No, i'm not using lowlevel stuff...which part of the script do you want > to see? The part that remains when you throw out everything that has no effect on the "strange errors" ;) For example if you have a routine def load_data(filename): ... # do complex processing return some_array that reads a custom file format, and your script still fails when you replace that by def load_data(filename): return numpy.array([42.0]) then post the simplified version. In that spirit apply every simplification you can think of, then make sure that your script still fails, then post. Alternatively, post the whole beast and hope that someone will care enough and find the needle in the haystack. From malaclypse2 at gmail.com Mon Feb 3 20:46:28 2014 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 3 Feb 2014 14:46:28 -0500 Subject: [Tutor] strange errors In-Reply-To: References: Message-ID: On Mon, Feb 3, 2014 at 2:17 PM, Gabriele Brambilla wrote: > No, i'm not using lowlevel stuff...which part of the script do you want to > see? Since you asked, what we'd really like to see is a Short, Self Contained, Compilable Example (see http://sscce.org/). That is, an example that is short enough to be read quickly, self contained enough so that we can actually save the code and run it, compilable in that the code will run, at least to the point where you're having a problem (it's fine to have code that won't run, as long as the error that pops up is the error you're actually looking for help with). We know that it can be a lot of work to create an example like that, but if you do there are two things that are likely to happen. First, probably 75% of the time, you will find your problem yourself without ever having to post it to the list. The very act of trimming your code into the piece that demonstrates your problem, will help you find the problem yourself. Second, you are very, very likely to get people to pay attention to your question and provide advice on how to fix your code when you make it easy for them to help. -- Jerry From dyoo at hashcollision.org Tue Feb 4 03:17:08 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 3 Feb 2014 18:17:08 -0800 Subject: [Tutor] My First Post In-Reply-To: References: <1391442840.17586.YahooMailBasic@web195001.mail.sg3.yahoo.com> Message-ID: Just as you might look at a dictionary to find the meaning of a word, you'll look at library documentation to look for the meaning of a method. Most likely, you may need to refer to the documentation of the library in question. I do not know if this is the method you are looking at, but here is something about a "bind" related to wxPython: http://www.wxpython.org/docs/api/wx.EvtHandler-class.html#Bind http://wxpython.org/Phoenix/docs/html/events_overview.html The first link is in the style of a reference manual: very terse, but with technical detail. The second link appears to be user-level documentation, with examples and a description of the event model. From dyoo at hashcollision.org Tue Feb 4 03:20:23 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 3 Feb 2014 18:20:23 -0800 Subject: [Tutor] My First Post Message-ID: (Sorry if you get this message twice: I think I accidently mis-sent the message to the wrong address, so to make sure, I'm sending to what I think is the right address this time.) --- Hi Premanshu, Just as you might look at a dictionary to find the meaning of a word, you'll look at library documentation to look for the meaning of a method. Most likely, you may need to refer to the documentation of the library in question. I do not know if this is the method you are looking at, but here is something about a "bind" related to wxPython: http://www.wxpython.org/docs/api/wx.EvtHandler-class.html#Bind http://wxpython.org/Phoenix/docs/html/events_overview.html The first link is in the style of a reference manual: very terse, but with technical detail. The second link appears to be user-level documentation, with examples and a description of the event model. Good luck to you! From kip at kdream.com Tue Feb 4 06:07:02 2014 From: kip at kdream.com (Kipton Moravec) Date: Mon, 03 Feb 2014 23:07:02 -0600 Subject: [Tutor] Traversing lists or getting the element you want. In-Reply-To: References: <1391373998.2058.53975.camel@Red> Message-ID: <1391490422.2058.54096.camel@Red> Thanks to all that helped on this one. I missed in my reading that you can address an element of a list as y[i]. Going back through "Think Python" book, they have one example of it. And spend 1/4 page out of the 263 pages in the book. They spend much more time on other parts of lists like slices, and methods, etc. For the record, this particular problem had to be linear, and I have to have the endpoint of one segment be the same point as the beginning of the next segment for the particular integer x[]. So I could not do a normal linear regression and least square fit for the line segment. My book also does not have anything about itertools, so I have never heard of that. So I will google it to learn more. Thanks, again, Kip On Mon, 2014-02-03 at 14:35 +0100, Peter Otten wrote: > Kipton Moravec wrote: > > > I am new to Python, and I do not know how to traverse lists like I > > traverse arrays in C. This is my first program other than "Hello World". > > I have a Raspberry Pi and they say Python is the language of choice for > > that little machine. So I am going to try to learn it. > > > > > > I have data in the form of x, y pairs where y = f(x) and is non linear. > > It comes from a .csv file. > > > > In this case x is an integer from 165 to 660 so I have 495 data sets. > > > > I need to find the optimal locations of three values of x to piecewise > > linear estimate the function. > > import itertools > > def boundaries(n, segments): > max_n = n-1 > for inner in itertools.combinations(range(n), segments-2): > yield (0,) + inner + (max_n,) > > def minimized(x, y, segments): > def total_error(b): > return sum(error(x, y, start, end) for start, end in zip(b, b[1:])) > return min(boundaries(len(x), segments), key=total_error) > > def error(x, y, istart, iend): > errorsq = 0 > for m in range(istart, iend): > lin_estimate = y[istart] + ((y[iend] - y[istart]) * > ((x[m] - x[istart]) / (x[iend] - x[istart]))) > d = lin_estimate - y[m] > errorsq += d*d > return errorsq > > if __name__ == "__main__": > # generate dataset with N random (x, y) pairs > import random > N = 100 > random.seed(42) # want reproducible result > data = [ > (random.random()*10, random.random()*100-50.) > for _ in range(N)] > > > print minimized([x for x, y in data], > [y for x, y in data], 4) > > > As this is mostly number crunching the Python version is probably a lot > slower than the C code. I tried to move the inner loop into numpy with > import numpy > > [...] > > def error(x, y, istart, iend): > lin_estimate = y[istart] + ((y[iend] - y[istart]) * > ((x[istart:iend] - x[istart]) / (x[iend] - x[istart]))) > delta = lin_estimate - y[istart:iend] > return (delta*delta).sum() > > [...] > > print minimized(numpy.array([x for x, y in data]), > numpy.array([y for x, y in data]), 4) > > but that had no noticeable effect. There may be potential gains for someone > willing to put in more work or with better knowledge of numpy. > > > By the way, your method of calculating the error > > > double error(int istart, int iend) > > { > > > > // linear interpolation I can optimize but left > > // it not optimized for clarity of the function > > > > int m; > > double lin_estimate; > > double errorsq; > > errorsq = 0; > > > > for (m=istart; m > { > > lin_estimate = y[istart] + ((y[iend] ? y[istart]) * > > ((x[m] ? x[istart]) / (x[iend] ? x[istart]))); > > > > errorsq += (lin_estimate ? y[m]) * (lin_estimate ? y[m]); > > } > > return (errorsq); > > } > > (which I adopted) looks odd. With a tried and tested method like "least > square fit" which does not require the line (segments) to go through any > point of the dataset you should get better fits. > > PS: Caveat emptor! I did not even plot a graph with the result to check > plausibility; there may be embarassing errors. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From duxbuz at hotmail.com Tue Feb 4 10:01:32 2014 From: duxbuz at hotmail.com (Ian D) Date: Tue, 4 Feb 2014 09:01:32 +0000 Subject: [Tutor] input python 3.3 Message-ID: Hello I used to use 2.7 and the input was pretty when inputting a numeric value, it would just get cast to an int. Seems that 3.3 I have to cast each input so : float(num1 = input("Enter a number") Is this just they way it is now? Is there a way to get back to just typing: num1 = input("Enter a number ") in python 33. Seems a backwards step unless (and am sure this is the case)it is beneficial in so many other ways? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From duxbuz at hotmail.com Tue Feb 4 10:09:19 2014 From: duxbuz at hotmail.com (Ian D) Date: Tue, 4 Feb 2014 09:09:19 +0000 Subject: [Tutor] input syntax I just posted totally wrong Message-ID: num1 = float(input("enter a number ")) I meant not float(num1 = input("Enter a number")) -------------- next part -------------- An HTML attachment was scrubbed... URL: From cowtux250 at gmail.com Tue Feb 4 10:10:46 2014 From: cowtux250 at gmail.com (Dayo) Date: Tue, 04 Feb 2014 11:10:46 +0200 Subject: [Tutor] Rsync script hangs after a while Message-ID: <52F0AE96.5070103@gmail.com> Hi I wrote this script (http://bpaste.net/show/175284/) to help me automate some rsync backups, and whenever I run the script for large syncs, it just freezes after a while, and then I have to Ctrl+C it. I can find any clues in both source and target /var/log/* files. Any idea how I can find out what's wrong with this thing? Thanks Dayo From __peter__ at web.de Tue Feb 4 10:18:07 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Feb 2014 10:18:07 +0100 Subject: [Tutor] input python 3.3 References: Message-ID: Ian D wrote: > Hello > > I used to use 2.7 and the input was pretty when inputting a numeric value, > it would just get cast to an int. > > Seems that 3.3 I have to cast each input so : > float(num1 = input("Enter a number") You mean num1 = float(input("Enter a number")) > Is this just they way it is now? Is there a way to get back to just > typing: > num1 = input("Enter a number ") > in python 33. > > Seems a backwards step unless (and am sure this is the case)it is > beneficial in so many other ways? input() in Python 2 did not just recognize numbers, it allowed you to evaluate an arbitrary Python expression. For example: $ touch important_file $ ls important_file $ python Python 2.7.2+ (default, Jul 20 2012, 22:15:08) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> input("Enter a number: ") Enter a number: __import__("os").remove("important_file") >>> $ ls Oops, the file is gone. I'm sure you can see why this is dangerous. Therefore the recommendation for Python 2 is to use raw_input() instead of input() -- and for Python 3 raw_input() was renamed to the more obvious input(). You can get the old input() behaviour with num1 = eval(input(...)) which is still dangerous, but makes the risk more obvious. From joshkmalone18 at gmail.com Tue Feb 4 01:35:58 2014 From: joshkmalone18 at gmail.com (josh Malone) Date: Mon, 3 Feb 2014 16:35:58 -0800 Subject: [Tutor] Any ideas Message-ID: Hi, I'm very new to programming and python is my first language. I'm currently enrolled in a class at Oregon State University where we are taught to program in python. I'm stuck on one problem and i know what i want to do... i just have no idea how to write the program. The question is as follows Consider four missiles initially located at the four corners of a square with a side of 100m. Model their behavior if each missile moves with a speed of 5m/s in the direction pointing directly at the missile counter-clockwise from itself. I think i can do most of this, i'm just confused on how to make the spheres continually change their direction. I'm assuming it has something to do with a while loop or possibly an if statement. Any help you could give me would be great! thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From siobhanwojcik at gmail.com Tue Feb 4 02:46:34 2014 From: siobhanwojcik at gmail.com (Siobhan Wojcik) Date: Mon, 3 Feb 2014 17:46:34 -0800 Subject: [Tutor] JES question concerning syntax Message-ID: Hello, I've been having an issue with a program that I'm writing. The program works until it has to compute something: def carPmt(): cost = requestInteger("How much does the car cost?") downPmt = requestInteger("If there is a down payment, how much?") tradeIn = requestInteger("If there is a trade-in, what is its value?") years = requestInteger("How many years will you be paying?") air = requestInteger("What is the interest rate?") payment = calculatePayment(cost,downPmt,tradeIn,years,air) print "With a down payment of",downPmt," a trade-in value of",tradeIn, print ", an annual interest rate of",air,", your new",cost, "car will cost", print "you only",payment, "per month." def calculatePayment(cost,downPmt,tradeIn,years,air): carCostInitial = cost - downPmt carCostIntermediate = carCostInitial - tradeIn monIntRate = air/12 compoundingFactor = (1.0+monIntRate)**12.0/(1+monIntRate**12.0)-1.0 monthPmt = monIntRate*carCostIntermediate*compoundingFactor return monthPmt The first two sections work; the third one does not. When inputting random values, I get this: "With a down payment of 5000 ,a trade-in value of 7000 ,an annual interest rate of 2 ,your new 25000 car will cost you only 0.0 per month" Obviously I don't want my answer to be 0.0. I've had other people look at it (although they aren't well-versed in Python) and they couldn't help me isolate the problem. Thanks a million. Siobhan Wojcik -------------- next part -------------- An HTML attachment was scrubbed... URL: From TMaher1 at escambia.k12.fl.us Mon Feb 3 21:43:34 2014 From: TMaher1 at escambia.k12.fl.us (Thomas Maher) Date: Mon, 03 Feb 2014 14:43:34 -0600 Subject: [Tutor] I am teaching my students Python the second semester using www.LearnStreet.com ( http://www.learnstreet.com/ ). I am in need of some help. I am having a problem with the Lists-Set 1 exercise 18. The problem is below. I have put in several codes and the output is 5, which is the right answer. But it is asking for List's index logic. I have tried support with LearnStreet but they have yet to respond. Thank you for your time. Message-ID: <52EFAB16020000BD0000B3B3@mail.escambia.k12.fl.us> I am teaching my students Python the second semester using www.LearnStreet.com ( http://www.learnstreet.com/ ). I am in need of some help. I am having a problem with the Lists-Set 1 exercise 18. The problem is below. I have put in several codes and the output is 5, which is the right answer. But it is asking for List's index logic. I have tried support with LearnStreet but they have yet to respond. Thank you for your time. Tommy Maher 18 : Finding the length of nested lists. Create two lists list1 = [1,2,3,4,5] and list2 = [6,7,8,list1]. Write a code to find the length of list1 in list2 using for loop. Use the if statement to check elements in the list2. def len_of_innerlist(list2): # your code here list1 = [1,2,3,4,5] print len_of_innerlist([6,7,8,list1]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Feb 4 11:11:16 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Feb 2014 11:11:16 +0100 Subject: [Tutor] JES question concerning syntax References: Message-ID: Siobhan Wojcik wrote: > Hello, > > I've been having an issue with a program that I'm writing. The program > works until it has to compute something: > > def carPmt(): > cost = requestInteger("How much does the car cost?") > downPmt = requestInteger("If there is a down payment, how much?") > tradeIn = requestInteger("If there is a trade-in, what is its value?") > years = requestInteger("How many years will you be paying?") > air = requestInteger("What is the interest rate?") > > payment = calculatePayment(cost,downPmt,tradeIn,years,air) > print "With a down payment of",downPmt," a trade-in value of",tradeIn, > print ", an annual interest rate of",air,", your new",cost, "car will > cost", > print "you only",payment, "per month." > > def calculatePayment(cost,downPmt,tradeIn,years,air): > carCostInitial = cost - downPmt > carCostIntermediate = carCostInitial - tradeIn > monIntRate = air/12 > compoundingFactor = (1.0+monIntRate)**12.0/(1+monIntRate**12.0)-1.0 > monthPmt = monIntRate*carCostIntermediate*compoundingFactor > return monthPmt > > > > The first two sections work; the third one does not. When inputting random > values, I get this: "With a down payment of 5000 ,a trade-in value of 7000 > ,an annual interest rate of 2 ,your new 25000 car will cost you only 0.0 > per month" Obviously I don't want my answer to be 0.0. I've had other > people look at it (although they aren't well-versed in Python) and they > couldn't help me isolate the problem. > > Thanks a million. Hint: >>> 2/12 0 Potential fixes: >>> 2/12.0 0.16666666666666666 >>> float(2)/12 0.16666666666666666 Or if you want to change the default behaviour for the whole module: >>> from __future__ import division # at the beginning of the file >>> 2/12 0.16666666666666666 From alan.gauld at btinternet.com Tue Feb 4 11:31:28 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Feb 2014 10:31:28 +0000 Subject: [Tutor] input python 3.3 In-Reply-To: References: Message-ID: On 04/02/14 09:01, Ian D wrote: > I used to use 2.7 and the input was pretty when inputting a numeric > value, it would just get cast to an int. Just to be picky it would get converted to an int not cast as an int. casting and converting are two very different things. casting means treat a bit pattern in memory as if it is a particular type regardless of how that bit pattern got there. Converting to a type changes the bit pattern to give a value that is in some way related to the original's meaning. To give a simple example of the difference: var = '2' # the character two castVar = ord(2) # treat the character as an int convVar = int(var) # convert '2' to 2 casting is often done in C/C++ because it is common to return a pointer to a piece of data and the programmer has to tell the compiler how to treat that data. It looks like a conversion so casting is often mistaken for conversion. But they are not the same. (And C++ confused the issue further by introducing "dynamic casts" which often are conversions!) Sorry to be picky but failing to understand the difference has caused many a bug in C programs and I've suffered enough pain to be sensitive! :-) > Seems a backwards step unless (and am sure this is the case)it is > beneficial in so many other ways? Peter has explained why the v2 Python input() was a bad idea. Explicit conversion is much safer. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Feb 4 11:37:13 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Feb 2014 10:37:13 +0000 Subject: [Tutor] Rsync script hangs after a while In-Reply-To: <52F0AE96.5070103@gmail.com> References: <52F0AE96.5070103@gmail.com> Message-ID: On 04/02/14 09:10, Dayo wrote: > I wrote this script (http://bpaste.net/show/175284/) to help me > automate some rsync backups, and whenever I run the script for large > syncs, it just freezes after a while, and then I have to Ctrl+C it. You have quite a few prints in there so you should have some idea what it was doing when it freezes? If not add a few debug prints to show entry/exit of the functions, that should narrow it down a bit. The most likely places for a freeze are loops and calls to external programs so again wrap your loops and subprocess calls up with debug prints to see if you can identify which one causes the freeze. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Tue Feb 4 11:59:54 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Feb 2014 11:59:54 +0100 Subject: [Tutor] Rsync script hangs after a while References: <52F0AE96.5070103@gmail.com> Message-ID: Dayo wrote: > I wrote this script (http://bpaste.net/show/175284/) to help me > automate some rsync backups, and whenever I run the script for large > syncs, it just freezes after a while, and then I have to Ctrl+C it. I Maybe you are just lacking patience ;) > can find any clues in both source and target /var/log/* files. Any idea > how I can find out what's wrong with this thing? > def tuxsync(): > """ Rsync data to target backup dir.""" > # Get config file > config = ConfigParser.ConfigParser() > config.read(os.getenv('HOME') + '/.tuxsync.conf') > backupdirparent = config.get("backupsdir","backupsdir") > remoteusername = "root" > > # Get the client hostname and path to the source directory which are to be > # synced to the backup server > for client in [sec for sec in config.sections() if sec.startswith('clients.')]: > delim = '.' > # section header is in the format [clients.]. > # So split away the 'clients.' part, because we need just the hostname > clienthostname = client.split(delim)[1] > clientpath = config.get(client, "path") > print "clienthostname: %s\n" %(clienthostname) > print "path: %s\n" %(clientpath) You are throwing away all but the last clienthostname/clientpath. Is that intentional? > # First check for old backups and delete those > deleteoldbackups(backupdirparent) > > # Create new backup > subprocess.call(["/usr/bin/rsync", "-aEPhu", "--log-file=" + os.getenv('HOME') + "/tuxsync.log", remoteusername + '@' + clienthostname + ':' + clientpath, backupdirparent + '/' + clienthostname + strftime("%Y%m%d_%H%M%S") + '/']) > First, I'd make sure that python is involved. If it hangs on the rsync invocation you could replace subprocess.call(...) with print subprocess.list2cmd(...) and then run the resulting line from the shell, without python. If that freezes, too, you have to look elsewhere. From __peter__ at web.de Tue Feb 4 12:07:07 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Feb 2014 12:07:07 +0100 Subject: [Tutor] I am teaching my students Python the second semester using www.LearnStreet.com ( http://www.learnstreet.com/ ). I am in need of some help. I am having a problem with the Lists-Set 1 exercise 18. The problem is below. I have put in several codes and the output is 5, which is the right answer. But it is asking for List's index logic. I have tried support with LearnStreet but they have yet to respond. Thank you for your time. References: <52EFAB16020000BD0000B3B3@mail.escambia.k12.fl.us> Message-ID: Thomas Maher wrote: > I am teaching my students Python the second semester using > www.LearnStreet.com ( http://www.learnstreet.com/ ). I am in need of some > help. I am having a problem with the Lists-Set 1 exercise 18. The > problem is below. I have put in several codes and the output is 5, which > is the right answer. But it is asking for List's index logic. I have > tried support with LearnStreet but they have yet to respond. Thank you > for your time. > > > Tommy Maher > 18 : Finding the length of nested lists. > > Create two lists list1 = [1,2,3,4,5] and list2 = [6,7,8,list1]. Write a > code to find the length of list1 in list2 using for loop. > > Use the if statement to check elements in the list2. > > > def len_of_innerlist(list2): > # your code here > > list1 = [1,2,3,4,5] > print len_of_innerlist([6,7,8,list1]) Was the isinstance() function already explained in the course? From duxbuz at hotmail.com Tue Feb 4 12:58:42 2014 From: duxbuz at hotmail.com (Ian D) Date: Tue, 4 Feb 2014 11:58:42 +0000 Subject: [Tutor] conditionals or comparison or expressions terminology Message-ID: Hi Are: <= == != simple conditionals statements, conditionals, comparison operators, conditional expressions or what? I am looking at a few different pages and am unsure what I should be calling these expressions. http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html#simple-conditions http://www.tutorialspoint.com/python/python_basic_operators.htm http://docs.python.org/2/library/stdtypes.html#truth-value-testing Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Feb 4 13:05:05 2014 From: davea at davea.name (Dave Angel) Date: Tue, 4 Feb 2014 07:05:05 -0500 (EST) Subject: [Tutor] Any ideas References: Message-ID: josh Malone Wrote in message: > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > First thing is to figure your goal. "Model" might mean anything from "figure out how far they each go" to "plot the four trajectories in real time on a screen. " Or even "make four robots traverse the course till they crash into each other." Next, figure how you'd solve it by hand. Probably that includes figuring how far each will go and where they'll end up. Assuming the real assignment is to come up with four lists of coordinates, figure you'll need a loop. Python's loop constructs are for and while. If you have already figured the formula for how long they'll take, a for loop is most reasonable, with an increment of perhaps a tenth of a second. Now please post some code, tell us what doesn't work, and make sure it's a text message, not html. -- DaveA From __peter__ at web.de Tue Feb 4 13:22:27 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Feb 2014 13:22:27 +0100 Subject: [Tutor] conditionals or comparison or expressions terminology References: Message-ID: Ian D wrote: > Are: > > <= > == > != > > simple conditionals statements, conditionals, comparison operators, > conditional expressions or what? [comparison] operators: http://docs.python.org/3.3/reference/lexical_analysis.html#operators a <= b # expression (something is evaluated; ideally there are no side effects) c = a <= b # statement (something is done, ideally only the side effect matters) if a <= b: # conditional [expression] (some action is taken based on the result of the expression) ... while a <= b: # conditional [expression] ... Context is important: c(a <= b) # statement, assuming c does something permanent if c(a <= b): # expression, ideally only the result of c(...) matters. > I am looking at a few different pages and am unsure what I should be > calling these expressions. > > http://anh.cs.luc.edu/python/hands- on/3.1/handsonHtml/ifstatements.html#simple-conditions > > http://www.tutorialspoint.com/python/python_basic_operators.htm > > http://docs.python.org/2/library/stdtypes.html#truth-value-testing > > Thanks From davea at davea.name Tue Feb 4 13:44:04 2014 From: davea at davea.name (Dave Angel) Date: Tue, 4 Feb 2014 07:44:04 -0500 (EST) Subject: [Tutor] input python 3.3 References: Message-ID: Ian D Wrote in message: > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > When making an amendment to a post, please reply to that post; don't start a new thread, especially with a new subject. And please post in text, not html. Others have answered your question, but I wanted to point out that in 2.x, the program really has no idea what type of value will be returned to input (). Could easily be float, int, tuple, list, Nonetype, or thousands of other things, including many exceptions. With 3.x it's a string, and the programmer remains in control. -- DaveA From davea at davea.name Tue Feb 4 13:53:51 2014 From: davea at davea.name (Dave Angel) Date: Tue, 4 Feb 2014 07:53:51 -0500 (EST) Subject: [Tutor] My First Post References: Message-ID: Danny Yoo Wrote in message: > (Sorry if you get this message twice: I think I accidently mis-sent > the message to the wrong address, so to make sure, I'm sending to what > I think is the right address this time.) > > --- > > Hi Premanshu, [deleting useful advice] Welcome to the list. When responding to a post on a mailing list, you should do a reply-list or reply-all. And usually keep the subject line intact. Many people don't read every message, but only those threads that look interesting, so you want to be in the same thread. -- DaveA From gb.gabrielebrambilla at gmail.com Tue Feb 4 14:59:51 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Tue, 4 Feb 2014 08:59:51 -0500 Subject: [Tutor] strange errors In-Reply-To: References: Message-ID: ok. the problem is that my "errors" are not always the same and sometimes they are only differences in the results displayed (with the same starting data and no random variables used between). so it's difficult for me to understand where the error is (and to give you a piece of code that can run). for example today I got this two warnings and the results displayed were wrong C:\Users\Gabriele\Anaconda1\lib\site-packages\matplotlib\colors.py:918: RuntimeWarning: overflow encountered in true_divide resdat /= (vmax - vmin) C:\Users\Gabriele\Anaconda1\lib\site-packages\matplotlib\colors.py:568: RuntimeWarning: overflow encountered in multiply xa *= self.N and when I search the maximum and the minimum in a matrix it has returned me two nan values. Gabriele 2014-02-03 Jerry Hill : > On Mon, Feb 3, 2014 at 2:17 PM, Gabriele Brambilla > wrote: > > No, i'm not using lowlevel stuff...which part of the script do you want > to > > see? > > Since you asked, what we'd really like to see is a Short, Self > Contained, Compilable Example (see http://sscce.org/). That is, an > example that is short enough to be read quickly, self contained enough > so that we can actually save the code and run it, compilable in that > the code will run, at least to the point where you're having a problem > (it's fine to have code that won't run, as long as the error that pops > up is the error you're actually looking for help with). > > We know that it can be a lot of work to create an example like that, > but if you do there are two things that are likely to happen. First, > probably 75% of the time, you will find your problem yourself without > ever having to post it to the list. The very act of trimming your > code into the piece that demonstrates your problem, will help you find > the problem yourself. > > Second, you are very, very likely to get people to pay attention to > your question and provide advice on how to fix your code when you make > it easy for them to help. > > -- > Jerry > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Feb 4 15:44:20 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Feb 2014 15:44:20 +0100 Subject: [Tutor] strange errors References: Message-ID: Gabriele Brambilla wrote: > ok. > the problem is that my "errors" are not always the same and sometimes they > are only differences in the results displayed (with the same starting data > and no random variables used between). Sometimes randomness lurks where you don't expect it. Are there any dicts or sets involved? If so set the environment variable PYTHONHASHSEED=0 and see if the error starts occuring in the same place. > so it's difficult for me to understand where the error is (and to give you > a piece of code that can run). Please understand that it is impossible to debug code that we don't have. From alan.gauld at btinternet.com Tue Feb 4 15:50:34 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Feb 2014 14:50:34 +0000 Subject: [Tutor] unsigned int or char equivalent in Python? Message-ID: I'm playing with some bit twiddling code at present and started to get some unexpected results which i eventually realized were down to Python ints acting like signed ints in C (but with a 'flexible' sign bit!) This led me to wonder if there is a way to get unsigned type behaviour in Python? This could be very useful in bit twiddling scenarios, especially now that Python is being used on RasberryPi type devices to control Arduinos and the like. I had a quick hunt in the docs but couldn't think of a way to fake it. Any ideas? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Tue Feb 4 16:01:16 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Feb 2014 16:01:16 +0100 Subject: [Tutor] unsigned int or char equivalent in Python? References: Message-ID: Alan Gauld wrote: > I'm playing with some bit twiddling code at present and started > to get some unexpected results which i eventually realized > were down to Python ints acting like signed ints in C (but > with a 'flexible' sign bit!) > > This led me to wonder if there is a way to get unsigned type > behaviour in Python? > > This could be very useful in bit twiddling scenarios, especially > now that Python is being used on RasberryPi type devices to > control Arduinos and the like. I had a quick hunt in the docs > but couldn't think of a way to fake it. I think you have to apply a mask: >>> -2 & 0xff 254 From alan.gauld at btinternet.com Tue Feb 4 17:26:18 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Feb 2014 16:26:18 +0000 Subject: [Tutor] unsigned int or char equivalent in Python? In-Reply-To: References: Message-ID: <52F114AA.9040701@btinternet.com> On 04/02/14 15:01, Peter Otten wrote: > Alan Gauld wrote: >> This led me to wonder if there is a way to get unsigned type >> behaviour in Python? >> > I think you have to apply a mask: > >>>> -2 & 0xff > 254 Ah! obvious when you see it! :-) And I'm applying masks all over the place but didn't think of using it here. Thanks, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From someukdeveloper at gmail.com Tue Feb 4 18:38:18 2014 From: someukdeveloper at gmail.com (Some Developer) Date: Tue, 04 Feb 2014 17:38:18 +0000 Subject: [Tutor] Splitting email headers when using imaplib Message-ID: <52F1258A.8050903@googlemail.com> I'm currently trying to download emails from an IMAP server using Python. I can download the emails just fine but I'm having an issue when it comes to splitting the relevant headers. Basically I'm using the following to fetch the headers of an email message: typ, msg_header_content = self.m.fetch(msg_id, '(BODY.PEEK[HEADER])') then I can get a string containing the headers by accessing msg_header_content[0][1]. This works fine but I need to split the Subject header, the From header and the To header out into separate strings so I can save the information in a database. I thought the following regular expressions would do the trick when using re.MULTILINE when matching them to the header string but apparently that appears to be wrong. msg_subject_regex = re.compile(r'^Subject:\.+\r\n') msg_from_regex = re.compile(r'^From:\.+\r\n') msg_to_regex = re.compile(r'^To:\.+\r\n') Can anyone point me in the right direction for this please? I'm at a loss here. From dyoo at hashcollision.org Tue Feb 4 19:59:02 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 4 Feb 2014 10:59:02 -0800 Subject: [Tutor] I am teaching my students Python the second semester using www.LearnStreet.com ( http://www.learnstreet.com/ ). I am in need of some help. I am having a problem with the Lists-Set 1 exercise 18. The problem is below. I have put in several codes and the output is 5, which is the right answer. But it is asking for List's index logic. I have tried support with LearnStreet but they have yet to respond. Thank you for your time. In-Reply-To: <52EFAB16020000BD0000B3B3@mail.escambia.k12.fl.us> References: <52EFAB16020000BD0000B3B3@mail.escambia.k12.fl.us> Message-ID: The question as stated is fairly artificial and a bit nonsensical. Let me explain that statement, because it's a strong one. If we know the exact shape for list1 and list2 are, we can answer this question directly, without loops. len(list1[-1]) "Take the last element of the list1, and grab its length." Note: no loops, no if statements. It's the direct solution to this problem as stated. You need lists and loops when you're working with data of some dynamic size that can vary. But this problem doesn't demonstrate that need at all, so as far as I can tell. And there's no need for 'if' statements here either with the original problem statement. Again, the problem as stated is so static, so anemic, that there's no need for any branching, conditional logic. Hence the problem does not seems like a good question to ask. It's likely nonsensical to a professional programmer, and likely nonsensical to your students as well. If yo can, try to find a better source of good questions. Your students will be happier. From dyoo at hashcollision.org Tue Feb 4 21:51:34 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 4 Feb 2014 12:51:34 -0800 Subject: [Tutor] I am teaching my students Python the second semester using www.LearnStreet.com ( http://www.learnstreet.com/ ). I am in need of some help. I am having a problem with the Lists-Set 1 exercise 18. The problem is below. I have put in several codes and the output is 5, which is the right answer. But it is asking for List's index logic. I have tried support with LearnStreet but they have yet to respond. Thank you for your time. In-Reply-To: <52F0EBCF020000BD0000B3FF@mail.escambia.k12.fl.us> References: <52EFAB16020000BD0000B3B3@mail.escambia.k12.fl.us> <52F0EBCF020000BD0000B3FF@mail.escambia.k12.fl.us> Message-ID: On Tue, Feb 4, 2014 at 11:31 AM, Thomas Maher wrote: > Thank you for helping me. I used a similar code, but with an if statement. > if list1 in list2: > return len(list2[-1]) > > This is the code they sent me this morning. > > def len_of_innerlist(list2): > for ele in list2: > if isinstance(ele, list): > return len(ele) > > list1 = [1,2,3,4,5] > print len_of_innerlist([6,7,8,list1]) > > Tommy Maher +cc:tutor at python.org ... Wow. Holy wow. Ok. I don't know the LearnStreet folks, but if that's the quality of the problem set, that's a big warning sign for me. If that's their response, then I do stand by what I said earlier. Any "beginning tutorial" material that is using isinstance() there, as a motivating reason to use basic loops and conditions, is not to be trusted. That sounds like the school of "take grab-bag random features of the language and dole them out in lessons." I'd recommend a curriculum that respects their audience. Alan Gauld has written a good tutorial, which you can find here: http://www.alan-g.me.uk/ Also consider "How to Think like a Computer Scientist". http://www.greenteapress.com/thinkpython/ From denis.spir at gmail.com Wed Feb 5 08:39:27 2014 From: denis.spir at gmail.com (spir) Date: Wed, 05 Feb 2014 08:39:27 +0100 Subject: [Tutor] Splitting email headers when using imaplib In-Reply-To: <52F1258A.8050903@googlemail.com> References: <52F1258A.8050903@googlemail.com> Message-ID: <52F1EAAF.2000003@gmail.com> On 02/04/2014 06:38 PM, Some Developer wrote: > I'm currently trying to download emails from an IMAP server using Python. I can > download the emails just fine but I'm having an issue when it comes to splitting > the relevant headers. Basically I'm using the following to fetch the headers of > an email message: > > typ, msg_header_content = self.m.fetch(msg_id, '(BODY.PEEK[HEADER])') > > then I can get a string containing the headers by accessing > msg_header_content[0][1]. This works fine but I need to split the Subject > header, the From header and the To header out into separate strings so I can > save the information in a database. > > I thought the following regular expressions would do the trick when using > re.MULTILINE when matching them to the header string but apparently that appears > to be wrong. > > msg_subject_regex = re.compile(r'^Subject:\.+\r\n') > msg_from_regex = re.compile(r'^From:\.+\r\n') > msg_to_regex = re.compile(r'^To:\.+\r\n') > > Can anyone point me in the right direction for this please? I'm at a loss here. I have no idea of the pattern or structure of email headers. Would you post some example of 'msg_header_content[0][1]'? In the meantine, try to suppress \r from the regex formats. (Shouldn't be here, because when reading strings from files, python converts newlines into \n; also try "'\r' in s" or "'\r\n' in s" to be sure.) d From __peter__ at web.de Wed Feb 5 10:12:47 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Feb 2014 10:12:47 +0100 Subject: [Tutor] Splitting email headers when using imaplib References: <52F1258A.8050903@googlemail.com> Message-ID: Some Developer wrote: > I'm currently trying to download emails from an IMAP server using > Python. I can download the emails just fine but I'm having an issue when > it comes to splitting the relevant headers. Basically I'm using the > following to fetch the headers of an email message: > > typ, msg_header_content = self.m.fetch(msg_id, '(BODY.PEEK[HEADER])') > > then I can get a string containing the headers by accessing > msg_header_content[0][1]. This works fine but I need to split the > Subject header, the From header and the To header out into separate > strings so I can save the information in a database. > > I thought the following regular expressions would do the trick when > using re.MULTILINE when matching them to the header string but > apparently that appears to be wrong. > > msg_subject_regex = re.compile(r'^Subject:\.+\r\n') > msg_from_regex = re.compile(r'^From:\.+\r\n') > msg_to_regex = re.compile(r'^To:\.+\r\n') > > Can anyone point me in the right direction for this please? I'm at a > loss here. Maybe you can use the email package? >>> import email >>> msg = email.message_from_file(open("tmp.txt")) >>> msg["From"] 'Some Developer ' >>> msg["Subject"] 'Splitting email headers when using imaplib' >>> msg.keys() ['Path', 'From', 'Newsgroups', 'Subject', 'Date', 'Lines', 'Approved', 'Message-ID', 'NNTP-Posting-Host', 'Mime-Version', 'Content-Type', 'Content- Transfer-Encoding', 'X-Trace', 'X-Complaints-To', 'NNTP-Posting-Date', 'To', 'Original-X-From', 'Return-path', 'Envelope-to', 'Original-Received', 'Original-Received', 'X-Original-To', 'Delivered-To', 'Original-Received', 'X-Spam-Status', 'X-Spam-Evidence', 'Original-Received', 'Original- Received', 'Original-Received', 'DKIM-Signature', 'X-Received', 'Original- Received', 'User-Agent', 'X-Antivirus', 'X-Antivirus-Status', 'X-BeenThere', 'X-Mailman-Version', 'Precedence', 'List-Id', 'List-Unsubscribe', 'List- Archive', 'List-Post', 'List-Help', 'List-Subscribe', 'Errors-To', 'Original-Sender', 'Xref', 'Archived-At'] There is also a message_from_string() function. From __peter__ at web.de Wed Feb 5 10:32:08 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Feb 2014 10:32:08 +0100 Subject: [Tutor] conditionals or comparison or expressions terminology References: Message-ID: Ian D wrote: Ian, please answer to the list, not me in private. Thank you. > Most of this makes sense except for the c(a<=b) > also > if c(a<=b) > > It is the c(...) syntax that I don't understand. > > I dont recall seeing a statement like this. c is just an arbitrary function, I put in the three dots as a placeholder for the actual arguments. A concrete example would be # python2: use raw_input(), not input() a = float(input("enter a float ")) b = float(input("enter another float ")) if abs(a - b) > 1.0: print("Your numbers are more than 1.0 apart.") Here abs(a-b) > 1.0 is the conditional expression. It is in turn built of the comparison x > 1.0 where x is the function call abs(z) where z is the arithmetic expression a - b PS: Fun fact: three dots may occur in actual Python code: >>> def f(x): return x ... >>> f(...) # python 3 only Ellipsis The only place I know where this is commonly used is the numpy library: >>> import numpy >>> a = numpy.array(range(1, 5)).reshape((2,2)) >>> a array([[1, 2], [3, 4]]) >>> a[0] array([1, 2]) >>> a[...,1] # python 2 and 3 array([2, 4]) From 303cookiemonster at gmail.com Tue Feb 4 23:05:21 2014 From: 303cookiemonster at gmail.com (Colin Struthers) Date: Tue, 4 Feb 2014 14:05:21 -0800 Subject: [Tutor] Changing only intergers in a list of strings Message-ID: I am in a beginning python course and am working through some code and I can't even figure out how to start building this particular section of code. My goal is to get a sentence for the user and to take each number in the user string and add 1 to each number. i.e "the 4 people had 6 dogs" would change to "the 5 people had 7 dogs" *a_string = [ ]int_list = [ ]a_string = raw_input("Enter a sentence with both words and numbers: ")def FindNumbers(): print "You entered: ", a_string for ints in a_string ...?FindNumbers()* I fully understand that this doesn't even begin to work but I don't really know where to start deconstructing the list, editing only the intergers, and joining it all back together. Thanks for the help. -- Colin -------------- next part -------------- An HTML attachment was scrubbed... URL: From dpalao.python at gmail.com Wed Feb 5 11:46:10 2014 From: dpalao.python at gmail.com (David Palao) Date: Wed, 5 Feb 2014 11:46:10 +0100 Subject: [Tutor] Changing only intergers in a list of strings In-Reply-To: References: Message-ID: Hi, Is it not clear to me if you must distinguish ints from other type of numbers, or if, for instances floats and ints must be dealt differently. Anyway, I would propose something like the following function: def FindNumbers(a_string): print "You entered:", a_string out_list = [] for item in a_string.split(): try: num = int(item) except ValueError: out_list.append(item) else: out_list.append("%s" % (num+a,)) out_string = ' '.join(out_list) # do whatever you want to do with the resulting out_string: return it, or display it... Some comments: 1) I would pass the input string as argument rather than using it as a global. 2) You could use float instead of int to make it more general 3) If you need to distinguish between ints and floats, then you must add a couple of extra lines I hope it helps. Best 2014-02-04 Colin Struthers <303cookiemonster at gmail.com>: > I am in a beginning python course and am working through some code and I > can't even figure out how to start building this particular section of code. > > My goal is to get a sentence for the user and to take each number in the > user string and add 1 to each number. i.e "the 4 people had 6 dogs" would > change to "the 5 people had 7 dogs" > > a_string = [ ] > int_list = [ ] > a_string = raw_input("Enter a sentence with both words and numbers: ") > > def FindNumbers(): > print "You entered: ", a_string > for ints in a_string > ...? > > FindNumbers() > > I fully understand that this doesn't even begin to work but I don't really > know where to start deconstructing the list, editing only the intergers, and > joining it all back together. > > Thanks for the help. > > -- > Colin > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From dpalao.python at gmail.com Wed Feb 5 11:47:32 2014 From: dpalao.python at gmail.com (David Palao) Date: Wed, 5 Feb 2014 11:47:32 +0100 Subject: [Tutor] Changing only intergers in a list of strings In-Reply-To: References: Message-ID: Sorry, there is a typo: "(num+a,)" should be "(num+1,)", obviously. 2014-02-05 David Palao : > Hi, > Is it not clear to me if you must distinguish ints from other type of > numbers, or if, for instances floats and ints must be dealt > differently. > Anyway, I would propose something like the following function: > > def FindNumbers(a_string): > print "You entered:", a_string > out_list = [] > for item in a_string.split(): > try: > num = int(item) > except ValueError: > out_list.append(item) > else: > out_list.append("%s" % (num+a,)) > out_string = ' '.join(out_list) > # do whatever you want to do with the resulting out_string: > return it, or display it... > > Some comments: > 1) I would pass the input string as argument rather than using it as a global. > 2) You could use float instead of int to make it more general > 3) If you need to distinguish between ints and floats, then you must > add a couple of extra lines > > I hope it helps. > > Best > > > 2014-02-04 Colin Struthers <303cookiemonster at gmail.com>: >> I am in a beginning python course and am working through some code and I >> can't even figure out how to start building this particular section of code. >> >> My goal is to get a sentence for the user and to take each number in the >> user string and add 1 to each number. i.e "the 4 people had 6 dogs" would >> change to "the 5 people had 7 dogs" >> >> a_string = [ ] >> int_list = [ ] >> a_string = raw_input("Enter a sentence with both words and numbers: ") >> >> def FindNumbers(): >> print "You entered: ", a_string >> for ints in a_string >> ...? >> >> FindNumbers() >> >> I fully understand that this doesn't even begin to work but I don't really >> know where to start deconstructing the list, editing only the intergers, and >> joining it all back together. >> >> Thanks for the help. >> >> -- >> Colin >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> From duxbuz at hotmail.com Wed Feb 5 12:09:35 2014 From: duxbuz at hotmail.com (Ian D) Date: Wed, 5 Feb 2014 11:09:35 +0000 Subject: [Tutor] sys.path.append import python3 not working Message-ID: Hi Seem when I run a module I created with import sys sys.path.append("d:\modules") import myMod it works great.... in 2.7 but in 3.3 it doesn't I get an error in 3.3: import myMod ImportError: No module named 'myMod' I have tried it with append("d:\\modules") append("d:/\modules") Anyone help please? Thanks p.s. Apologies for poor etiquette so far as have been double posting and replying direct to replies. Will try and stop making these mistakes. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Wed Feb 5 12:32:46 2014 From: davea at davea.name (Dave Angel) Date: Wed, 5 Feb 2014 06:32:46 -0500 (EST) Subject: [Tutor] sys.path.append import python3 not working References: Message-ID: Ian D Wrote in message: > > import sys > sys.path.append("d:\modules") ?? > I have tried it with append("d:\\modules") append("d:/\modules") ?? The first form is not reasonable, you'd need to double the backslash. But your second try should have worked. Here's what I would use: "d:/modules" or perhaps r"d:\modules" "d:\\modules" I would suggest printing sys.path from your code, just in case. I would then check the actual directory name and module name, especially for case. Windows may not usually care about case, but sometimes it does matter. Finally I'd run the python with the -v switch, and see what it tells you. -- DaveA From oscar.j.benjamin at gmail.com Wed Feb 5 12:24:27 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 5 Feb 2014 11:24:27 +0000 Subject: [Tutor] Any ideas In-Reply-To: References: Message-ID: <20140205112424.GA2518@gmail.com> On Mon, Feb 03, 2014 at 04:35:58PM -0800, josh Malone wrote: > Hi, I'm very new to programming and python is my first language. I'm > currently enrolled in a class at Oregon State University where we are > taught to program in python. I'm stuck on one problem and i know what i > want to do... i just have no idea how to write the program. The question is > as follows > > Consider four missiles initially located at the four corners of a square > with a side of 100m. Model their behavior if each missile moves with a > speed of 5m/s in the direction pointing directly at the missile > counter-clockwise from itself. > > I think i can do most of this, i'm just confused on how to make the spheres > continually change their direction. I'm assuming it has something to do > with a while loop or possibly an if statement. Any help you could give me > would be great! thanks! You need to give more description about what you're actually doing (or expected to do) in your code here. I thought I was with you until you mentioned the spheres. Are you supposed to make an animation? Is it about numerical integration? I would probably use numerical integration for this. The simplest way is to use the Euler method: http://en.wikipedia.org/wiki/Euler_method It's common to use the Euler method as a demonstration of how to do dynamic simulations (a more advanced tutorial might rightly scorn the method as being inferior to proper integration techniques). Does this seem like what you need to do? If you're using scipy then it has a function called odeint that is a good numerical integrator (better than the Euler method). Oscar From duxbuz at hotmail.com Wed Feb 5 12:28:50 2014 From: duxbuz at hotmail.com (Ian D) Date: Wed, 5 Feb 2014 11:28:50 +0000 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: References: Message-ID: Ok I seem to be having some success with it at the moment after moving the location of the module. From: duxbuz at hotmail.com To: tutor at python.org Date: Wed, 5 Feb 2014 11:09:35 +0000 Subject: [Tutor] sys.path.append import python3 not working Hi Seem when I run a module I created with import sys sys.path.append("d:\modules") import myMod it works great.... in 2.7 but in 3.3 it doesn't I get an error in 3.3: import myMod ImportError: No module named 'myMod' I have tried it with append("d:\\modules") append("d:/\modules") Anyone help please? Thanks p.s. Apologies for poor etiquette so far as have been double posting and replying direct to replies. Will try and stop making these mistakes. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From duxbuz at hotmail.com Wed Feb 5 12:46:09 2014 From: duxbuz at hotmail.com (Ian D) Date: Wed, 5 Feb 2014 11:46:09 +0000 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: References: , Message-ID: Ok even more strangely it is working in the original location. Am now not 100% sure that I have the folder structure correct. I will keep a eye on it. Thanks To: tutor at python.org From: davea at davea.name Date: Wed, 5 Feb 2014 06:32:46 -0500 Subject: Re: [Tutor] sys.path.append import python3 not working Ian D Wrote in message: > > import sys > sys.path.append("d:\modules") > I have tried it with append("d:\\modules") append("d:/\modules") The first form is not reasonable, you'd need to double the backslash. But your second try should have worked. Here's what I would use: "d:/modules" or perhaps r"d:\modules" "d:\\modules" I would suggest printing sys.path from your code, just in case. I would then check the actual directory name and module name, especially for case. Windows may not usually care about case, but sometimes it does matter. Finally I'd run the python with the -v switch, and see what it tells you. -- DaveA _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Feb 5 12:51:18 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 05 Feb 2014 11:51:18 +0000 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: References: , Message-ID: <52F225B6.603@timgolden.me.uk> On 05/02/2014 11:46, Ian D wrote: > Ok even more strangely it is working in the original location. > > Am now not 100% sure that I have the folder structure correct. > > I will keep a eye on it. You might want to consider whether your approach is the best. One usually appends to sys.path when there's something dynamic about the location of modules (eg for a plugin mechanism). If your library modules are always in, say, d:/modules then just set up a PYTHONPATH env var with that in it; or use a .pth file in your python directory. I do the latter, altho' it's frowned upon by some for reasons I've never entirely understood. TJG From duxbuz at hotmail.com Wed Feb 5 12:53:01 2014 From: duxbuz at hotmail.com (Ian D) Date: Wed, 5 Feb 2014 11:53:01 +0000 Subject: [Tutor] my modules idle doesn't list functions python3.3 Message-ID: Hi In Python 2.7 If I create my own modules and call them with import sys sys.path.append("d:\modules") import myMod and use tab to autocomplete I get a list functions. myMod. <---- if I tab this I get a list of my functions (This only works if I have ran program at least once, then it seems to have loaded the module and can display its functions) But if I use Python 3.3 It does not display the functions using autocomplete Anyone know if this is fixable? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From duxbuz at hotmail.com Wed Feb 5 12:55:37 2014 From: duxbuz at hotmail.com (Ian D) Date: Wed, 5 Feb 2014 11:55:37 +0000 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: <52F225B6.603@timgolden.me.uk> References: , , , , <52F225B6.603@timgolden.me.uk> Message-ID: The network dictates that it is the only way I can really do it as I cannot edit any files directly. I have to append the path on the fly > Date: Wed, 5 Feb 2014 11:51:18 +0000 > From: mail at timgolden.me.uk > To: tutor at python.org > Subject: Re: [Tutor] sys.path.append import python3 not working > > On 05/02/2014 11:46, Ian D wrote: > > Ok even more strangely it is working in the original location. > > > > Am now not 100% sure that I have the folder structure correct. > > > > I will keep a eye on it. > > You might want to consider whether your approach is the best. One > usually appends to sys.path when there's something dynamic about the > location of modules (eg for a plugin mechanism). If your library modules > are always in, say, d:/modules then just set up a PYTHONPATH env var > with that in it; or use a .pth file in your python directory. I do the > latter, altho' it's frowned upon by some for reasons I've never entirely > understood. > > TJG > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Wed Feb 5 12:58:46 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 5 Feb 2014 11:58:46 +0000 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: <52F225B6.603@timgolden.me.uk> References: <52F225B6.603@timgolden.me.uk> Message-ID: On 5 February 2014 11:51, Tim Golden wrote: > On 05/02/2014 11:46, Ian D wrote: >> Ok even more strangely it is working in the original location. >> >> Am now not 100% sure that I have the folder structure correct. >> >> I will keep a eye on it. > > You might want to consider whether your approach is the best. One > usually appends to sys.path when there's something dynamic about the > location of modules (eg for a plugin mechanism). If your library modules > are always in, say, d:/modules then just set up a PYTHONPATH env var > with that in it; or use a .pth file in your python directory. I do the > latter, altho' it's frowned upon by some for reasons I've never entirely > understood. Another option is to place it in site-packages. If you don't want to use the system site packages you can always use the one in your user directory. In my case on Ubuntu that's in ~/.local/lib/pythonX.Y/site-packages/ $ cat ~/.local/lib/python2.7/site-packages/mymod.py print("This is my mod installed in my user site-packages") $ python2.7 Python 2.7.3 (default, Sep 26 2013, 20:03:06) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import mymod This is my mod installed in my user site-packages Oscar From mail at timgolden.me.uk Wed Feb 5 13:02:19 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 05 Feb 2014 12:02:19 +0000 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: References: <52F225B6.603@timgolden.me.uk> Message-ID: <52F2284B.5090407@timgolden.me.uk> On 05/02/2014 11:58, Oscar Benjamin wrote: > Another option is to place it in site-packages. If you don't want to > use the system site packages you can always use the one in your user > directory. In my case on Ubuntu that's in > ~/.local/lib/pythonX.Y/site-packages/ Good point: I always forget the user-specific site-package. Since the OP is on Windows... on my (Windows 7) box it's: %APPDATA%\Python\Python33\site-packages TJG From mail at timgolden.me.uk Wed Feb 5 13:05:54 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 05 Feb 2014 12:05:54 +0000 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: References: , , , , <52F225B6.603@timgolden.me.uk> Message-ID: <52F22922.9090303@timgolden.me.uk> On 05/02/2014 11:55, Ian D wrote: > The network dictates that it is the only way I can really do it as I > cannot edit any files directly. I have to append the path on the fly Ok; just wanted to make sure you weren't making life more difficult for yourself than needs be. TJG From mail at timgolden.me.uk Wed Feb 5 13:08:28 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 05 Feb 2014 12:08:28 +0000 Subject: [Tutor] my modules idle doesn't list functions python3.3 In-Reply-To: References: Message-ID: <52F229BC.2050807@timgolden.me.uk> On 05/02/2014 11:53, Ian D wrote: > Hi > > In Python 2.7 > > If I create my own modules and call them with > > import sys > sys.path.append("d:\modules") > > import myMod > > and use tab to autocomplete I get a list functions. > myMod. <---- if I tab this I get a list of my functions > > (This only works if I have ran program at least once, then it seems to > have loaded the module and can display its functions) > > But if I use Python 3.3 > It does not display the functions using autocomplete > > Anyone know if this is fixable? The default Python interpeter on Windows doesn't come with built-in autocomplete functionality. You're may be using an IDE or extended interpreter (including the batteries-included IDLE). Or on 2.7 you've installed the pyreadline module which I think the IPython project now maintains. You'd need to install that again for 3.x. TJG From davea at davea.name Wed Feb 5 13:36:40 2014 From: davea at davea.name (Dave Angel) Date: Wed, 5 Feb 2014 07:36:40 -0500 (EST) Subject: [Tutor] Splitting email headers when using imaplib References: <52F1258A.8050903@googlemail.com> <52F1EAAF.2000003@gmail.com> Message-ID: spir Wrote in message: > > I have no idea of the pattern or structure of email headers. Would you post some > example of 'msg_header_content[0][1]'? > > In the meantine, try to suppress \r from the regex formats. (Shouldn't be here, > because when reading strings from files, python converts newlines into \n Only for text files. These headers use 0d0a as part of the specified format, so it'd probably be best not to ignore them. -- DaveA From alan.gauld at btinternet.com Wed Feb 5 13:41:03 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Feb 2014 12:41:03 +0000 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: <52F2284B.5090407@timgolden.me.uk> References: <52F225B6.603@timgolden.me.uk> <52F2284B.5090407@timgolden.me.uk> Message-ID: On 05/02/14 12:02, Tim Golden wrote: > On 05/02/2014 11:58, Oscar Benjamin wrote: >> Another option is to place it in site-packages. If you don't want to >> use the system site packages you can always use the one in your user >> directory. In my case on Ubuntu that's in >> ~/.local/lib/pythonX.Y/site-packages/ > > Good point: I always forget the user-specific site-package. Since the OP > is on Windows... on my (Windows 7) box it's: And after 15 years of using Python I didn't know it existed until now! I've always used a local directory and added it to PYTHONPATH... Always something new... :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Wed Feb 5 13:53:51 2014 From: davea at davea.name (Dave Angel) Date: Wed, 5 Feb 2014 07:53:51 -0500 (EST) Subject: [Tutor] sys.path.append import python3 not working References: Message-ID: Ian D Wrote in message: > __ Ok I seem to??be having some success with??it at the moment after moving the location of the module. That might be because the letter following the backslash is not currently a valid escape code. You really shouldn't leave half broken code; it tends to break again at the most embarrassing times. -- DaveA From eryksun at gmail.com Wed Feb 5 14:35:23 2014 From: eryksun at gmail.com (eryksun) Date: Wed, 5 Feb 2014 08:35:23 -0500 Subject: [Tutor] my modules idle doesn't list functions python3.3 In-Reply-To: References: Message-ID: On Wed, Feb 5, 2014 at 6:53 AM, Ian D wrote: > > But if I use Python 3.3 > It does not display the functions using autocomplete Maybe IDLE's AutoComplete extension is disabled. The configuration is in Lib\idlelib\config-extensions.def, with the following defaults: [AutoComplete] enable=1 popupwait=2000 [AutoComplete_cfgBindings] force-open-completions= [AutoComplete_bindings] autocomplete= try-open-completions= From eryksun at gmail.com Wed Feb 5 15:07:35 2014 From: eryksun at gmail.com (eryksun) Date: Wed, 5 Feb 2014 09:07:35 -0500 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: References: <52F225B6.603@timgolden.me.uk> Message-ID: On Wed, Feb 5, 2014 at 6:55 AM, Ian D wrote: > The network dictates that it is the only way I can really do it as I cannot > edit any files directly. I have to append the path on the fly If you can modify your profile, then I'd expect you can permanently set PYTHONPATH for the current user. setx.exe will modify the key at HKCU\environment, e.g.: setx PYTHONPATH D:\modules Verify that it was set: reg query HKCU\Environment /v PYTHONPATH %PYTHONPATH% should exist the next time you logon. No guarantees, but it's at least worth trying. As to mixed-case module names, that's a pain to be avoided. The Windows file API is case insensitive, but NTFS is case preserving. Python uses this to do its own case-sensitive import. From oscar.j.benjamin at gmail.com Wed Feb 5 15:31:14 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 5 Feb 2014 14:31:14 +0000 Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: References: <52F225B6.603@timgolden.me.uk> <52F2284B.5090407@timgolden.me.uk> Message-ID: On 5 February 2014 12:41, Alan Gauld wrote: > > And after 15 years of using Python I didn't know it existed until now! > I've always used a local directory and added it to PYTHONPATH... Then maybe you're also not aware of the --user option for pip/easy_install. That's how I discovered the user site-packages directory. I've always thought it would be good if distro package managers would have a --user option, but failing that pip serves me quite well for a lot of things. Oscar From someukdeveloper at gmail.com Wed Feb 5 16:52:33 2014 From: someukdeveloper at gmail.com (Some Developer) Date: Wed, 05 Feb 2014 15:52:33 +0000 Subject: [Tutor] Splitting email headers when using imaplib In-Reply-To: References: <52F1258A.8050903@googlemail.com> Message-ID: <52F25E41.40905@googlemail.com> On 05/02/2014 09:12, Peter Otten wrote: > Some Developer wrote: > >> I'm currently trying to download emails from an IMAP server using >> Python. I can download the emails just fine but I'm having an issue when >> it comes to splitting the relevant headers. Basically I'm using the >> following to fetch the headers of an email message: >> >> typ, msg_header_content = self.m.fetch(msg_id, '(BODY.PEEK[HEADER])') >> >> then I can get a string containing the headers by accessing >> msg_header_content[0][1]. This works fine but I need to split the >> Subject header, the From header and the To header out into separate >> strings so I can save the information in a database. >> >> I thought the following regular expressions would do the trick when >> using re.MULTILINE when matching them to the header string but >> apparently that appears to be wrong. >> >> msg_subject_regex = re.compile(r'^Subject:\.+\r\n') >> msg_from_regex = re.compile(r'^From:\.+\r\n') >> msg_to_regex = re.compile(r'^To:\.+\r\n') >> >> Can anyone point me in the right direction for this please? I'm at a >> loss here. > Maybe you can use the email package? > >>>> import email >>>> msg = email.message_from_file(open("tmp.txt")) >>>> msg["From"] > 'Some Developer ' >>>> msg["Subject"] > 'Splitting email headers when using imaplib' >>>> msg.keys() > ['Path', 'From', 'Newsgroups', 'Subject', 'Date', 'Lines', 'Approved', > 'Message-ID', 'NNTP-Posting-Host', 'Mime-Version', 'Content-Type', 'Content- > Transfer-Encoding', 'X-Trace', 'X-Complaints-To', 'NNTP-Posting-Date', 'To', > 'Original-X-From', 'Return-path', 'Envelope-to', 'Original-Received', > 'Original-Received', 'X-Original-To', 'Delivered-To', 'Original-Received', > 'X-Spam-Status', 'X-Spam-Evidence', 'Original-Received', 'Original- > Received', 'Original-Received', 'DKIM-Signature', 'X-Received', 'Original- > Received', 'User-Agent', 'X-Antivirus', 'X-Antivirus-Status', 'X-BeenThere', > 'X-Mailman-Version', 'Precedence', 'List-Id', 'List-Unsubscribe', 'List- > Archive', 'List-Post', 'List-Help', 'List-Subscribe', 'Errors-To', > 'Original-Sender', 'Xref', 'Archived-At'] > > There is also a message_from_string() function. > Awesome. That's exactly what I was looking for. Thanks. From alan.gauld at btinternet.com Wed Feb 5 17:42:07 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 5 Feb 2014 16:42:07 +0000 (GMT) Subject: [Tutor] sys.path.append import python3 not working In-Reply-To: References: <52F225B6.603@timgolden.me.uk> <52F2284B.5090407@timgolden.me.uk> Message-ID: <1391618527.6459.YahooMailNeo@web186001.mail.ir2.yahoo.com> >> And after 15 years of using Python I didn't know it existed until now! >> I've always used a local directory and added it to PYTHONPATH... > >Then maybe you're also not aware of the --user option for >pip/easy_install. That's how I discovered the user site-packages >directory.To be honest I've not really used pip or easy_install much. Most of what I do uses the standard library. The only extra packages? I use are BeautifulSoup(very rarely) and wxPython(also rarely) and TurboGears and Django once each. In fact, one of the things I'm playing with just now is the whole? distutils packaging thing and reading up on eggs etc. Frankly it's? all a bit of a mess and I hope the promised improvements from? Python 3.4 onwards will make it a lot less messy! Regards, Alan g. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alanho_80 at yahoo.com.sg Wed Feb 5 16:30:35 2014 From: alanho_80 at yahoo.com.sg (Alan Ho) Date: Wed, 5 Feb 2014 23:30:35 +0800 (SGT) Subject: [Tutor] Advice on Python codes - A recursive function to output entire directory subkeys of Windows Registry Message-ID: <1391614235.50058.YahooMailNeo@web192801.mail.sg3.yahoo.com> Hi, I am a novice in Python, having attended a course few weeks ago and I'm working on my assignment now, and I encounter this issue when I was trying to print the entire Windows Registry (WR) sub-keys directories (trying that first with the below codes with adaptations from on-line research) and its value (later on). Kindly advise if any, as it has been taking me few days. What I need is a display on the std screen the entire directory of sub-keys (inserted into a list) in a WR key say, HKEY_CURRENT_FIG, and then I will write the contents into a text or CSV file. Thanks advance! Here are my codes, ----------------- import winreg def traverse(root, key, list): ? ? hKey = winreg.OpenKey(root, key) ? ? try: ? ? ? ? i = 0 ? ? ? ? while True: ? ? ? ? ? ? strFullSubKey = "" ? ? ? ? ? ? try: ? ? ? ? ? ? ? ? strSubKey = winreg.EnumKey(hKey, i) ? ? ? ? ? ? ? ? if (key != ""): ? ? ? ? ? ? ? ? ? ? strFullSubKey = key + "\\" + strSubKey ? ? ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? ? ? strFullSubKey = strSubKey ? ? ? ? ? ? except WindowsError: ? ? ? ? ? ? ? ? hKey.Close() ? ? ? ? ? ? ? ? return ? ? ? ? ? ? traverse(root, strFullSubKey, list) ? ? ? ? ? ? list.append(strFullSubKey) ? ? ? ? ? ? i += 1 ? ? except ?WindowsError: ? ? ? ? hKey.Close() global list list = list() traverse (winreg.HKEY_CURRENT_CONFIG,"",list) print (list) ----------------- results on screen, which is not very correct, seeing that the 2nd item ("Software") on the list should not be printed/inside in the first place, as it is not as such in the actual directory structure of HKEY_CURRENT_CONFIG ['Software\\Fonts', 'Software', 'System\\CurrentControlSet\\Control\\Print\\Printers\\HP Deskjet F300 Series', 'System\\CurrentControlSet\\Control\\Print\\Printers', 'System\\CurrentControlSet\\Control\\Print', 'System\\CurrentControlSet\\Control\\VIDEO', 'System\\CurrentControlSet\\Control', 'System\\CurrentControlSet\\SERVICES\\TSDDD\\DEVICE0', 'System\\CurrentControlSet\\SERVICES\\TSDDD', 'System\\CurrentControlSet\\SERVICES\\VGASAVE\\DEVICE0', 'System\\CurrentControlSet\\SERVICES\\VGASAVE', 'System\\CurrentControlSet\\SERVICES', 'System\\CurrentControlSet', 'System'] -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmbaio at gmail.com Wed Feb 5 16:47:38 2014 From: jmbaio at gmail.com (Juan Manuel Lopez Baio) Date: Wed, 5 Feb 2014 13:47:38 -0200 Subject: [Tutor] Changing only intergers in a list of strings In-Reply-To: References: Message-ID: On Wed, Feb 5, 2014 at 7:47 AM, David Palao wrote: > Sorry, there is a typo: > "(num+a,)" should be "(num+1,)", obviously. > > 2014-02-05 David Palao : >> Hi, >> Is it not clear to me if you must distinguish ints from other type of >> numbers, or if, for instances floats and ints must be dealt >> differently. >> Anyway, I would propose something like the following function: >> >> def FindNumbers(a_string): >> print "You entered:", a_string >> out_list = [] >> for item in a_string.split(): >> try: >> num = int(item) >> except ValueError: >> out_list.append(item) >> else: >> out_list.append("%s" % (num+a,)) >> out_string = ' '.join(out_list) >> # do whatever you want to do with the resulting out_string: >> return it, or display it... hi, I thought it might be interesting to make this work for cases where the numbers are not necessarily "word-separated" i.e., something like '12this is a rather odd string,3 I know 32. ' with regular expressions, I managed this: >>> import re >>> st = '12this is a rather odd string,3 I know 32. ' >>> pattern = r'(\d+|\D+)' # any digit one or more times OR any non-digit one or more times >>> re.findall(pattern,st) ['12', 'this is a rather odd string,', '3', ' I know ', '32', '. '] which allows me to increment each integer and reconstruct the string, just iterating through the list. now, I would like to construct a pattern such that this next alternative usage works (my intention is to embed the 'findall' logic in the pattern itself): >>>re.search(pattern,st).groups() returning a tuple instead of a list, but with the same elements as before. I've been trying for a while and can't find a way to make it work. Does anyone know if this is possible? thank you From mail at timgolden.me.uk Wed Feb 5 19:01:31 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 05 Feb 2014 18:01:31 +0000 Subject: [Tutor] Advice on Python codes - A recursive function to output entire directory subkeys of Windows Registry In-Reply-To: <1391614235.50058.YahooMailNeo@web192801.mail.sg3.yahoo.com> References: <1391614235.50058.YahooMailNeo@web192801.mail.sg3.yahoo.com> Message-ID: <52F27C7B.30202@timgolden.me.uk> On 05/02/2014 15:30, Alan Ho wrote: > Hi, > > I am a novice in Python, having attended a course few weeks ago and I'm > working on my assignment now, and I encounter this issue when I was > trying to print the entire Windows Registry (WR) sub-keys directories > (trying that first with the below codes with adaptations from on-line > research) and its value (later on). > > Kindly advise if any, as it has been taking me few days. What I need is > a display on the std screen the entire directory of sub-keys (inserted > into a list) in a WR key say, HKEY_CURRENT_FIG, and then I will write > the contents into a text or CSV file. > Thanks advance! > > Here are my codes, > > ----------------- > import winreg > > def traverse(root, key, list): > hKey = winreg.OpenKey(root, key) > try: > i = 0 > while True: > strFullSubKey = "" > try: > strSubKey = winreg.EnumKey(hKey, i) > if (key != ""): > strFullSubKey = key + "\\" + strSubKey > else: > strFullSubKey = strSubKey > except WindowsError: > hKey.Close() > return > traverse(root, strFullSubKey, list) > list.append(strFullSubKey) > i += 1 > > except WindowsError: > hKey.Close() > > global list > list = list() > traverse (winreg.HKEY_CURRENT_CONFIG,"",list) > print (list) > > ----------------- > > results on screen, which is not very correct, seeing that the 2nd item > ("Software") on the list should not be printed/inside in the first > place, as it is not as such in the actual directory structure of > HKEY_CURRENT_CONFIG My box has "Software" and "Software\Fonts" within HKEY_CURRENT_CONFIG. But, to give you a slightly different answer, you could try putting print() calls in at various points so you can understand the flow of the program if you're not sure it's doing the right thing. TJG From oscar.j.benjamin at gmail.com Wed Feb 5 20:36:20 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 5 Feb 2014 19:36:20 +0000 Subject: [Tutor] Python packaging Was:Re: sys.path.append import python3 not working Message-ID: On 5 February 2014 16:42, ALAN GAULD wrote: > >> And after 15 years of using Python I didn't know it existed until now! >> I've always used a local directory and added it to PYTHONPATH... > > Then maybe you're also not aware of the --user option for > pip/easy_install. That's how I discovered the user site-packages > directory. > > To be honest I've not really used pip or easy_install much. > Most of what I do uses the standard library. The only extra packages > I use are BeautifulSoup(very rarely) and wxPython(also rarely) > and TurboGears and Django once each. > > In fact, one of the things I'm playing with just now is the whole > distutils packaging thing and reading up on eggs etc. Frankly it's > all a bit of a mess and I hope the promised improvements from > Python 3.4 onwards will make it a lot less messy! The only improvement Python 3.4 brings is that pip and setuptools will usually be bundled with Python so that you don't need to install them separately. Any other improvements will be available to all Python versions provided you update pip and setuptools. (Many people will always do this stuff in virtualenvs so that they're always using newest pip and setuptools). If you're not looking to package/install C extensions then actually the situation right now is pretty good. Distutils, pip, setuptools and PyPI work pretty well for distributing pure Python code. It's also straight-forward to have dependencies on other packages on PyPI that will be resolved automatically when the user asks to install your package. The wheel format is supposed to replace the (effectively deprecated) egg format and makes it viable to distribute precompiled C extensions for Windows users (and soon for OSX users also). It's not clear how viable that will ever be on Linux et al because of the different libc ABIs. Oscar From colin.chinsammy at erickson.com Wed Feb 5 19:34:49 2014 From: colin.chinsammy at erickson.com (Colin Chinsammy) Date: Wed, 5 Feb 2014 18:34:49 +0000 Subject: [Tutor] Which computer operating system is best for Python Message-ID: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> I am considering purchasing the Acer c720 chromebook for my 13yo to begin learning Python for Kids. Obviously I am on a budget. Is this a good choice for a complete beginner? Any particular challenges that she might encounter using a chromebook OS? Any advice would be greatly appreciated. As I have researched my way into confusion. Thanks Colin Chinsammy Transportation Coord Transportation Office: 703-923-3150 7400 Spring Village Drive Springfield, VA 22150 www.EricksonLiving.com [cid:image001.jpg at 01CF2276.489ABEE0] [cid:image002.png at 01CF2276.489ABEE0] [cid:image003.png at 01CF2276.489ABEE0] [cid:image004.png at 01CF2276.489ABEE0] [cid:image005.png at 01CF2276.489ABEE0] The information in this email is intended only for the person or entity to which it is addressed and may contain confidential and/or privileged material. Any review, retransmissions, dissemination or other use of or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you receive this email in error, please contact the sender and delete the material from any computer. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 11597 bytes Desc: image001.jpg URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image002.png Type: image/png Size: 2005 bytes Desc: image002.png URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image003.png Type: image/png Size: 2011 bytes Desc: image003.png URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image004.png Type: image/png Size: 1831 bytes Desc: image004.png URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image005.png Type: image/png Size: 1430 bytes Desc: image005.png URL: From alan.gauld at btinternet.com Thu Feb 6 00:13:29 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Feb 2014 23:13:29 +0000 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: On 05/02/14 18:34, Colin Chinsammy wrote: > I am considering purchasing the Acer c720 chromebook for my 13yo to > begin learning Python for Kids. Obviously I am on a budget. I wouldn't consider a Chromebpook for anyone learning programming. They are fine for folks who are happy to do everything "in the cloud" but programming is not one of the things that works well there IMHO. A netbook or basic laptop is a little more expensive but much more powerful and flexible. It doesn't need to be state of the art or even a latest generation model but the ability to install and run programs locally is crucial. I don't know about prices in the US but the difference in price between a Chromebook and a basic laptop/netbook in the UK is less than 25%. The Chromebook may look sexier but it's far less useful to a wannabe programmer. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From joel.goldstick at gmail.com Thu Feb 6 00:18:56 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 5 Feb 2014 18:18:56 -0500 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: On Feb 5, 2014 6:14 PM, "Alan Gauld" wrote: > > On 05/02/14 18:34, Colin Chinsammy wrote: >> >> I am considering purchasing the Acer c720 chromebook for my 13yo to >> begin learning Python for Kids. Obviously I am on a budget. > > > I wouldn't consider a Chromebpook for anyone learning programming. > They are fine for folks who are happy to do everything "in the cloud" but programming is not one of the things that works well there IMHO. > > A netbook or basic laptop is a little more expensive but > much more powerful and flexible. It doesn't need to be state > of the art or even a latest generation model but the ability > to install and run programs locally is crucial. > > I don't know about prices in the US but the difference in > price between a Chromebook and a basic laptop/netbook in > the UK is less than 25%. The Chromebook may look sexier > but it's far less useful to a wannabe programmer. > > hth > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor I would get a laptop with as large a screen as you can afford. Windows or Linux. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 6 00:39:32 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Feb 2014 23:39:32 +0000 Subject: [Tutor] Python packaging Was:Re: sys.path.append import python3 not working In-Reply-To: References: Message-ID: On 05/02/14 19:36, Oscar Benjamin wrote: >> all a bit of a mess and I hope the promised improvements from >> Python 3.4 onwards will make it a lot less messy! > > The only improvement Python 3.4 brings is that pip and setuptools will > usually be bundled with Python Yes, I wasn't expecting 3.4 to deliver much but it is the official starting point for the recent PPA roadmap to unify the distribution tools for python. It was that vision and roadmap I was alluding to rather than 3.4 itself. The one Nick Coghlan describes here: http://pyvideo.org/video/2197/nobody-expects-the-python-packaging-authority -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From marc.tompkins at gmail.com Thu Feb 6 01:23:57 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 5 Feb 2014 16:23:57 -0800 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: On Wed, Feb 5, 2014 at 3:18 PM, Joel Goldstick wrote: > I would get a laptop with as large a screen as you can afford. Windows or > Linux. > > I second that emotion, and also: try out the keyboard first (or rather, have your kid try it out). We spend a lot of time on our laptops, and a badly-designed keyboard can ruin an otherwise-great machine. Yes, you can plug in an external keyboard, mouse, and monitor, but most of the time you're gonna stick with what came in the box. Make sure you won't hate it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at pythontoo.com Thu Feb 6 01:35:21 2014 From: david at pythontoo.com (David Abbott) Date: Wed, 5 Feb 2014 19:35:21 -0500 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: On Wed, Feb 5, 2014 at 7:23 PM, Marc Tompkins wrote: > On Wed, Feb 5, 2014 at 3:18 PM, Joel Goldstick > wrote: >> >> I would get a laptop with as large a screen as you can afford. Windows or >> Linux. >> > I second that emotion, and also: try out the keyboard first (or rather, have > your kid try it out). We spend a lot of time on our laptops, and a > badly-designed keyboard can ruin an otherwise-great machine. Yes, you can > plug in an external keyboard, mouse, and monitor, but most of the time > you're gonna stick with what came in the box. Make sure you won't hate it. Linux runs great on older Laptops that were the top of the line in their day, two nice examples with great keyboards are dell e6400 and ibm T61's. Linux is easy to install and set up now a days :) -- David Abbott From tdkrupinski at gmail.com Thu Feb 6 02:51:51 2014 From: tdkrupinski at gmail.com (Tim Krupinski) Date: Wed, 5 Feb 2014 19:51:51 -0600 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: I would agree with David and others. For programming, a chromebook would not be a good choice because you can't install any type of development environment onto the machine itself. Get something with a big screen and, preferably a full keyboard - I'm talking full size in the sense that you have the numeric keypad to the right. Unless you look a little deeper most options available will be windows based. Not a problem - I would recommend using a piece of software called "Virtualbox". It is freely available and distributed by Oracle. It will allow you to install a Linux operating system on a "Virtual" machine that runs within windows. While this may seem complicated to somebody without experience in this area, there are great tutorials on this and the process is much more straightforward than it was just a couple years ago. The reason I suggest Linux is because a lot of Python is used in it already. Once it's installed, you are ready to go. Also, a lot of documentation you find on how to set up and configure a Python environment assumes you are using Linux. While Windows isn't entirely dissimilar, there are a few key differences which could make it more frustrating to navigate for first time users. Plus, most popular distributions make it *very *easy to install python addons and libraries. As an ancillary benefit, your child will also be learning Linux as he learns to program. On Wed, Feb 5, 2014 at 6:35 PM, David Abbott wrote: > On Wed, Feb 5, 2014 at 7:23 PM, Marc Tompkins > wrote: > > On Wed, Feb 5, 2014 at 3:18 PM, Joel Goldstick > > > wrote: > >> > >> I would get a laptop with as large a screen as you can afford. Windows > or > >> Linux. > >> > > I second that emotion, and also: try out the keyboard first (or rather, > have > > your kid try it out). We spend a lot of time on our laptops, and a > > badly-designed keyboard can ruin an otherwise-great machine. Yes, you > can > > plug in an external keyboard, mouse, and monitor, but most of the time > > you're gonna stick with what came in the box. Make sure you won't hate > it. > > Linux runs great on older Laptops that were the top of the line in > their day, two nice examples with great keyboards are dell e6400 and > ibm T61's. Linux is easy to install and set up now a days :) > > > -- > David Abbott > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Feb 6 03:11:47 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 6 Feb 2014 13:11:47 +1100 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: <20140206021147.GY3799@ando> On Wed, Feb 05, 2014 at 07:51:51PM -0600, Tim Krupinski wrote: > I would agree with David and others. For programming, a chromebook would > not be a good choice because you can't install any type of development > environment onto the machine itself. Get something with a big screen and, > preferably a full keyboard - I'm talking full size in the sense that you > have the numeric keypad to the right. Does anyone use the numeric keypad for programming? I'd hardly consider it essential. Having the keys large enough to comfortably type is essential. Arrow keys and the usual Home/End/Page Up/Page Down keys being readily available, that's essential. As far as "big screen" goes, please remember that the OP is on a budget, and the bigger the screen the less portable the laptop and the less battery life. > Unless you look a little deeper most > options available will be windows based. Not a problem - I would recommend > using a piece of software called "Virtualbox". It is freely available and > distributed by Oracle. It will allow you to install a Linux operating > system on a "Virtual" machine that runs within windows. While this may > seem complicated to somebody without experience in this area, there are > great tutorials on this and the process is much more straightforward than > it was just a couple years ago. But still complex. And you're limited by the (lack of) stability of Windows. If you don't *need* Windows, there is no point in running Linux on top of Windows in a virtual machine. It just means you're using twice as much memory, and you are still bound by the stability of Windows. [...] > As an ancillary benefit, > your child will also be learning Linux as he learns to program. I believe that Colin is buying this laptop for his daughter. -- Steven From jeanpierreda at gmail.com Thu Feb 6 03:17:37 2014 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 5 Feb 2014 18:17:37 -0800 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: On Wed, Feb 5, 2014 at 4:35 PM, David Abbott wrote: > Linux runs great on older Laptops that were the top of the line in > their day, two nice examples with great keyboards are dell e6400 and > ibm T61's. Linux is easy to install and set up now a days :) FWIW linux does, but firefox and chrome don't. I've found that they work very poorly on older machines with little memory. I also second anyone that suggests Linux is good for learning Python. I found it a very conducive platform to learn Python on when I first learned, even as a new linux user -- it makes it really easy to get everything you need, and it encourages development practices (in particular, using a terminal, but also things like using a real text editor) that make programming easier both short- and longer- term. It's also not that hard to learn, especially for children, especially compared to Python. -- Devin From steve at pearwood.info Thu Feb 6 03:27:51 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 6 Feb 2014 13:27:51 +1100 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: <20140206022751.GZ3799@ando> On Wed, Feb 05, 2014 at 06:34:49PM +0000, Colin Chinsammy wrote: > I am considering purchasing the Acer c720 chromebook for my 13yo to > begin learning Python for Kids. Obviously I am on a budget. Is this a > good choice for a complete beginner? Any particular challenges that > she might encounter using a chromebook OS? Any advice would be greatly > appreciated. As I have researched my way into confusion. I've never used Chromebook, and I'm philosophically and practically opposed to any system which works "on the cloud" instead of on a machine I control. More importantly, how are your daughter's skills? Is she interested in programming? I've seen too many people decide that because their son or daughter is browsing Facebook all the time, they must be "good with computers". Don't be one of them :-) If you can afford a MacBook, it is probably the best for people who are not technically minded, as well as those who are. Some of the computer techs and programmers I work with wouldn't be caught dead without their Mac. If your daughter is really interested in the technical side of computers, and wants to roll up her sleeves and understand *everything* about how modern computers work, Linux is probably the best system to go for. You can run a modern, up-to-date Linux system on a two or five year old laptop, and with a few careful choices and tweaks, have just as good or better performance than Windows on a brand-new laptop. In my experience, in order of preference, I would say: Debian-based Linux (best) Other Linux Mac OS Windows (worst) with ChromeOS an unknown. But when I say Windows is the worst for Python programming, that doesn't mean you can't do it. It just means that there may be a few bumps in the road that you don't get with other systems. -- Steven From kfiresmith at gmail.com Thu Feb 6 03:51:42 2014 From: kfiresmith at gmail.com (Kodiak Firesmith) Date: Wed, 5 Feb 2014 21:51:42 -0500 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: <20140206022751.GZ3799@ando> References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> <20140206022751.GZ3799@ando> Message-ID: In response to the OP with considerations for budget and the target learner: * At this stage in operating systems and python setups, I posit that the easiest and most meritorious path is to use a "beginner's Linux" that is easy to install and focuses on a good desktop experience. The best offering in this area right now is Linux Mint (version 16, "Cinnamon" edition http://www.linuxmint.com/download.php). * You are in a *very* good area for finding a quality laptop on Craigslist. I lived in Arlington from 2008-2012 and purchased computer equipment almost exclusively on the 2nd hand market as it is flooded with recent cast-offs from well-off techies who sell last generation stuff for a fraction of what you would pay new. You should be able to find an Intel core i3/i5 based laptop in the $225 range locally if you keep an eye out for a few days. * High resolution screens are nice but will price you out, so just look for a typical 15.4" laptop since it will provide a decent sized keyboard and even if it's only 1366x768, the bigger screen makes it easier on the eyes when first learning to program. It also makes it easier for those who may be watching over her shoulder to help. * I would vote against a Chrome OS based device for a number of practical reasons when considering a computer for learning how to do anything, but especially coding. I hope this helps, - Kodiak On Wed, Feb 5, 2014 at 9:27 PM, Steven D'Aprano wrote: > On Wed, Feb 05, 2014 at 06:34:49PM +0000, Colin Chinsammy wrote: > > > I am considering purchasing the Acer c720 chromebook for my 13yo to > > begin learning Python for Kids. Obviously I am on a budget. Is this a > > good choice for a complete beginner? Any particular challenges that > > she might encounter using a chromebook OS? Any advice would be greatly > > appreciated. As I have researched my way into confusion. > > I've never used Chromebook, and I'm philosophically and practically > opposed to any system which works "on the cloud" instead of on a > machine I control. > > More importantly, how are your daughter's skills? Is she interested > in programming? I've seen too many people decide that because their son > or daughter is browsing Facebook all the time, they must be "good with > computers". Don't be one of them :-) > > If you can afford a MacBook, it is probably the best for people who are > not technically minded, as well as those who are. Some of the computer > techs and programmers I work with wouldn't be caught dead without their > Mac. > > If your daughter is really interested in the technical side of > computers, and wants to roll up her sleeves and understand *everything* > about how modern computers work, Linux is probably the best system to go > for. You can run a modern, up-to-date Linux system on a two or five year > old laptop, and with a few careful choices and tweaks, have just as good > or better performance than Windows on a brand-new laptop. > > In my experience, in order of preference, I would say: > > Debian-based Linux (best) > Other Linux > Mac OS > Windows (worst) > > with ChromeOS an unknown. But when I say Windows is the worst for Python > programming, that doesn't mean you can't do it. It just means that there > may be a few bumps in the road that you don't get with other systems. > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Feb 6 05:00:24 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 5 Feb 2014 20:00:24 -0800 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> <20140206022751.GZ3799@ando> Message-ID: Hi everyone, > * I would vote against a Chrome OS based device for a number of practical > reasons when considering a computer for learning how to do anything, but > especially coding. I'm not quite sure what to make of the above statement: it seems a bit broad. Anyway, there seems to be an underlying agreement here that, for programming, a Linux distribution is a good base for programming. There is the Crouton project, which is to allow installation of Linux on Chromebooks. https://github.com/dnschneid/crouton Preliminary google search results suggest that the support for the Acer C720 isn't quite perfect at the time of this writing. But some other Chromebooks appear to work fine with Crouton. I would expect the support to gradually get better (which is probably a familiar situation for those who use Linux with new shiny laptops.) I would not call installing Linux on a Chromebook a scenario that is quite beginner friendly, so this may not be a good option for a complete beginner. It _might_ be a good option for someone who is very familiar with Linux and willing to hack at it. I think a lot of folks here don't sympathize enough with how stupidly difficult software installation can be. With regards to learning basic Python programming, regardless of computing environment, one might look into sites like: http://repl.it/languages/Python which provide an editing and evaluating environment. Being on the web does mean you have less control over the environment. But it also means you don't have to install anything. That can be very useful for a beginner. There are other web-based computing environments out there. Having worked for one in http://wescheme.org and http://bootstrapworld.org, I do have a responsibility to say: web-based online programming environments do have their good sides as well. Good luck to you! From dyoo at hashcollision.org Thu Feb 6 05:19:55 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 5 Feb 2014 20:19:55 -0800 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> <20140206022751.GZ3799@ando> Message-ID: ... reading through the rest of this thread... I'm surprised no one has mentioned: http://www.codecademy.com/tracks/python Depending on your child's level, you might even look at Scratch: http://scratch.mit.edu/ which is not Python at all, but it is programming, and it is very much focused on the beginner experience. From dyoo at hashcollision.org Thu Feb 6 05:42:12 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 5 Feb 2014 20:42:12 -0800 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: On Wed, Feb 5, 2014 at 10:34 AM, Colin Chinsammy < colin.chinsammy at erickson.com> wrote: > I am considering purchasing the Acer c720 chromebook for my 13yo to > begin learning Python for Kids. Obviously I am on a budget. > > Is this a good choice for a complete beginner? Any particular challenges > that she might encounter using a chromebook OS? > > Any advice would be greatly appreciated. As I have researched my way into > confusion. > > Hi Colin, Ok, I read this question a little more carefully. You're planning to use the book "Python for Kids", right? http://shop.oreilly.com/product/9781593274078.do If using that book is a requirement, then I have to take back what I said about web environments being appropriate for this particular situation. That book requires a computer running either Windows, Mac OS X, or Linux. It will have some exercises that assume that it can have graphical control over the desktop with the "Tk" graphics library, a capability that you will not likely have in a web-based environment. Apologies for not reading the requirements more closely. I saw "learning Python for kids", and did not think that you were referring to a specific book! :P -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Feb 6 06:38:19 2014 From: davea at davea.name (Dave Angel) Date: Thu, 6 Feb 2014 00:38:19 -0500 (EST) Subject: [Tutor] Which computer operating system is best for Python References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> <20140206021147.GY3799@ando> Message-ID: Steven D'Aprano Wrote in message: > > > > > But still complex. And you're limited by the (lack of) stability of > Windows. > > If you don't *need* Windows, there is no point in running Linux on top > of Windows in a virtual machine. It just means you're using twice as > much memory, and you are still bound by the stability of Windows. > Right. I repartitioned my drive, shrank the installed Windows partition to a minimum, and installed linux as a dual boot. If I really need a Windows program, I run it in a Virtual box with XP. > > > -- DaveA From sacharook at gmail.com Thu Feb 6 08:41:12 2014 From: sacharook at gmail.com (Sacha Rook) Date: Thu, 6 Feb 2014 07:41:12 +0000 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: Hi as much as I like chrome books.... My opinion so I would rather give him a laptop either with Linux or windows with free virtualisation software on to run either so and program on both especially if he will be offline. Alternative if you have wifi/network constant connection then just a browser and spin up a free tier aws host and program on that. It's good to get a grasp early of things like git github an IDE and a appstack on a PaaS to run the apps developed, like aws elastic beanstalk or heroku. The reason I say this is that it's great to learn python but it's great to learn about using it in the real world... Again my opinion hope it's useful to you. S On Wednesday, 5 February 2014, Colin Chinsammy wrote: > I am considering purchasing the Acer c720 chromebook for my 13yo to > begin learning Python for Kids. Obviously I am on a budget. > > Is this a good choice for a complete beginner? Any particular challenges > that she might encounter using a chromebook OS? > > Any advice would be greatly appreciated. As I have researched my way into > confusion. > > > > Thanks > > > > *Colin Chinsammy* > Transportation Coord > Transportation > Office: 703-923-3150 > 7400 Spring Village Drive > Springfield, VA 22150 > www.EricksonLiving.com > > > > > > > > > > > > > > > > The information in this email is intended only for the person or entity to > which it is addressed and may contain confidential and/or privileged > material. Any review, retransmissions, dissemination or other use of or > taking of any action in reliance upon this information by persons or > entities other than the intended recipient is prohibited. If you receive > this email in error, please contact the sender and delete the material from > any computer. > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image002.png Type: image/png Size: 2005 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image005.png Type: image/png Size: 1430 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 11597 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image004.png Type: image/png Size: 1831 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image003.png Type: image/png Size: 2011 bytes Desc: not available URL: From alan.gauld at btinternet.com Thu Feb 6 10:46:54 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Feb 2014 09:46:54 +0000 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: <20140206021147.GY3799@ando> References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> <20140206021147.GY3799@ando> Message-ID: On 06/02/14 02:11, Steven D'Aprano wrote: > But still complex. And you're limited by the (lack of) stability of > Windows. Unless you are running a server a modern Windows set up is stable enough. Since windows 7 and 8 the core OS is far better than earlier incarnations. I've only had one BSOD in the last 5 years and I've had at least two kernel panics on my Linux boxes in that time. But then I use Linux(70%?) more than Windows(15%?)... The big bugbear with Windows is not instability per se but the need to reboot it every time you change anything. Linux is much better for that. But for an ordinary user, once you have the basic setup and apps in place I don't think Windows stability is a real factor any more. Especially on a laptop that will likely be reboot every day anyway! And for a beginner who is only programming casually and likely doing other things with the PC a Windows box makes a lot of sense since other programs are more plentiful and generally better quality for casual use. If you want to become a pro then sure Linux is great and without doubt the best development OS around. But for a 13 year old casual user? I doubt it makes much difference. All IMHO of course :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Feb 6 10:52:56 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Feb 2014 09:52:56 +0000 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: On 05/02/14 18:34, Colin Chinsammy wrote: > I am considering purchasing the Acer c720 chromebook for my 13yo to > begin learning Python for Kids. Obviously I am on a budget. One option which is aimed at the kids eduication kind of market and hasn't been mentioned is the RasberryPi. Its very Python friendly and cheap and whilst not portable in the sense of a Chromebook it is certainly small enough to transport to anywhere that has a USB keyboard mouse and a monitor/TV. Just a thought. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Thu Feb 6 12:09:07 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 6 Feb 2014 22:09:07 +1100 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: <20140206110907.GB3799@ando> Hi Sasha, and welcome! On Thu, Feb 06, 2014 at 07:41:12AM +0000, Sacha Rook wrote: > Hi as much as I like chrome books.... > > My opinion so I would rather give him a laptop ....................................^^^ Her. I'll just drop this link here: http://www.linuxjournal.com/content/girls-and-software and for a less positive side: http://www.tgdaily.com/software-features/41053-linux-saga-girl-drops-out-of-school-over-ubuntu One of the reasons I'm not a big fan of Ubuntu. Too many wanna-be macho-men with a chip on their shoulder. -- Steven From steve at pearwood.info Thu Feb 6 12:25:53 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 6 Feb 2014 22:25:53 +1100 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: <20140206110907.GB3799@ando> References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> <20140206110907.GB3799@ando> Message-ID: <20140206112552.GD3799@ando> On Thu, Feb 06, 2014 at 10:09:07PM +1100, Steven D'Aprano wrote: > Hi Sasha, and welcome! Correction, Sacha. Sorry about that, I know how annoying it is to have your name misspelled. -- Steven From denis.spir at gmail.com Thu Feb 6 13:02:39 2014 From: denis.spir at gmail.com (spir) Date: Thu, 06 Feb 2014 13:02:39 +0100 Subject: [Tutor] Advice on Python codes - A recursive function to output entire directory subkeys of Windows Registry In-Reply-To: <1391614235.50058.YahooMailNeo@web192801.mail.sg3.yahoo.com> References: <1391614235.50058.YahooMailNeo@web192801.mail.sg3.yahoo.com> Message-ID: <52F379DF.4020409@gmail.com> On 02/05/2014 04:30 PM, Alan Ho wrote: > Hi, > > I am a novice in Python, having attended a course few weeks ago and I'm working on my assignment now, and I encounter this issue when I was trying to print the entire Windows Registry (WR) sub-keys directories (trying that first with the below codes with adaptations from on-line research) and its value (later on). > > Kindly advise if any, as it has been taking me few days. What I need is a display on the std screen the entire directory of sub-keys (inserted into a list) in a WR key say, HKEY_CURRENT_FIG, and then I will write the contents into a text or CSV file. > Thanks advance! > > Here are my codes, > > ----------------- > import winreg > > def traverse(root, key, list): > hKey = winreg.OpenKey(root, key) > try: > i = 0 > while True: > strFullSubKey = "" > try: > strSubKey = winreg.EnumKey(hKey, i) > if (key != ""): > strFullSubKey = key + "\\" + strSubKey > else: > strFullSubKey = strSubKey > except WindowsError: > hKey.Close() > return > traverse(root, strFullSubKey, list) > list.append(strFullSubKey) > i += 1 > > except WindowsError: > hKey.Close() > > global list > list = list() > traverse (winreg.HKEY_CURRENT_CONFIG,"",list) > print (list) > > ----------------- This is all right in my view, a good example of (forward) recursive traversal (like for a tree). Very functional programming (FP), in fact. However, even in FP, people often make up a more "intuitive" interface to their functions, and I guess this would be much more pythonic. If you did this, your program may look like: def win_key (): def rec_keys (node, key, list): # often called 'loop' # recursive func keys = list() rec_keys (winreg.HKEY_CURRENT_CONFIG, "", keys) return keys keys = win_keys() print(keys) First look at the last lines: they form a simple, "intuitive", usage. They are just what the client of your service --making a list of win reg keys-- expects, right? To achieve this, you have to make the recursivity an internal quality of the service, an "implementation detail". Clinet, users, don't care how you do it internally, you could in fact do ot otherwise, and they (the clients) should not be forced to deal with tyour implementation requirements or choices. The example above thus defines an *internal* recursive func, the FP equivalent of a loop (for thos reason often called 'loop' in FP code). With (such) recursive funcs, we must pass to the func a start or end case (root=winreg.HKEY_CURRENT_CONFIG), a current index (key=""), a temporary result (list=list). This is what users should not be forced to deal with. Side-note: avoid using python built-in names like 'list'. PS: I don't understand why there is an outer try...except. The only statement in there that may fail I guess is "traverse(root, strFullSubKey, list)", but this is a self-call (self-recursive), so possible failure are already caught in the inner try...except. What happens if you get rid of it, and why? (I may be wrong, but I suspect the following: you first had WindowsError exceptions and to deal with them introduced the outer try...except; then, because of the self-call, you had to introduce the inner try...except; but in fact the latter is the only one you need, it catches all possible exception of the process, WindowsError's. Notice both try...except constructs catch WindowsError's. Again i may be wrong.) d From denis.spir at gmail.com Thu Feb 6 13:45:21 2014 From: denis.spir at gmail.com (spir) Date: Thu, 06 Feb 2014 13:45:21 +0100 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: <52F383E1.3030909@gmail.com> On 02/06/2014 12:13 AM, Alan Gauld wrote: > On 05/02/14 18:34, Colin Chinsammy wrote: >> I am considering purchasing the Acer c720 chromebook for my 13yo to >> begin learning Python for Kids. Obviously I am on a budget. > > I wouldn't consider a Chromebpook for anyone learning programming. > They are fine for folks who are happy to do everything "in the cloud" but > programming is not one of the things that works well there IMHO. > > A netbook or basic laptop is a little more expensive but > much more powerful and flexible. It doesn't need to be state > of the art or even a latest generation model but the ability > to install and run programs locally is crucial. > > I don't know about prices in the US but the difference in > price between a Chromebook and a basic laptop/netbook in > the UK is less than 25%. The Chromebook may look sexier > but it's far less useful to a wannabe programmer. I second Alan's advice. For programming, especially learning, you don't need power (memory including, CPU freq, etc). In fact, you need very very few. (On the other hand, as user, *running* some rare progs may require much power.) I would put the price in the screen: as programmers, people spend all their time *reading*, this for very long periods of time. We read our code, other people's code (much more than you'd think), tutorials, docs, articles... This, in editors or IDE's, web browsers, email readers, terminals... We need comfort. Display quality. And also space to have several windows open constantly (possibly overlapping). [I'd recommend at least 21''. And rather 16/10 or even 4/3 if you can find one, than hypish 16/9 which are only good for pirating films ;-). What we miss in programming and reading is rather vertical space; we would be better at embracing more at once vertically; we're constantly moving up & down, because screens are wide and not high.] d From denis.spir at gmail.com Thu Feb 6 13:54:39 2014 From: denis.spir at gmail.com (spir) Date: Thu, 06 Feb 2014 13:54:39 +0100 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> Message-ID: <52F3860F.3010003@gmail.com> On 02/06/2014 02:51 AM, Tim Krupinski wrote: > The reason I suggest Linux is because a lot of Python is used in it > already. People was also designed (according to Guido vR) to please Unix/C hackers. d From neilc at norwich.edu Thu Feb 6 14:38:29 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 6 Feb 2014 13:38:29 +0000 (UTC) Subject: [Tutor] Which computer operating system is best for Python References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> <20140206021147.GY3799@ando> Message-ID: On 2014-02-06, Alan Gauld wrote: > And for a beginner who is only programming casually and likely > doing other things with the PC a Windows box makes a lot of > sense since other programs are more plentiful and generally > better quality for casual use. > > If you want to become a pro then sure Linux is great and > without doubt the best development OS around. But for a 13 year > old casual user? I doubt it makes much difference. Linux is a great OS for a child to learn computing and programming on, provided the parent knows it well enough to train the student on it. If not, it's just inviting needless headaches. -- Neil Cerutti From leamhall at gmail.com Thu Feb 6 15:35:27 2014 From: leamhall at gmail.com (leam hall) Date: Thu, 6 Feb 2014 09:35:27 -0500 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> <20140206021147.GY3799@ando> Message-ID: On Thu, Feb 6, 2014 at 8:38 AM, Neil Cerutti wrote: > Linux is a great OS for a child to learn computing and > programming on, provided the parent knows it well enough to train > the student on it. If not, it's just inviting needless headaches. Look at http://www.edubuntu.org/ Leam --- Mind on a Mission From denis.heidtmann at gmail.com Thu Feb 6 20:28:25 2014 From: denis.heidtmann at gmail.com (Denis Heidtmann) Date: Thu, 6 Feb 2014 11:28:25 -0800 Subject: [Tutor] learning recursion Message-ID: Running python 2.7 on Ubuntu 12.04 Code: def fib2(n): if n==1: return 1 elif n==2: return 1 else: return fib2(n-2) +fib2(n-1) The above works: >>> fib2(7) 13 >>> fib2(4) 3 >>> for i in range(4): ... print fib2(i) ... The above results in an error: Traceback (most recent call last): File "", line 2, in File "testing.py", line 21, in fib2 return fib2(n-2) +fib2(n-1) File "testing.py", line 21, in fib2 return fib2(n-2) +fib2(n-1) File "testing.py", line 21, in fib2 return fib2(n-2) +fib2(n-1) RuntimeError: maximum recursion depth exceeded >>> Is this some subtle problem or is it some stupid mistake on my part? Thanks for your help. -Denis H. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Feb 6 20:45:06 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Feb 2014 20:45:06 +0100 Subject: [Tutor] learning recursion References: Message-ID: Denis Heidtmann wrote: > Running python 2.7 on Ubuntu 12.04 > > Code: > def fib2(n): > if n==1: > return 1 > elif n==2: > return 1 > else: > return fib2(n-2) +fib2(n-1) > > The above works: > >>>> fib2(7) > 13 >>>> fib2(4) > 3 > >>>> for i in range(4): > ... print fib2(i) > ... > > The above results in an error: > > Traceback (most recent call last): > File "", line 2, in > File "testing.py", line 21, in fib2 > return fib2(n-2) +fib2(n-1) > File "testing.py", line 21, in fib2 > return fib2(n-2) +fib2(n-1) > > > > File "testing.py", line 21, in fib2 > return fib2(n-2) +fib2(n-1) > RuntimeError: maximum recursion depth exceeded >>>> > > Is this some subtle problem or is it some stupid mistake on my part? Try to figure out how fib2(0) is evaluated. From neilc at norwich.edu Thu Feb 6 20:44:40 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 6 Feb 2014 19:44:40 +0000 (UTC) Subject: [Tutor] learning recursion References: Message-ID: On 2014-02-06, Denis Heidtmann wrote: > Running python 2.7 on Ubuntu 12.04 > > Code: > def fib2(n): > if n==1: > return 1 > elif n==2: > return 1 > else: > return fib2(n-2) +fib2(n-1) Something ate your leading spaces. Keep in mind that that makes most Python code unrecoverably corrupt. When sharing Python code you have to take care that leading space (preferably) or tabs (if you must) are preserved. > The above works: > >>>> fib2(7) > 13 >>>> fib2(4) > 3 > >>>> for i in range(4): > ... print fib2(i) > ... > > The above results in an error: > > File "testing.py", line 21, in fib2 > return fib2(n-2) +fib2(n-1) > RuntimeError: maximum recursion depth exceeded > > Is this some subtle problem or is it some stupid mistake on my > part? > > Thanks for your help. It's because fib(0) never terminates. The fibonacci numbers should start with (1, 1, 2) i.e., fib(0) ought to return 1, with the rest of your algorithm adjusted accordingly. -- Neil Cerutti From dyoo at hashcollision.org Thu Feb 6 20:44:02 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 6 Feb 2014 11:44:02 -0800 Subject: [Tutor] learning recursion In-Reply-To: References: Message-ID: Ah. Consider what range(4) looks like. It's similar to the sequence: [0, 1, 2, 3] What happens when you do fib2(0)? :P Here's your program (modified with a correction) on repl.it, for convenience: http://repl.it/O30 From jeanpierreda at gmail.com Thu Feb 6 20:38:29 2014 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Thu, 6 Feb 2014 11:38:29 -0800 Subject: [Tutor] learning recursion In-Reply-To: References: Message-ID: On Thu, Feb 6, 2014 at 11:28 AM, Denis Heidtmann wrote: >>>> for i in range(4): > ... print fib2(i) > ... > > The above results in an error: Because fib2(0) recurses infinitely, and i's first value is 0. -- Devin From oscar.j.benjamin at gmail.com Thu Feb 6 22:50:14 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 6 Feb 2014 21:50:14 +0000 Subject: [Tutor] Which computer operating system is best for Python In-Reply-To: References: <517E3BA3E9B9FC4D8EC21A1BC1B392DD1A555F29@MD1-EX10.corp.ericksonretirement.com> <20140206021147.GY3799@ando> Message-ID: On 6 February 2014 09:46, Alan Gauld wrote: > On 06/02/14 02:11, Steven D'Aprano wrote: > >> But still complex. And you're limited by the (lack of) stability of >> Windows. > > Unless you are running a server a modern Windows set up is stable enough. > Since windows 7 and 8 the core OS is far better than earlier incarnations. I haven't had much of a chance to use Windows post-XP but even XP was a big improvement over the Win 9x days. I don't particularly think Windows is unstable - provided you don't install loads of rubbish. And that's the big thing: when I get asked to fix someone's Windows machine (e.g. by a family member or friend) the problem is usually viruses/malware and it that sense it is unstable (although perhaps it's better post-XP). > I've only had one BSOD in the last 5 years and I've had at least two kernel > panics on my Linux boxes in that time. But then I use Linux(70%?) more than > Windows(15%?)... My experience is similar and I've probably been doing about 70% Windows (at the office) and 30% Linux. I've seen many more system crashes on Linux than Windows (possible because of the radeon graphics drivers). > If you want to become a pro then sure Linux is great and without doubt the > best development OS around. But for a 13 year old casual user? I doubt it > makes much difference. I use Linux for everything now (even my phone) but I still wouldn't recommend it to someone who had never used it before unless I knew that I could personally help them with it on an ongoing basis. This is what happened with my sister and when she got a new laptop she installed Ubuntu herself and set it up without any help. But this was after I had previously shown her how to do it, carefully explained how it works and showed her whatever tweaks were required to make it usable in a "normal" way. Oscar From cspears2002 at yahoo.com Thu Feb 6 22:49:41 2014 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 6 Feb 2014 13:49:41 -0800 Subject: [Tutor] good django book? Message-ID: Can anyone recommend a good Django book? I have been looking on Amazon, and the books seem to be out of date. Thanks, Chris From davea at davea.name Fri Feb 7 00:06:41 2014 From: davea at davea.name (Dave Angel) Date: Thu, 6 Feb 2014 18:06:41 -0500 (EST) Subject: [Tutor] learning recursion References: Message-ID: Denis Heidtmann Wrote in message: > > Please post in text, not html. Your posting program loses the indentation in the text view, which is what most people see. Code: def fib2(n): if n==1: return 1 elif n==2: return 1 else: return fib2(n-2) +fib2(n-1) That code doesn't do anything reasonable for zero or negative values. Probably what you want is if n==0: return 0 elif n <3: return 1 else: It would probably be technically correct to raise an exception for n < 1, because fibonacci didn't define earlier values. But it's apparently acceptable to return zero for the zero case. -- DaveA From lelanislabber at yahoo.co.uk Fri Feb 7 12:29:40 2014 From: lelanislabber at yahoo.co.uk (Lelani Slabber) Date: Thu, 7 Feb 2014 12:29:40 +0100 Subject: [Tutor] Lelani Slabber Message-ID: <3fL0bB1B1Xz7LjS@mail.python.org> An HTML attachment was scrubbed... URL: From dpalao.python at gmail.com Fri Feb 7 15:04:13 2014 From: dpalao.python at gmail.com (David Palao) Date: Fri, 7 Feb 2014 15:04:13 +0100 Subject: [Tutor] good django book? In-Reply-To: References: Message-ID: Hi, The Django community has plenty of good information in the web. I would go there and have a look. At least this is what I did, precisely for the same reason that you mention. Best, David 2014-02-06 Christopher Spears : > Can anyone recommend a good Django book? I have been looking on Amazon, and the books seem to be out of date. > > Thanks, > Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From someukdeveloper at gmail.com Fri Feb 7 23:43:55 2014 From: someukdeveloper at gmail.com (Some Developer) Date: Fri, 07 Feb 2014 22:43:55 +0000 Subject: [Tutor] good django book? In-Reply-To: References: Message-ID: <52F561AB.5060208@googlemail.com> On 06/02/2014 21:49, Christopher Spears wrote: > Can anyone recommend a good Django book? I have been looking on Amazon, and the books seem to be out of date. > > Thanks, > Chris If you really want a book then get this one: http://www.amazon.co.uk/Two-Scoops-Django-Best-Practices/dp/098146730X/ref=sr_1_2?s=books&ie=UTF8&qid=1391812973&sr=1-2&keywords=two+scoops+of+django I have the previous version and it really is very good. The newer version looks even better. I'm thinking about getting it myself. From akleider at sonic.net Sat Feb 8 02:02:33 2014 From: akleider at sonic.net (Alex Kleider) Date: Fri, 07 Feb 2014 17:02:33 -0800 Subject: [Tutor] =?utf-8?q?good_django_book=3F?= In-Reply-To: <52F561AB.5060208@googlemail.com> References: <52F561AB.5060208@googlemail.com> Message-ID: On 2014-02-07 14:43, Some Developer wrote: > On 06/02/2014 21:49, Christopher Spears wrote: >> Can anyone recommend a good Django book? I have been looking on >> Amazon, and the books seem to be out of date. >> >> Thanks, >> Chris > If you really want a book then get this one: > > http://www.amazon.co.uk/Two-Scoops-Django-Best-Practices/dp/098146730X/ref=sr_1_2?s=books&ie=UTF8&qid=1391812973&sr=1-2&keywords=two+scoops+of+django > > I have the previous version and it really is very good. The newer > version looks even better. I'm thinking about getting it myself. It might be worth pointing out that the version of django that comes with Debian/Ubuntu is Version: 1.3.1-4ubuntu1 so worrying about having a text that describes 1.6 vs 1.4 may not be all that important. Comments? From eryksun at gmail.com Sat Feb 8 04:43:55 2014 From: eryksun at gmail.com (eryksun) Date: Fri, 7 Feb 2014 22:43:55 -0500 Subject: [Tutor] good django book? In-Reply-To: References: <52F561AB.5060208@googlemail.com> Message-ID: On Fri, Feb 7, 2014 at 8:02 PM, Alex Kleider wrote: > It might be worth pointing out that the version of django that comes with > Debian/Ubuntu is > Version: 1.3.1-4ubuntu1 > so worrying about having a text that describes 1.6 vs 1.4 may not be all > that important. > > Comments? Debian stable currently supports Django 1.4. Ubuntu's upcoming LTS release supports Django 1.6. Debian python-django Squeeze (oldstable): 1.2.3-3 Wheezy (stable): 1.4.5-1 Jessie (testing): 1.6.1-2 Oldstable gets security updates for a year, so Squeeze EOL should be in May 2014. Jessie enters feature freeze in Nov 2014, but there's no release date as of yet. Ubuntu python-django (EOL) Lucid: 1.1.1-2 (2015-04) Precise: 1.3.1-4 (2017-04) Quantal: 1.4.1-2 (2014-04) Saucy: 1.5.4-1 (2014-07) Trusty: 1.6.1-2 Trusty will be released in Apr 2014. From rakeshsharma14 at hotmail.com Sat Feb 8 05:51:10 2014 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Sat, 8 Feb 2014 10:21:10 +0530 Subject: [Tutor] good django book? In-Reply-To: References: , <52F561AB.5060208@googlemail.com> , Message-ID: Hi Alex, >From my experience, though in windows env, there is considerable amount of difference in the way both the version gets implemented thanks,rakesh > From: eryksun at gmail.com > Date: Fri, 7 Feb 2014 22:43:55 -0500 > To: akleider at sonic.net > CC: tutor at python.org > Subject: Re: [Tutor] good django book? > > On Fri, Feb 7, 2014 at 8:02 PM, Alex Kleider wrote: > > It might be worth pointing out that the version of django that comes with > > Debian/Ubuntu is > > Version: 1.3.1-4ubuntu1 > > so worrying about having a text that describes 1.6 vs 1.4 may not be all > > that important. > > > > Comments? > > Debian stable currently supports Django 1.4. Ubuntu's upcoming LTS > release supports Django 1.6. > > Debian python-django > Squeeze (oldstable): 1.2.3-3 > Wheezy (stable): 1.4.5-1 > Jessie (testing): 1.6.1-2 > > Oldstable gets security updates for a year, so Squeeze EOL should be > in May 2014. Jessie enters feature freeze in Nov 2014, but there's no > release date as of yet. > > Ubuntu python-django (EOL) > Lucid: 1.1.1-2 (2015-04) > Precise: 1.3.1-4 (2017-04) > Quantal: 1.4.1-2 (2014-04) > Saucy: 1.5.4-1 (2014-07) > Trusty: 1.6.1-2 > > Trusty will be released in Apr 2014. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From rakeshsharma14 at hotmail.com Sat Feb 8 06:05:03 2014 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Sat, 8 Feb 2014 10:35:03 +0530 Subject: [Tutor] learning recursion In-Reply-To: References: , Message-ID: Hi Shouldn't your code be like this def fib(n): if n==0: return 0 else: return n + fib(n-1) this works >>> for i in range(4): print fib(i) 0136>>> > To: tutor at python.org > From: davea at davea.name > Date: Thu, 6 Feb 2014 18:06:41 -0500 > Subject: Re: [Tutor] learning recursion > > Denis Heidtmann Wrote in message: > > > > > Please post in text, not html. Your posting program loses the > indentation in the text view, which is what most people > see. > > Code: > def fib2(n): > if n==1: > return 1 > > elif n==2: > return 1 > else: > return fib2(n-2) +fib2(n-1) > > That code doesn't do anything reasonable for zero or negative > values. Probably what you want is > > if n==0: > return 0 > elif n <3: > return 1 > else: > > It would probably be technically correct to raise an exception for > n < 1, because fibonacci didn't define earlier values. But it's > apparently acceptable to return zero for the zero > case. > > > > > -- > DaveA > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.heidtmann at gmail.com Sat Feb 8 06:40:49 2014 From: denis.heidtmann at gmail.com (Denis Heidtmann) Date: Fri, 7 Feb 2014 21:40:49 -0800 Subject: [Tutor] learning recursion In-Reply-To: References: Message-ID: On Fri, Feb 7, 2014 at 9:05 PM, rakesh sharma wrote: > Hi > > Shouldn't your code be like this > > def fib(n): > if n==0: > return 0 > else: > return n + fib(n-1) > > this works > >>>> for i in range(4): > print fib(i) > > 0 > 1 > 3 > 6 >>>> interesting, but the Fibonacci sequence is 1,1,2,3,5,8,13,... -Denis H. From dyoo at hashcollision.org Sat Feb 8 09:20:19 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 8 Feb 2014 00:20:19 -0800 Subject: [Tutor] learning recursion In-Reply-To: References: Message-ID: On Fri, Feb 7, 2014 at 9:05 PM, rakesh sharma wrote: > Hi > > Shouldn't your code be like this > > def fib(n): > if n==0: > return 0 > else: > return n + fib(n-1) Hi Rakesh, Unfortunately, no, because this computes a slightly different function: the triangular numbers! :P That is, your function above is an implementation for the sum: 0 + 1 + 2 + ... + n It's also known as a "Gauss sum". ################################################################## [Tangent ahead. Skip if you're not interested.] As a very tangent note, it's good for us programmers to know about this function, because it shows up in some common places. For example, it occurs when we try to figure out approximately how long it takes to concatenate a bunch of strings in a naive way. Imagine the following artificial scenario: ############################# long_string = "" for n in range(1000): long_string = long_string + "X" ############################# where we're building up a large string with repeated concatenations. Does this look bad to you? It should! The string concatenation operation takes time that's proportional to the size of the string we're building up. If we do the above, with _repeated_ string concatenation, going through the whole loop will cost, altogether, something on the order of: 0 + 1 + 2 + ... + 1000 elementary operations, representing the first, second, ... and thousandth time through that loop. And if you know your Gauss sum, this sum can be quickly computed without having to do each individual addition: 0 + 1 + 2 + ... + 1000 = (1000 * 1001) / 2 = 500500 which is a fairly big number. In general: 0 + 1 + 2 + ... + n = n * (n+1) / 2 In practice, this means for us programmers that if we're going to build up a large string in parts, doing repeated string concatenation is not the right approach as it means we're doing things in quadratic time. It's better to build up a list of strings, and then do the concatenation all at once, avoiding the repeating rebuilding of a larger and larger string: ############################# long_string_chunks = [] for n in range(1000): long_string_chunks.append("X") long_string = "".join(long_string_chunks) ############################# where the "".join(...) part, having been implemented well, and knowing all the long_string_chunk elements, can do the string concatenation in one single, efficient pass. From rakeshsharma14 at hotmail.com Sat Feb 8 10:58:52 2014 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Sat, 8 Feb 2014 15:28:52 +0530 Subject: [Tutor] learning recursion In-Reply-To: References: , , Message-ID: Hi I guess I need to revisit my maths lessons.Thank you for correcting me. thanks,rakesh > From: dyoo at hashcollision.org > Date: Sat, 8 Feb 2014 00:20:19 -0800 > Subject: Re: [Tutor] learning recursion > To: rakeshsharma14 at hotmail.com > CC: davea at davea.name; tutor at python.org > > On Fri, Feb 7, 2014 at 9:05 PM, rakesh sharma > wrote: > > Hi > > > > Shouldn't your code be like this > > > > def fib(n): > > if n==0: > > return 0 > > else: > > return n + fib(n-1) > > > Hi Rakesh, > > Unfortunately, no, because this computes a slightly different > function: the triangular numbers! :P > > > That is, your function above is an implementation for the sum: > > 0 + 1 + 2 + ... + n > > It's also known as a "Gauss sum". > > > ################################################################## > > [Tangent ahead. Skip if you're not interested.] > > As a very tangent note, it's good for us programmers to know about > this function, because it shows up in some common places. For > example, it occurs when we try to figure out approximately how long it > takes to concatenate a bunch of strings in a naive way. > > Imagine the following artificial scenario: > > ############################# > long_string = "" > for n in range(1000): > long_string = long_string + "X" > ############################# > > where we're building up a large string with repeated concatenations. > > Does this look bad to you? It should! The string concatenation > operation takes time that's proportional to the size of the string > we're building up. If we do the above, with _repeated_ string > concatenation, going through the whole loop will cost, altogether, > something on the order of: > > 0 + 1 + 2 + ... + 1000 > > elementary operations, representing the first, second, ... and > thousandth time through that loop. > > And if you know your Gauss sum, this sum can be quickly computed > without having to do each individual addition: > > 0 + 1 + 2 + ... + 1000 > = (1000 * 1001) / 2 > = 500500 > > which is a fairly big number. > > In general: > > 0 + 1 + 2 + ... + n > = n * (n+1) / 2 > > In practice, this means for us programmers that if we're going to > build up a large string in parts, doing repeated string concatenation > is not the right approach as it means we're doing things in quadratic > time. It's better to build up a list of strings, and then do the > concatenation all at once, avoiding the repeating rebuilding of a > larger and larger string: > > ############################# > long_string_chunks = [] > for n in range(1000): > long_string_chunks.append("X") > long_string = "".join(long_string_chunks) > ############################# > > where the "".join(...) part, having been implemented well, and knowing > all the long_string_chunk elements, can do the string concatenation in > one single, efficient pass. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rakeshsharma14 at hotmail.com Sat Feb 8 11:06:20 2014 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Sat, 8 Feb 2014 15:36:20 +0530 Subject: [Tutor] learning recursion In-Reply-To: References: , , , Message-ID: I got my definition wrong the code should be more like this def fib(n): if n==0: return elif n==1: return 1 elif n==2: return 1 else: return fib(n-2) + fib(n-1) thanks,rakesh > Date: Fri, 7 Feb 2014 21:40:49 -0800 > Subject: Re: [Tutor] learning recursion > From: denis.heidtmann at gmail.com > To: rakeshsharma14 at hotmail.com > CC: davea at davea.name; tutor at python.org > > On Fri, Feb 7, 2014 at 9:05 PM, rakesh sharma > wrote: > > Hi > > > > Shouldn't your code be like this > > > > def fib(n): > > if n==0: > > return 0 > > else: > > return n + fib(n-1) > > > > this works > > > >>>> for i in range(4): > > print fib(i) > > > > 0 > > 1 > > 3 > > 6 > >>>> > > interesting, but the Fibonacci sequence is 1,1,2,3,5,8,13,... > > -Denis H. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Feb 8 23:22:25 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Feb 2014 22:22:25 +0000 Subject: [Tutor] learning recursion In-Reply-To: References: , , , Message-ID: On 08/02/2014 10:06, rakesh sharma wrote: Please do not top post on this list. > I got my definition wrong > > the code should be more like this > > def fib(n): > if n==0: > return What does the above line return? As others have already said what happens if n is negative? > elif n==1: > return 1 > elif n==2: > return 1 > else: > return fib(n-2) + fib(n-1) > > thanks, > rakesh > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From nsivaram.net at gmail.com Sun Feb 9 07:33:43 2014 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sun, 09 Feb 2014 12:03:43 +0530 Subject: [Tutor] catching the row that raises IntegrityError in sqlite Message-ID: <87ha88dcc8.fsf@gmail.com> I've written this code that seems to work and I'd like to know how to get the record that causes the abort. Apparently 'executemany' doesn't support lastrow? And if it doesn't, any suggestions? --8<---------------cut here---------------start------------->8--- def table_load(datafile,name,conn,dbh): print "processing table ",name conn.execute("PRAGMA table_info("+ name +")") #parse the resultset to get the col name cols= [ x[1] for x in conn.fetchall()] cv= ("?" * len(cols)) with open(datafile,'r') as fin: dr = csv.reader(fin, delimiter='|') to_db = [tuple(i) for i in dr] print "Records read in: ", len(to_db) cl=','.join(cols) cvv=','.join(cv) try: sql = "insert into %s (%s) values(%s)" %(name, cl, cvv) conn.executemany(sql, to_db) dbh.commit() except sq.IntegrityError: print('Record already exists') # but which record??? dbh.rollback() finally: sql= "select count(*) from %s;" %(name) (row_cnt,) = conn.execute(sql).fetchone() print "rows inserted ", row_cnt --8<---------------cut here---------------end--------------->8--- And do tell if I'm doing this try catch bits correctly please. sivaram -- From steve at pearwood.info Sun Feb 9 10:39:24 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 9 Feb 2014 20:39:24 +1100 Subject: [Tutor] catching the row that raises IntegrityError in sqlite In-Reply-To: <87ha88dcc8.fsf@gmail.com> References: <87ha88dcc8.fsf@gmail.com> Message-ID: <20140209093924.GL3799@ando> On Sun, Feb 09, 2014 at 12:03:43PM +0530, Sivaram Neelakantan wrote: > try: > sql = "insert into %s (%s) values(%s)" %(name, cl, cvv) > conn.executemany(sql, to_db) > dbh.commit() > except sq.IntegrityError: > print('Record already exists') # but which record??? > dbh.rollback() When you get an error, and don't know how to interpret it, the first thing to do is to look at the exception and see what it says. try: # as above except sq.IntegrityError as exception: print(exception) dbh.rollback() Often (although not always) the exception will give you details on what went wrong. That should always be the first thing to look at. -- Steven From __peter__ at web.de Sun Feb 9 11:20:55 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Feb 2014 11:20:55 +0100 Subject: [Tutor] catching the row that raises IntegrityError in sqlite References: <87ha88dcc8.fsf@gmail.com> Message-ID: Sivaram Neelakantan wrote: > > I've written this code that seems to work and I'd like to know how to get > the record that causes the abort. Apparently 'executemany' doesn't > support lastrow? And if it doesn't, any suggestions? > > --8<---------------cut here---------------start------------->8--- > def table_load(datafile,name,conn,dbh): > print "processing table ",name > conn.execute("PRAGMA table_info("+ name +")") > #parse the resultset to get the col name > cols= [ x[1] for x in conn.fetchall()] > cv= ("?" * len(cols)) > with open(datafile,'r') as fin: > dr = csv.reader(fin, delimiter='|') > to_db = [tuple(i) for i in dr] > print "Records read in: ", len(to_db) > cl=','.join(cols) > cvv=','.join(cv) > try: > sql = "insert into %s (%s) values(%s)" %(name, cl, cvv) > conn.executemany(sql, to_db) > dbh.commit() > except sq.IntegrityError: > print('Record already exists') # but which record??? > dbh.rollback() > finally: > sql= "select count(*) from %s;" %(name) > (row_cnt,) = conn.execute(sql).fetchone() > print "rows inserted ", row_cnt > --8<---------------cut here---------------end--------------->8--- > > And do tell if I'm doing this try catch bits correctly please. If nobody here comes up with a good way to find the offending record you could ask in a mailing list/newsgroup dedicated to sqlite (Please report back here if you do). If there is no "official" way you might try the workaround shown below. The idea here is to wrap the iterable of records to be inserted in the Iter class which keeps track of the last accessed row. $ cat sqlite_integrity2.py import sqlite3 import csv import sys class Iter(object): def __init__(self, items): self.items = items def __iter__(self): for item in self.items: self.last = item yield item def table_load(datafile, name, cursor, db): print("processing table {}".format(name)) cursor.execute("PRAGMA table_info("+ name +")") column_names = [descr[1] for descr in cursor.fetchall()] with open(datafile,'r') as fin: records = csv.reader(fin, delimiter='|') records = Iter(records) sql = "insert or rollback into {name} ({columns}) values({qmarks})".format( name=name, columns=", ".join(column_names), qmarks=", ".join("?"*len(column_names))) try: cursor.executemany(sql, records) except sqlite3.IntegrityError as err: print("{}: {}".format(err, records.last)) finally: sql= "select count(*) from {};".format(name) [row_count] = cursor.execute(sql).fetchone() print("rows inserted: {}".format(row_count)) if __name__ == "__main__": filename = sys.argv[1] db = sqlite3.connect(":memory:") cursor = db.cursor() cursor.execute("create table demo (name unique, value);") table_load(filename, "demo", cursor, db) $ cat records_ records_conflict.csv records_no_conflict.csv $ cat records_conflict.csv alpha|1 beta|2 gamma|3 alpha|4 delta|5 $ python sqlite_integrity2.py records_conflict.csv processing table demo column name is not unique: ['alpha', '4'] rows inserted: 0 $ cat records_no_conflict.csv alpha|1 beta|2 gamma|3 delta|4 $ python sqlite_integrity2.py records_no_conflict.csv processing table demo rows inserted: 4 While this approach seems to work at the moment it will of course break should sqlite decide one day to read records ahead before performing the integrity test. Therefore I recommend the more conservative road to loop over the records explicitly: for row in records: try: cursor.execute(sql, row) except ... ... From russel at winder.org.uk Sun Feb 9 14:22:22 2014 From: russel at winder.org.uk (Russel Winder) Date: Sun, 09 Feb 2014 13:22:22 +0000 Subject: [Tutor] learning recursion In-Reply-To: References: Message-ID: <1391952142.13785.56.camel@anglides.winder.org.uk> On Thu, 2014-02-06 at 18:06 -0500, Dave Angel wrote: [?] > > Code: > def fib2(n): > if n==1: > return 1 > > elif n==2: > return 1 > else: > return fib2(n-2) +fib2(n-1) [?] I suggest it also be pointed out that this form is algorithmically dreadful. Having transformed the maths to this first cut code, we then need to consider it as code and shift to a tail recursive form, iterative form, or at the very least memoize the function. Leaving students of programming (in any current language) with the idea that this is a good final solution is, I believe, a disservice. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder From nsivaram.net at gmail.com Sun Feb 9 14:23:41 2014 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sun, 09 Feb 2014 18:53:41 +0530 Subject: [Tutor] catching the row that raises IntegrityError in sqlite References: <87ha88dcc8.fsf@gmail.com> <20140209093924.GL3799@ando> Message-ID: <87d2iwctcy.fsf@gmail.com> On Sun, Feb 09 2014,Steven D'Aprano wrote: > On Sun, Feb 09, 2014 at 12:03:43PM +0530, Sivaram Neelakantan wrote: > [snipped 8 lines] > When you get an error, and don't know how to interpret it, the first > thing to do is to look at the exception and see what it says. > > try: > # as above > except sq.IntegrityError as exception: > print(exception) > dbh.rollback() I'm sorry I wasn't clear but I do know what kind of error is going to come; I was trying to make a more helpful exit by printing out the offending row/row #. When I tried your suggestion above, I get 'UNIQUE constraint failed: users.id ' which I know but not the offending row or row number. sivaram -- From russel at winder.org.uk Sun Feb 9 14:28:20 2014 From: russel at winder.org.uk (Russel Winder) Date: Sun, 09 Feb 2014 13:28:20 +0000 Subject: [Tutor] Python as Teaching Language In-Reply-To: <20140120104135.GB2178@gmail.com> References: <20140120104135.GB2178@gmail.com> Message-ID: <1391952500.13785.60.camel@anglides.winder.org.uk> On Mon, 2014-01-20 at 10:41 +0000, Oscar Benjamin wrote: [?] > f = open('myfile.txt') > for line in f: > print(line.upper()) > f.close() I suggest we even see this as not good code due to the possibility of I/O exceptions: with open('myfile.txt') as f: for line in f: print(line.upper()) should, I argue, be the canonical idiom in modern Python. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder From oscar.j.benjamin at gmail.com Sun Feb 9 14:36:12 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 9 Feb 2014 13:36:12 +0000 Subject: [Tutor] Python as Teaching Language In-Reply-To: <1391952500.13785.60.camel@anglides.winder.org.uk> References: <20140120104135.GB2178@gmail.com> <1391952500.13785.60.camel@anglides.winder.org.uk> Message-ID: On 9 February 2014 13:28, Russel Winder wrote: > On Mon, 2014-01-20 at 10:41 +0000, Oscar Benjamin wrote: > [...] >> f = open('myfile.txt') >> for line in f: >> print(line.upper()) >> f.close() > > I suggest we even see this as not good code due to the possibility of > I/O exceptions: > > with open('myfile.txt') as f: > for line in f: > print(line.upper()) > > should, I argue, be the canonical idiom in modern Python. I agree entirely, but what you've overlooked is that my examples are carefully targeted at a particular part of a tutorial-based class. We're talking about iteration so this is quite early in the course. At this stage I want my students to understand that closing a file is an explicit action that needs to occur. Later in the course I will teach exception handling and explain that the above should be rewritten as f = open('myfile.txt') try: for line in f: print(line.upper()) finally: f.close() Shortly after that we will look at using (but not creating) context managers and I'll explain that file objects are also context managers. Oscar From nsivaram.net at gmail.com Sun Feb 9 15:19:01 2014 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sun, 09 Feb 2014 19:49:01 +0530 Subject: [Tutor] catching the row that raises IntegrityError in sqlite References: <87ha88dcc8.fsf@gmail.com> Message-ID: <874n48cqsq.fsf@gmail.com> On Sun, Feb 09 2014,Peter Otten wrote: > Sivaram Neelakantan wrote: > [snipped 32 lines] > > If nobody here comes up with a good way to find the offending record you > could ask in a mailing list/newsgroup dedicated to sqlite (Please report > back here if you do). If there is no "official" way you might try the > workaround shown below. > > The idea here is to wrap the iterable of records to be inserted in the Iter > class which keeps track of the last accessed row. > [snipped 62 lines] Thanks for the code, appreciate the help. > While this approach seems to work at the moment it will of course break > should sqlite decide one day to read records ahead before performing the > integrity test. Therefore I recommend the more conservative road to loop > over the records explicitly: > > for row in records: > try: > cursor.execute(sql, row) > except ... > ... Right, i'll go with this then [snipped 7 lines] sivaram -- From davea at davea.name Sun Feb 9 19:56:46 2014 From: davea at davea.name (Dave Angel) Date: Sun, 9 Feb 2014 13:56:46 -0500 (EST) Subject: [Tutor] learning recursion References: <1391952142.13785.56.camel@anglides.winder.org.uk> Message-ID: Russel Winder Wrote in message: > On Thu, 2014-02-06 at 18:06 -0500, Dave Angel wrote: > [???] >> >> Code: >> def fib2(n): >> if n==1: >> return 1 >> >> elif n==2: >> return 1 >> else: >> return fib2(n-2) +fib2(n-1) > [???] > > I suggest it also be pointed out that this form is algorithmically > dreadful. Having transformed the maths to this first cut code, we then > need to consider it as code and shift to a tail recursive form, > iterative form, or at the very least memoize the function. Leaving > students of programming (in any current language) with the idea that > this is a good final solution is, I believe, a disservice. > > Not as bad as attributing that code to me. -- DaveA From altrius13 at gmail.com Sun Feb 9 23:37:06 2014 From: altrius13 at gmail.com (Altrius) Date: Sun, 9 Feb 2014 16:37:06 -0600 Subject: [Tutor] Recommendation For A Complete Noob Message-ID: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> Hi, I?m completely new to programming in general and everything I have read so far has pointed me to Python. I?ll put this another way: All I know is that a programming language is a medium for a human to tell a computer what to do. After that I?m kinda lost. I was just hoping to get some input as to where I might start. I?m not completely computer illiterate but you can reply to me as if I am. What should I work on learning first. I?m good at doing my own research and teaching myself but I need to know what I?m researching and where to start. Any advice would be VERY much appreciated. Thanks, Altrius From joel.goldstick at gmail.com Sun Feb 9 23:48:12 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 9 Feb 2014 17:48:12 -0500 Subject: [Tutor] Recommendation For A Complete Noob In-Reply-To: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> Message-ID: On Feb 9, 2014 5:37 PM, "Altrius" wrote: > > Hi, > > I?m completely new to programming in general and everything I have read so far has pointed me to Python. I?ll put this another way: All I know is that a programming language is a medium for a human to tell a computer what to do. After that I?m kinda lost. I was just hoping to get some input as to where I might start. I?m not completely computer illiterate but you can reply to me as if I am. What should I work on learning first. I?m good at doing my own research and teaching myself but I need to know what I?m researching and where to start. Any advice would be VERY much appreciated. > > Thanks, > Altrius > > > Start at python.org. do the rituals. Follow the links. Dive in _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Feb 10 00:19:04 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 9 Feb 2014 15:19:04 -0800 Subject: [Tutor] Recommendation For A Complete Noob In-Reply-To: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> Message-ID: Hi Altrius, Welcome! You might start by looking at some of the learning resources at python.org. As a beginner, you'll probably want to look at: https://wiki.python.org/moin/BeginnersGuide Feel free to ask questions here. Good luck! -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Mon Feb 10 00:22:03 2014 From: eryksun at gmail.com (eryksun) Date: Sun, 9 Feb 2014 18:22:03 -0500 Subject: [Tutor] catching the row that raises IntegrityError in sqlite In-Reply-To: References: <87ha88dcc8.fsf@gmail.com> Message-ID: On Sun, Feb 9, 2014 at 5:20 AM, Peter Otten <__peter__ at web.de> wrote: > > The idea here is to wrap the iterable of records to be inserted in the Iter > class which keeps track of the last accessed row. You could also use a parameters iterator, e.g. `it = iter(to_db)`. Then for an IntegrityError, list the remaining records and use that to infer the last record. This way uses an efficient built-in list iterator instead of a generator. http://docs.python.org/3/library/sqlite3#sqlite3.Cursor.executemany I can't see why the implementation would change in future versions. Internally it gets an iterator and executes the statement for each record in a loop. I don't see any point to reading ahead. From davea at davea.name Mon Feb 10 00:45:00 2014 From: davea at davea.name (Dave Angel) Date: Sun, 9 Feb 2014 18:45:00 -0500 (EST) Subject: [Tutor] Recommendation For A Complete Noob References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> Message-ID: Altrius Wrote in message: > Hi, > > I???m completely new to programming in general and everything I have read so far has pointed me to Python. I???ll put this another way: All I know is that a programming language is a medium for a human to tell a computer what to do. After that I???m kinda lost. I was just hoping to get some input as to where I might start. I???m not completely computer illiterate but you can reply to me as if I am. What should I work on learning first. I???m good at doing my own research and teaching myself but I need to know what I???m researching and where to start. Any advice would be VERY much appreciated. > Welcome to the mailing list. Learning python can be as slow as you like or as fast as you're able. As you get stuck on concepts, you can post questions, and some volunteers usually will have suggestions to help. But you'll have to learn to provide your constraints with your question. In this case you are probably constrained by whatever operating system you run. For now I'll assume Windows. When I was using Windows, I found the Active Python version a good choice. It includes most things you don't know you want yet. www.activestate.com/activepython/downloads then pick 3.3.2.0 and Windows installer. Download and run the msi file. As for docs, see python.org. That has links to the whole site. Start with the left side, Quick Links-3.3. Be sure you're following the approximate version you downloaded. There was a fairly big break between 2.7 and 3.x On the documentation page, you'll see many parts. The tutorial is the next logical step, but be aware all these other parts exist. Eventually you'll need the library reference, to expand on some concept the tutorial brought up. The language reference will be very tough going at your stage. There are other tutorials out there, including Alan Gauld ' s http:// www.alan-g.me.uk/ But if you get a book or tutorial, make sure the version matches approximately, as above. > > -- DaveA From denis.spir at gmail.com Mon Feb 10 00:56:33 2014 From: denis.spir at gmail.com (spir) Date: Mon, 10 Feb 2014 00:56:33 +0100 Subject: [Tutor] Recommendation For A Complete Noob In-Reply-To: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> Message-ID: <52F815B1.1000802@gmail.com> On 02/09/2014 11:37 PM, Altrius wrote: > Hi, > > I?m completely new to programming in general and everything I have read so far has pointed me to Python. I?ll put this another way: All I know is that a programming language is a medium for a human to tell a computer what to do. After that I?m kinda lost. I was just hoping to get some input as to where I might start. I?m not completely computer illiterate but you can reply to me as if I am. What should I work on learning first. I?m good at doing my own research and teaching myself but I need to know what I?m researching and where to start. Any advice would be VERY much appreciated. Welcome! I would recommend "Learning to Program" (using Python) by Alan Gauld, a member of this mailing list: http://www.alan-g.me.uk/ Unlike most tutorials, this one is *really* for beginners (not for people only new to python, not supposed to be for beginners but by an author unable to imagine beginner questions). There are versions for Python 2 & 3. Since you start, use version 3, as it is the future of the language (however, it is not easier, rather somewhat more abstract, but you won't meet the new difficulties before quite a long time). A few recommandations (very subjective): * Take your time. * Follow your drive and intuitions. * Have fun, don't force. Also: ask questions and/or search about the numerous enigmas you will step on. d From alan.gauld at btinternet.com Mon Feb 10 01:00:37 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Feb 2014 00:00:37 +0000 Subject: [Tutor] Recommendation For A Complete Noob In-Reply-To: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> Message-ID: On 09/02/14 22:37, Altrius wrote: > I?m completely new to programming in general and everything I have read so far has pointed me to Python. Its still one of the best choices for learning. Other languages are easier to get started with but then you can't go any further. Python lets you keep on growing. > All I know is that a programming language is a medium for a human > to tell a computer what to do. That's exactly right and a great start. I'll blow my own trumpet here and suggest you at least read the first section of my tutor (see below) because it explains the concepts which most tutorials don't cover. The official python docs will likely be unintelligible to you at this stage but by the time you have gone through one of the non-programmers tuts found here: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers you should be able to run through the official tutorial and read the other documentation. Don;t be afraid to sample several tuts. Different people learn better with different styles. Find one that suits you. If you get stuck, don't give up but ask questions here. The more specific the question the more specific the answer. But don't be shy of asking for explanations of concepts and buzzwords/jargon too. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Feb 10 01:17:20 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Feb 2014 00:17:20 +0000 Subject: [Tutor] Python as Teaching Language In-Reply-To: References: <20140120104135.GB2178@gmail.com> <1391952500.13785.60.camel@anglides.winder.org.uk> Message-ID: On 09/02/14 13:36, Oscar Benjamin wrote: > We're talking about iteration so this is quite early in the course. At > this stage I want my students to understand that closing a file is an > explicit action that needs to occur. Later in the course I will teach > exception handling and explain that the above should be rewritten as These are good points. And in my tutorial I deliberately don't teach many of the "standard" Python idioms because I'm trying to teach programming rather than Python. So if python has an insanely great way to do stuff but virtually no other language has it I will ignore it. (Or more likely mention it as an aside/footnote.) What's interesting (to me) is that I'm currently working on a new project aimed at beginners who have progressed beyond the first steps but are not confident in putting together a bigger program. That is allowing me to address many of the idiomatic aspects of Python that my first book didn't permit. It means that although there is some overlap in coverage the style and content are quite different. Context and target make a big difference in what and how you teach. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From abhinavrajkp at gmail.com Sun Feb 9 12:38:02 2014 From: abhinavrajkp at gmail.com (abhinav raj kp nirmallur) Date: Sun, 9 Feb 2014 17:08:02 +0530 Subject: [Tutor] catching the row that raises IntegrityError in sqlite In-Reply-To: References: <87ha88dcc8.fsf@gmail.com> Message-ID: Sir I don't know nothing about programming but I have a great intrest in it so that now a days I began to study python, many of my friends and teachers suggest me it. But still I have no tutor, can you please suggest me to study python using book or any good websit. Thanks. Abhinav Raj >From Calicut, Kerala, India. I'm currently studying in plus one science. On 2/9/14, Peter Otten <__peter__ at web.de> wrote: > Sivaram Neelakantan wrote: > >> >> I've written this code that seems to work and I'd like to know how to get >> the record that causes the abort. Apparently 'executemany' doesn't >> support lastrow? And if it doesn't, any suggestions? >> >> --8<---------------cut here---------------start------------->8--- >> def table_load(datafile,name,conn,dbh): >> print "processing table ",name >> conn.execute("PRAGMA table_info("+ name +")") >> #parse the resultset to get the col name >> cols= [ x[1] for x in conn.fetchall()] >> cv= ("?" * len(cols)) >> with open(datafile,'r') as fin: >> dr = csv.reader(fin, delimiter='|') >> to_db = [tuple(i) for i in dr] >> print "Records read in: ", len(to_db) >> cl=','.join(cols) >> cvv=','.join(cv) >> try: >> sql = "insert into %s (%s) values(%s)" %(name, cl, cvv) >> conn.executemany(sql, to_db) >> dbh.commit() >> except sq.IntegrityError: >> print('Record already exists') # but which record??? >> dbh.rollback() >> finally: >> sql= "select count(*) from %s;" %(name) >> (row_cnt,) = conn.execute(sql).fetchone() >> print "rows inserted ", row_cnt >> --8<---------------cut here---------------end--------------->8--- >> >> And do tell if I'm doing this try catch bits correctly please. > > If nobody here comes up with a good way to find the offending record you > could ask in a mailing list/newsgroup dedicated to sqlite (Please report > back here if you do). If there is no "official" way you might try the > workaround shown below. > > The idea here is to wrap the iterable of records to be inserted in the Iter > > class which keeps track of the last accessed row. > > $ cat sqlite_integrity2.py > import sqlite3 > import csv > import sys > > class Iter(object): > def __init__(self, items): > self.items = items > def __iter__(self): > for item in self.items: > self.last = item > yield item > > def table_load(datafile, name, cursor, db): > print("processing table {}".format(name)) > cursor.execute("PRAGMA table_info("+ name +")") > column_names = [descr[1] for descr in cursor.fetchall()] > > with open(datafile,'r') as fin: > records = csv.reader(fin, delimiter='|') > records = Iter(records) > sql = "insert or rollback into {name} ({columns}) > values({qmarks})".format( > name=name, > columns=", ".join(column_names), > qmarks=", ".join("?"*len(column_names))) > try: > cursor.executemany(sql, records) > except sqlite3.IntegrityError as err: > print("{}: {}".format(err, records.last)) > finally: > sql= "select count(*) from {};".format(name) > [row_count] = cursor.execute(sql).fetchone() > print("rows inserted: {}".format(row_count)) > > if __name__ == "__main__": > filename = sys.argv[1] > db = sqlite3.connect(":memory:") > cursor = db.cursor() > cursor.execute("create table demo (name unique, value);") > table_load(filename, "demo", cursor, db) > $ cat records_ > records_conflict.csv records_no_conflict.csv > $ cat records_conflict.csv > alpha|1 > beta|2 > gamma|3 > alpha|4 > delta|5 > $ python sqlite_integrity2.py records_conflict.csv > processing table demo > column name is not unique: ['alpha', '4'] > rows inserted: 0 > $ cat records_no_conflict.csv > alpha|1 > beta|2 > gamma|3 > delta|4 > $ python sqlite_integrity2.py records_no_conflict.csv > processing table demo > rows inserted: 4 > > While this approach seems to work at the moment it will of course break > should sqlite decide one day to read records ahead before performing the > integrity test. Therefore I recommend the more conservative road to loop > over the records explicitly: > > for row in records: > try: > cursor.execute(sql, row) > except ... > ... > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From jimmy_ya77 at yahoo.com Sat Feb 8 06:55:58 2014 From: jimmy_ya77 at yahoo.com (james campbell) Date: Fri, 7 Feb 2014 21:55:58 -0800 (PST) Subject: [Tutor] Python .decode issue Message-ID: <1391838958.95990.YahooMailNeo@web125506.mail.ne1.yahoo.com> I have been currently trying to get a small piece of code to work, but keep getting an error: header_bin = header_hex.decode('hex') AttributeError: 'str' object has no attribute 'decode' The source of this code is from: https://en.bitcoin.it/wiki/Block_hashing_algorithm ?Here is the the code: ? >>> import hashlib >>> header_hex = ("01000000" + "81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000" + "e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b" + "c7f5d74d" + "f2b9441a" + "42a14695") >>> header_bin = header_hex.decode('hex') >>> hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest() >>> hash.encode('hex_codec') '1dbd981fe6985776b644b173a4d0385ddc1aa2a829688d1e0000000000000000' >>> hash[::-1].encode('hex_codec') '00000000000000001e8d6829a8a21adc5d38d0a473b144b6765798e61f98bd1d' I get the above error when I input this line by line into Win7 IDLE 3.3.3. Hopefully somebody can point me in the right direction. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From matbioinfo at gmail.com Fri Feb 7 17:14:12 2014 From: matbioinfo at gmail.com (rahmad akbar) Date: Fri, 7 Feb 2014 17:14:12 +0100 Subject: [Tutor] second if Message-ID: he guys, i am trying to understand this code: i understand the first if statement (if line.startswith..) in read_fasta function but couldnt understand the next one(if index >=...). thanks in advance!! import sys #class declaration with both attributes we need class Fasta: def __init__(self, name, sequence): #this will store the sequence name self.name = name #this will store the sequence itself self.sequence = sequence #this function will receive the list with the file #contents, create instances of the Fasta class as #it scans the list, putting the sequence name on the #first attribute and the sequence itself on the second #attribute def read_fasta(file): #we declare an empty list that will store all #Fasta class instances generated items = [] index = 0 for line in file: #we check to see if the line starts with a > sign if line.startswith(">"): #if so and our counter is large than 1 #we add the created class instance to our list #a counter larger than 1 means we are reading #from sequences 2 and above if index >= 1: items.append(aninstance) index+=1 #we add the line contents to a string name = line[:-1] #and initialize the string to store the sequence seq = '' #this creates a class instance and we add the attributes #which are the strings name and seq aninstance = Fasta(name, seq) else: #the line does not start with > so it has to be #a sequence line, so we increment the string and #add it to the created instance seq += line[:-1] aninstance = Fasta(name, seq) #the loop before reads everything but the penultimate #sequence is added at the end, so we need to add it #after the loop ends items.append(aninstance) #a list with all read sequences is returned return items fastafile = open(sys.argv[1], 'r').readlines() mysequences = read_fasta(fastafile) print mysequences for i in mysequences: print i.name -- many thanks mat -------------- next part -------------- An HTML attachment was scrubbed... URL: From r.cziva.1 at research.gla.ac.uk Fri Feb 7 17:07:58 2014 From: r.cziva.1 at research.gla.ac.uk (Richard Cziva) Date: Fri, 7 Feb 2014 16:07:58 +0000 Subject: [Tutor] trace / profile every function with inputs Message-ID: <03D3ED9B42D15745B78A7F12F3DD7D39D38D827D53@CMS05.campus.gla.ac.uk> Hi All, I am struggling with a "simple" problem: I would like to print out every function that is being executed while my Python program is running. I can not modify the Python programs that I would like to profile. Let me give an example. A program contains a function and a call like this: def foo(x): y = math.cos(x) time.sleep(y+1) return x * 50 print foo(100) I would like to retrieve an execution trace that shows me each function called (with the value or hash of the function arguments). According to the example, I am looking for a way to extract something similar: foo(100) math.cos(100) time.sleep(0.87) Things I have tried with only partial success: - trace: couldn't get the function names in some cases - profile / cProfile: no information about the arguments Could you suggest me a way of doing this? Thanks, Richard From r.cziva.1 at research.gla.ac.uk Sat Feb 8 17:36:13 2014 From: r.cziva.1 at research.gla.ac.uk (Richard Cziva) Date: Sat, 8 Feb 2014 16:36:13 +0000 Subject: [Tutor] trace / profile function calls with inputs Message-ID: <52F65CFD.9080607@research.gla.ac.uk> Hi All, I am trying to print out every function that is being called while my Python program is running (own functions and library calls too). I can not modify the Python programs I am trying to profile. Let me give an example. A program contains a function like this: def foo(x): y = math.cos(x) z = 1 + 1 time.sleep(y+1) return x * 50 And it calls the function: print foo(100) I would like to retrieve an execution trace that shows me each function called with the value or hash of its arguments. According to the example, I am looking for a technique to extract something similar: foo(100) math.cos(100) time.sleep(0.87) Things I have tried with only partial success: - trace module - profile module / cProfile Could you suggest me a way of doing this? Thanks, Richard From alan.gauld at btinternet.com Mon Feb 10 02:04:12 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Feb 2014 01:04:12 +0000 Subject: [Tutor] trace / profile function calls with inputs In-Reply-To: <52F65CFD.9080607@research.gla.ac.uk> References: <52F65CFD.9080607@research.gla.ac.uk> Message-ID: On 08/02/14 16:36, Richard Cziva wrote: > I am trying to print out every function that is being called while my > Python program is running (own functions and library calls too). I can > not modify the Python programs I am trying to profile. I don't know of any way of doing this exactly as you want it. > def foo(x): > y = math.cos(x) > z = 1 + 1 > time.sleep(y+1) > return x * 50 > > And it calls the function: > > print foo(100) > > I would like to retrieve an execution trace that shows me each function > called with the value or hash of its arguments. According to the > example, I am looking for a technique to extract something similar: > > foo(100) > math.cos(100) > time.sleep(0.87) You say functions. But what about the functions used to implement operators like +,-,*,+= etc? For classes they are methods. Should it list all of those calls to? If so what about the operations on built in classes? The x * 50 above for example? What about operations on literals? z = 1+1 for instance? If you know all the functions you could use a debugger and just watch all functions and log the output. How are you planning on analyzing the results? Sometimes a more intelligent and considered approach is better than just logging everything... HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Mon Feb 10 03:46:39 2014 From: davea at davea.name (Dave Angel) Date: Sun, 9 Feb 2014 21:46:39 -0500 (EST) Subject: [Tutor] second if References: Message-ID: rahmad akbar Wrote in message: Between invisible colors and a tiny font, your message is totally incomprehensible to me. This is a text list, please post in text, not html. -- DaveA From davea at davea.name Mon Feb 10 03:55:12 2014 From: davea at davea.name (Dave Angel) Date: Sun, 9 Feb 2014 21:55:12 -0500 (EST) Subject: [Tutor] Python .decode issue References: <1391838958.95990.YahooMailNeo@web125506.mail.ne1.yahoo.com> Message-ID: james campbell Wrote in message: > (Context lost because message was erroneously posted in html) strings cannot be decoded, so there's naturally no such method. Why not post a two line example of what you're trying, and explain what you were expecting it to do. -- DaveA From russel at winder.org.uk Mon Feb 10 11:49:47 2014 From: russel at winder.org.uk (Russel Winder) Date: Mon, 10 Feb 2014 10:49:47 +0000 Subject: [Tutor] learning recursion In-Reply-To: References: <1391952142.13785.56.camel@anglides.winder.org.uk> Message-ID: <1392029387.19013.6.camel@anglides.winder.org.uk> On Sun, 2014-02-09 at 13:56 -0500, Dave Angel wrote: [?] > Not as bad as attributing that code to me. Apologies for that implication, bad editing on my part, I should have retained the link to the author. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder From dpalao.python at gmail.com Mon Feb 10 11:52:45 2014 From: dpalao.python at gmail.com (David Palao) Date: Mon, 10 Feb 2014 11:52:45 +0100 Subject: [Tutor] second if In-Reply-To: References: Message-ID: Also, could you explain better what is your doubt? You don't understand what "index >= 1" means, or why this "if" at this point, or anything else? Best 2014-02-07 17:14 GMT+01:00 rahmad akbar : > he guys, i am trying to understand this code: i understand the first if > statement (if line.startswith..) in read_fasta function but couldnt > understand the next one(if index >=...). thanks in advance!! > > import sys > #class declaration with both attributes we need > class Fasta: > def __init__(self, name, sequence): > #this will store the sequence name > self.name = name > #this will store the sequence itself > self.sequence = sequence > > #this function will receive the list with the file > #contents, create instances of the Fasta class as > #it scans the list, putting the sequence name on the > #first attribute and the sequence itself on the second > #attribute > def read_fasta(file): > #we declare an empty list that will store all > #Fasta class instances generated > items = [] > index = 0 > for line in file: > #we check to see if the line starts with a > sign > if line.startswith(">"): > #if so and our counter is large than 1 > #we add the created class instance to our list > #a counter larger than 1 means we are reading > #from sequences 2 and above > if index >= 1: > items.append(aninstance) > index+=1 > #we add the line contents to a string > name = line[:-1] > #and initialize the string to store the sequence > seq = '' > #this creates a class instance and we add the attributes > #which are the strings name and seq > aninstance = Fasta(name, seq) > else: > #the line does not start with > so it has to be > #a sequence line, so we increment the string and > #add it to the created instance > seq += line[:-1] > aninstance = Fasta(name, seq) > > #the loop before reads everything but the penultimate > #sequence is added at the end, so we need to add it > #after the loop ends > items.append(aninstance) > #a list with all read sequences is returned > return items > > fastafile = open(sys.argv[1], 'r').readlines() > mysequences = read_fasta(fastafile) > > print mysequences > > for i in mysequences: > print i.name > > -- > many thanks > mat > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From russel at winder.org.uk Mon Feb 10 11:55:19 2014 From: russel at winder.org.uk (Russel Winder) Date: Mon, 10 Feb 2014 10:55:19 +0000 Subject: [Tutor] Python as Teaching Language In-Reply-To: References: <20140120104135.GB2178@gmail.com> <1391952500.13785.60.camel@anglides.winder.org.uk> Message-ID: <1392029719.19013.9.camel@anglides.winder.org.uk> On Sun, 2014-02-09 at 13:36 +0000, Oscar Benjamin wrote: [?] > I agree entirely, but what you've overlooked is that my examples are > carefully targeted at a particular part of a tutorial-based class. > We're talking about iteration so this is quite early in the course. At > this stage I want my students to understand that closing a file is an > explicit action that needs to occur. Later in the course I will teach > exception handling and explain that the above should be rewritten as > > f = open('myfile.txt') > try: > for line in f: > print(line.upper()) > finally: > f.close() > > Shortly after that we will look at using (but not creating) context > managers and I'll explain that file objects are also context managers. Works for me. Personally I would ensure I put in forward signposts at the time of covering earlier codes to ensure people realize there is a progression and that the current code is initial not final. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder From russel at winder.org.uk Mon Feb 10 12:00:59 2014 From: russel at winder.org.uk (Russel Winder) Date: Mon, 10 Feb 2014 11:00:59 +0000 Subject: [Tutor] Python as Teaching Language In-Reply-To: References: <20140120104135.GB2178@gmail.com> <1391952500.13785.60.camel@anglides.winder.org.uk> Message-ID: <1392030059.19013.13.camel@anglides.winder.org.uk> On Mon, 2014-02-10 at 00:17 +0000, Alan Gauld wrote: [?] > And in my tutorial I deliberately don't teach many of the "standard" > Python idioms because I'm trying to teach programming rather than > Python. So if python has an insanely great way to do stuff but virtually > no other language has it I will ignore it. (Or more > likely mention it as an aside/footnote.) In the case of file handling and the with statement, indeed any resource management, it is a standard idiom across languages so well worth covering in Python: RAII in C++, ARM in Java, etc. > What's interesting (to me) is that I'm currently working on a new > project aimed at beginners who have progressed beyond the first > steps but are not confident in putting together a bigger program. > That is allowing me to address many of the idiomatic aspects > of Python that my first book didn't permit. It means that although there > is some overlap in coverage the style and content are quite different. > > Context and target make a big difference in what and how you teach. Definitely. Good luck with the new project. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder From alan.gauld at btinternet.com Mon Feb 10 12:24:39 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Feb 2014 11:24:39 +0000 Subject: [Tutor] second if In-Reply-To: References: Message-ID: On 07/02/14 16:14, rahmad akbar wrote: > he guys, i am trying to understand this code: i understand the first if > statement (if line.startswith..) in read_fasta function but couldnt > understand the next one(if index >=...). thanks in advance!! I'm not sure what you don't understand about it. But so far as I can see its effect is to miss out the first line in the file that starts with '>' The logic appears to be, in pseudo code: read the file line buy line if line starts with > if not the first time add instance to the collection add one to index create an instance. It has to miss the first one because an instance doesn't exist yet. It seems odd and I'd probably have done it this way: read the file line buy line if line starts with > create an instance. add instance to the collection But there may be reasons why the author didn't do that. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Mon Feb 10 12:24:58 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Feb 2014 12:24:58 +0100 Subject: [Tutor] second if References: Message-ID: rahmad akbar wrote: > he guys, i am trying to understand this code: i understand the first if > statement (if line.startswith..) in read_fasta function but couldnt > understand the next one(if index >=...). thanks in advance!! Every time a line starts with a ">" sign the current Fasta instance is stored in the items list and new Fasta instance is created. But the first time a line starts with ">" there is not yet a "current" instance which can be appended to the list. The index variable keeps track of the number of Fasta instances created, so the first time around the index is 0 and the if index >= 1: items.append(aninstance) suite is not executed. By the way, can you figure out what happens if the file contains no lines at all? How would you need to change the script to avoid raising an exception in this case? > import sys > #class declaration with both attributes we need > class Fasta: > def __init__(self, name, sequence): > #this will store the sequence name > self.name = name > #this will store the sequence itself > self.sequence = sequence > > #this function will receive the list with the file > #contents, create instances of the Fasta class as > #it scans the list, putting the sequence name on the > #first attribute and the sequence itself on the second > #attribute > def read_fasta(file): > #we declare an empty list that will store all > #Fasta class instances generated > items = [] > index = 0 > for line in file: > #we check to see if the line starts with a > sign > if line.startswith(">"): > #if so and our counter is large than 1 > #we add the created class instance to our list > #a counter larger than 1 means we are reading > #from sequences 2 and above > if index >= 1: > items.append(aninstance) > index+=1 > #we add the line contents to a string > name = line[:-1] > #and initialize the string to store the sequence > seq = '' > #this creates a class instance and we add the attributes > #which are the strings name and seq > aninstance = Fasta(name, seq) > else: > #the line does not start with > so it has to be > #a sequence line, so we increment the string and > #add it to the created instance > seq += line[:-1] > aninstance = Fasta(name, seq) > > #the loop before reads everything but the penultimate > #sequence is added at the end, so we need to add it > #after the loop ends > items.append(aninstance) > #a list with all read sequences is returned > return items > > fastafile = open(sys.argv[1], 'r').readlines() > mysequences = read_fasta(fastafile) > > print mysequences > > for i in mysequences: > print i.name > From alan.gauld at btinternet.com Mon Feb 10 12:54:36 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 10 Feb 2014 11:54:36 +0000 (GMT) Subject: [Tutor] trace / profile function calls with inputs In-Reply-To: <52F8B8B4.7060601@research.gla.ac.uk> References: <52F65CFD.9080607@research.gla.ac.uk> <52F8B8B4.7060601@research.gla.ac.uk> Message-ID: <1392033276.16712.YahooMailNeo@web186003.mail.ir2.yahoo.com> CCing tutor list. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos >________________________________ > >> You say functions. But what about the functions used to implement >> operators like +,-,*,+= etc? >I don't need them now. > >> to? If so what about the operations on built in classes? >> The x * 50 above for example? What about operations on literals? >> z = 1+1 for instance? >Neither them this time. > >> How are you planning on analyzing the results? Sometimes a more >> intelligent and considered approach is better than just logging >> everything... > >I need all the functions called by the program in a simple txt file. I >would like to create a statistic of the common functions called (yes, >identified by only name and input) between different software products. > > >Ah. That's what I feared. If you were trying to understand how some? system functioned or trying to improve performance in some way a? more considered subset would be feasible. But if you want to collect? stats for their own sake then you have no option.? And I don't really know how to help you. Maybe one of our python internals gurus can help there... Alan g. -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at gmail.com Mon Feb 10 13:09:37 2014 From: denis.spir at gmail.com (spir) Date: Mon, 10 Feb 2014 13:09:37 +0100 Subject: [Tutor] trace / profile function calls with inputs In-Reply-To: <52F65CFD.9080607@research.gla.ac.uk> References: <52F65CFD.9080607@research.gla.ac.uk> Message-ID: <52F8C181.6080304@gmail.com> On 02/08/2014 05:36 PM, Richard Cziva wrote: > Hi All, > > I am trying to print out every function that is being called while my Python > program is running (own functions and library calls too). I can not modify the > Python programs I am trying to profile. > > Let me give an example. A program contains a function like this: > > def foo(x): > y = math.cos(x) > z = 1 + 1 > time.sleep(y+1) > return x * 50 > > And it calls the function: > > print foo(100) > > I would like to retrieve an execution trace that shows me each function called > with the value or hash of its arguments. According to the example, I am looking > for a technique to extract something similar: > > foo(100) > math.cos(100) > time.sleep(0.87) > > Things I have tried with only partial success: > - trace module > - profile module / cProfile > > Could you suggest me a way of doing this? You need to wrap every function call in a tracing wrapper function that (1) does what you want (2) calls the wrapped function. Something like this: def trace (func, *args): # trace func_name = func.__name__ arg_strings = (str(arg) for arg in args) arg_string = ", ".join(arg_strings) print("%s(%s)" % (func_name, arg_string)) # call result = func(*args) if result: return result def f (x,y): return (x+y) / 2 def g (x,y): print((x+y) / 2) trace(g, 3, 7) z = trace(f, 3, 7) print(z) ==> g(3, 7) 5.0 f(3, 7) 5.0 As you see, there is a subtility about the distinction between functions that _do_ something (actions, in fact) and function that compute a product (function properly speaking). But actually you could ignore because the former implicitely return none. You cannot always have the same call expression as in the actual calling code: you always have the _values_. For example: a = 9 y = 7 trace(f(math.sqrt(a), y) will show: f(3, 7) Python does not let you know _the code_. You would need a "homoiconic" language like Lisp for that: a language in which "code is data" (data of the language types). In python, code is opaque, it is plain raw data (bit string) without any language type & value. So, I guess we cannot do much better than the above, but I may be wrong. The right way to do this would in fact be using so-called "decorators". But the example above shows the principle (and the code you'd have to put in a decorator). d From matbioinfo at gmail.com Mon Feb 10 16:32:19 2014 From: matbioinfo at gmail.com (rahmad akbar) Date: Mon, 10 Feb 2014 16:32:19 +0100 Subject: [Tutor] if >= 0 Message-ID: hey again guys, i am trying to understand these statements, if i do it like this, it will only print the 'print locus' part for element in in_file: if element.find('LOCUS'): locus += element elif element.find('ACCESSION'): accession += element elif element.find('ORGANISM'): organism += element print locus print accession print organism once i add >= 0 to each if conditions like so, the entire loop works and prints the 3 items for element in in_file: if element.find('LOCUS') >= 0: locus += element elif element.find('ACCESSION') >= 0: accession += element elif element.find('ORGANISM') >= 0: organism += element print locus print accession print organism why without '>= 0' the loop doesnt works? -- many thanks mat -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Feb 10 16:59:47 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Feb 2014 16:59:47 +0100 Subject: [Tutor] if >= 0 References: Message-ID: rahmad akbar wrote: > hey again guys, i am trying to understand these statements, > > if i do it like this, it will only print the 'print locus' part > > for element in in_file: > if element.find('LOCUS'): > locus += element > elif element.find('ACCESSION'): > accession += element > elif element.find('ORGANISM'): > organism += element > > print locus > print accession > print organism > > > once i add >= 0 to each if conditions like so, the entire loop works and > prints the 3 items > > for element in in_file: > if element.find('LOCUS') >= 0: > locus += element > elif element.find('ACCESSION') >= 0: > accession += element > elif element.find('ORGANISM') >= 0: > organism += element > > print locus > print accession > print organism > > why without '>= 0' the loop doesnt works? element.find(some_string) returns the position of some_string in element, or -1 if some_string doesn't occur in element. All integers but 0 are true in a boolean context, i. e. if -1: print -1 # printed if 0: print 0 # NOT printed if 123456789: print 123456789 # printed So unlike what you might expect if element.find(some_string): # WRONG! print "found" else: print "not found" will print "not found" if element starts with some_string and "found" for everything else. As you are not interested in the actual position of the potential substring you should rewrite your code to if "LOCUS" in element: locus += element elif "ACCESSION" in element: accession += element elif "ORGANISM" in element: organism += element which unlike the str.find() method works as expected. From joel.goldstick at gmail.com Mon Feb 10 17:00:15 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 10 Feb 2014 11:00:15 -0500 Subject: [Tutor] if >= 0 In-Reply-To: References: Message-ID: On Feb 10, 2014 10:33 AM, "rahmad akbar" wrote: > > hey again guys, i am trying to understand these statements, > > if i do it like this, it will only print the 'print locus' part > > for element in in_file: # do this print element > if element.find('LOCUS'): > locus += element > elif element.find('ACCESSION'): > accession += element > elif element.find('ORGANISM'): > organism += element > > print locus > print accession > print organism > > > once i add >= 0 to each if conditions like so, the entire loop works and prints the 3 items > > for element in in_file: > if element.find('LOCUS') >= 0: > locus += element > elif element.find('ACCESSION') >= 0: > accession += element > elif element.find('ORGANISM') >= 0: > organism += element > > print locus > print accession > print organism > > why without '>= 0' the loop doesnt works? > -- > many thanks > mat > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dpalao.python at gmail.com Mon Feb 10 17:11:08 2014 From: dpalao.python at gmail.com (David Palao) Date: Mon, 10 Feb 2014 17:11:08 +0100 Subject: [Tutor] second if In-Reply-To: References: Message-ID: I guess the replies by Alan and Peter precisely answer to your question? Best 2014-02-10 12:46 GMT+01:00 rahmad akbar : > David, > > thanks for your reply. i cant figure out why the if at that point and what > is the 'if' try to accompolish > > > On Mon, Feb 10, 2014 at 11:52 AM, David Palao > wrote: >> >> Also, could you explain better what is your doubt? You don't >> understand what "index >= 1" means, or why this "if" at this point, or >> anything else? >> >> Best >> >> 2014-02-07 17:14 GMT+01:00 rahmad akbar : >> > he guys, i am trying to understand this code: i understand the first if >> > statement (if line.startswith..) in read_fasta function but couldnt >> > understand the next one(if index >=...). thanks in advance!! >> > >> > import sys >> > #class declaration with both attributes we need >> > class Fasta: >> > def __init__(self, name, sequence): >> > #this will store the sequence name >> > self.name = name >> > #this will store the sequence itself >> > self.sequence = sequence >> > >> > #this function will receive the list with the file >> > #contents, create instances of the Fasta class as >> > #it scans the list, putting the sequence name on the >> > #first attribute and the sequence itself on the second >> > #attribute >> > def read_fasta(file): >> > #we declare an empty list that will store all >> > #Fasta class instances generated >> > items = [] >> > index = 0 >> > for line in file: >> > #we check to see if the line starts with a > sign >> > if line.startswith(">"): >> > #if so and our counter is large than 1 >> > #we add the created class instance to our list >> > #a counter larger than 1 means we are reading >> > #from sequences 2 and above >> > if index >= 1: >> > items.append(aninstance) >> > index+=1 >> > #we add the line contents to a string >> > name = line[:-1] >> > #and initialize the string to store the sequence >> > seq = '' >> > #this creates a class instance and we add the attributes >> > #which are the strings name and seq >> > aninstance = Fasta(name, seq) >> > else: >> > #the line does not start with > so it has to be >> > #a sequence line, so we increment the string and >> > #add it to the created instance >> > seq += line[:-1] >> > aninstance = Fasta(name, seq) >> > >> > #the loop before reads everything but the penultimate >> > #sequence is added at the end, so we need to add it >> > #after the loop ends >> > items.append(aninstance) >> > #a list with all read sequences is returned >> > return items >> > >> > fastafile = open(sys.argv[1], 'r').readlines() >> > mysequences = read_fasta(fastafile) >> > >> > print mysequences >> > >> > for i in mysequences: >> > print i.name >> > >> > -- >> > many thanks >> > mat >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> > https://mail.python.org/mailman/listinfo/tutor >> > > > > > > -- > many thanks > mat From alan.gauld at btinternet.com Mon Feb 10 17:25:48 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Feb 2014 16:25:48 +0000 Subject: [Tutor] if >= 0 In-Reply-To: References: Message-ID: On 10/02/14 15:32, rahmad akbar wrote: > hey again guys, i am trying to understand these statements, > > if i do it like this, it will only print the 'print locus' part > > for element in in_file: > if element.find('LOCUS'): > locus += element The only time this is not executed is if LOCUS is at the very start of the line. In *every* other case this will be executed. Even if LOCUS is not in the element. > elif element.find('ACCESSION'): > accession += element > elif element.find('ORGANISM'): > organism += element > > print locus > print accession > print organism I assume by not printing you mean the other two print statements don't print anything visible? Or are you actually getting an error message? Without seeing how accession and organism are defined its hard to know why you are not seeing anything. The print statements are not inside the loop so should always (all three) print something,even if the something is an empty string. > once i add >= 0 to each if conditions like so, the entire loop works and > prints the 3 items > for element in in_file: > if element.find('LOCUS') >= 0: > locus += element This should always be executed unless LOCUS happens to be at the start of the line *or missing*. The greater than zero test eliminates the casers where LOCUS does not exist, in these cases it will move onto the next elif clause. Presumably thats why you now get 3 values printed. But that assumes you initialised the variables to empty strings at the start? > elif element.find('ACCESSION') >= 0: > accession += element > elif element.find('ORGANISM') >= 0: > organism += element > > print locus > print accession > print organism > > why without '>= 0' the loop doesnt works? Can you show us some output? I don't really understand what you mean by "doesn't work". Do you get any error messages? Or is it just the lack of print outputs (that really have nothing to do with the loop part)? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From pierre.dagenais at ncf.ca Mon Feb 10 23:00:25 2014 From: pierre.dagenais at ncf.ca (Pierre Dagenais) Date: Mon, 10 Feb 2014 17:00:25 -0500 Subject: [Tutor] Recommendation For A Complete Noob In-Reply-To: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> Message-ID: <52F94BF9.6050502@ncf.ca> On 14-02-09 05:37 PM, Altrius wrote: > Hi, > > I?m completely new to programming in general and everything I have read so far has pointed me to Python. I?ll put this another way: All I know is that a programming language is a medium for a human to tell a computer what to do. After that I?m kinda lost. I was just hoping to get some input as to where I might start. I'd start with Guido van Rossum http://www.network-theory.co.uk/docs/pytut/ for a gentle introduction. Then I'd follow up with http://swaroopch.com http://www.diveintopython3.net/ by Mark Pilgrim and Learning to program by Alan Gauld http://www.freenetpages.co.uk/hp/alan.gauld/ You may also want to check http://www.linuxlinks.com/article/20121228122317781/20oftheBestFreePythonBooks-Part1.html for more advice. Welcome and good luck, PierreD. From pierre.dagenais at ncf.ca Tue Feb 11 00:16:35 2014 From: pierre.dagenais at ncf.ca (Pierre Dagenais) Date: Mon, 10 Feb 2014 18:16:35 -0500 Subject: [Tutor] Python .decode issue In-Reply-To: <1391838958.95990.YahooMailNeo@web125506.mail.ne1.yahoo.com> References: <1391838958.95990.YahooMailNeo@web125506.mail.ne1.yahoo.com> Message-ID: <52F95DD3.3070003@ncf.ca> On 14-02-08 12:55 AM, james campbell wrote: > header_bin = header_hex.decode('hex') > AttributeError: 'str' object has no attribute 'decode' What I understand is that you are trying to decode 'hex', which is a string. The interpreter is telling you that strings cannot be decoded. I do not know header_hex.decode(), but I suspect it's expecting an hex number, check it out. PierreD. From breamoreboy at yahoo.co.uk Tue Feb 11 00:33:37 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Feb 2014 23:33:37 +0000 Subject: [Tutor] Python .decode issue In-Reply-To: <52F95DD3.3070003@ncf.ca> References: <1391838958.95990.YahooMailNeo@web125506.mail.ne1.yahoo.com> <52F95DD3.3070003@ncf.ca> Message-ID: On 10/02/2014 23:16, Pierre Dagenais wrote: > > On 14-02-08 12:55 AM, james campbell wrote: >> header_bin = header_hex.decode('hex') >> AttributeError: 'str' object has no attribute 'decode' > > What I understand is that you are trying to decode 'hex', which is a > string. The interpreter is telling you that strings cannot be decoded. > I do not know header_hex.decode(), but I suspect it's expecting an hex > number, check it out. > > PierreD. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > "AttributeError: 'str' object has no attribute 'decode'" is saying that header_hex has no attribute decode, the string 'hex' doesn't enter into the equation. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From carroll at tjc.com Tue Feb 11 00:49:22 2014 From: carroll at tjc.com (Terry Carroll) Date: Mon, 10 Feb 2014 15:49:22 -0800 (PST) Subject: [Tutor] Your confirmation is required to leave the Tutor mailing list In-Reply-To: References: Message-ID: On Mon, 10 Feb 2014, tutor-confirm+c3fa710640d780363ebaec9fd955eefa81f1b46c at python.org wrote: > Mailing list removal confirmation notice for mailing list Tutor > > We have received a request for the removal of your email address, > "carroll at tjc.com" from the tutor at python.org mailing list. To confirm > that you want to be removed from this mailing list, simply reply to > this message, keeping the Subject: header intact. Or visit this web > page: > > https://mail.python.org/mailman/confirm/tutor/c3fa710640d780363ebaec9fd955eefa81f1b46c > > > Or include the following line -- and only the following line -- in a > message to tutor-request at python.org: > > confirm c3fa710640d780363ebaec9fd955eefa81f1b46c > > Note that simply sending a `reply' to this message should work from > most mail readers, since that usually leaves the Subject: line in the > right form (additional "Re:" text in the Subject: is okay). > > If you do not wish to be removed from this list, please simply > disregard this message. If you think you are being maliciously > removed from the list, or have any other questions, send them to > tutor-owner at python.org. > From alan.gauld at btinternet.com Tue Feb 11 00:58:28 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 10 Feb 2014 23:58:28 +0000 (GMT) Subject: [Tutor] if >= 0 In-Reply-To: References: Message-ID: <1392076708.10442.YahooMailNeo@web186002.mail.ir2.yahoo.com> CCing Tutor list. ? here are the entire code? > > >import sys >in_file = open(sys.argv[1], 'r').readlines() >locus = '' >accession = '' >organism = '' > >OK, as suspected you initialise these to empty strings so they almost certainly? are being printed they just don't contain anything. Its easilyy proved by making? the initial value something visible like a dash '-'... say for element in in_file: > >? if ?element.find(LOCUS'): >? ? locus += element > > >The only time this is not executed is if LOCUS is at the > >very start of the line. In *every* other case this will >be executed. Even if LOCUS is not in the element. > > > >why is that?Because the Python 'if' test treats any number other than zero as True. And the string find() method returns the index at which the string is? found or -1. So the only time you get zero(False) is if the string starts? on the first character. If the string is missing you get a -1 which is? considered True When you added the >=0 you eliminated the cases where find()? returned -1, ie where the string was not found and so you checked? the other search cases. --? Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos -------------- next part -------------- An HTML attachment was scrubbed... URL: From rakeshsharma14 at hotmail.com Tue Feb 11 02:21:49 2014 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Tue, 11 Feb 2014 06:51:49 +0530 Subject: [Tutor] trace / profile every function with inputs In-Reply-To: <03D3ED9B42D15745B78A7F12F3DD7D39D38D827D53@CMS05.campus.gla.ac.uk> References: <03D3ED9B42D15745B78A7F12F3DD7D39D38D827D53@CMS05.campus.gla.ac.uk> Message-ID: Hi, Have tried inspect module in python.See this code def foo(): print inspect.stack()[0][3] >>> foo()foo>>> this shall meet your purpose I believe thanks,rakesh > From: r.cziva.1 at research.gla.ac.uk > To: tutor at python.org > Date: Fri, 7 Feb 2014 16:07:58 +0000 > Subject: [Tutor] trace / profile every function with inputs > > Hi All, > > I am struggling with a "simple" problem: I would like to print out every function that is being executed while my Python program is running. I can not modify the Python programs that I would like to profile. > > Let me give an example. A program contains a function and a call like this: > > def foo(x): > y = math.cos(x) > time.sleep(y+1) > return x * 50 > > print foo(100) > > I would like to retrieve an execution trace that shows me each function called (with the value or hash of the function arguments). According to the example, I am looking for a way to extract something similar: > > foo(100) > math.cos(100) > time.sleep(0.87) > > Things I have tried with only partial success: > - trace: couldn't get the function names in some cases > - profile / cProfile: no information about the arguments > > Could you suggest me a way of doing this? > > Thanks, > Richard > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Tue Feb 11 04:59:31 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 10 Feb 2014 19:59:31 -0800 Subject: [Tutor] second if In-Reply-To: References: Message-ID: By the way, if you are trying to write your own FASTA parser, please reconsider. A good FASTA parser has been written by the folks at BioPython.org. Use that one unless you really know what you're doing. See: http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec12 for example usage. If you are using your own home-grown FASTA parser, consider switching to the biopython one. (As Lincoln Stein of Bioperl fame has observed, reimplementing a FASTA parser should not be a rite of passage. Reference: the talk "Bioinformatics: Building a Nation from a Land of City States", mentioned in http://www.oreillynet.com/pub/a/network/2002/01/29/bioday2.html. Sadly, the audio to his keynote speech does not appear to be on Dr. Dobbs Technetcast anymore, as that web site appears to have fallen on hard times.) From dyoo at hashcollision.org Tue Feb 11 05:25:52 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 10 Feb 2014 20:25:52 -0800 Subject: [Tutor] Learning about programming Message-ID: On Sun, Feb 9, 2014 at 3:38 AM, abhinav raj kp nirmallur wrote: > Sir I don't know nothing about programming but I have a great intrest > in it so that now a days I began to study python, many of my friends > and teachers suggest me it. But still I have no tutor, can you please > suggest me to study python using book or any good websit. Hi Abhinav, I am changing the subject line. In the future, please use appropriate subject lines for fresh questions. Doing so helps others on the list to know if they are interested in your question. You have said: "Still I have no tutor". You are very mistaken. You have the folks on this mailing list. We will be happy to help. We do not work for free, of course. You have to try to ask good questions. But do so, and you will have people falling out of the aisles here who will be overjoyed to serve. We all know what it's like to start as a beginner. You've asked where you can find good resources. Do you have access to the following web page? https://wiki.python.org/moin/BeginnersGuide That page has links to tutorials that may be helpful for you. You should be able to get started by picking one of them, and reading and practicing them. If you have trouble with them, come back here and ask questions about the difficulty. Folks here will be happy to help. Finally, take a few minutes and read through: http://www.catb.org/~esr/faqs/smart-questions.html That document might be a little obnoxious at first, but it provides some guidelines for asking questions to a particular and strange group of humanity, namely computer programmers. I recommend this because, as a beginner, you might not know about certain expectations that these weird programmers have. If you try to meet those cultural expectations, you'll almost certainly get better answers in turn from technical forums. Good luck! From __peter__ at web.de Tue Feb 11 09:42:01 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Feb 2014 09:42:01 +0100 Subject: [Tutor] Python .decode issue References: <1391838958.95990.YahooMailNeo@web125506.mail.ne1.yahoo.com> Message-ID: james campbell wrote: > I have been currently trying to get a small piece of code to work, but > keep getting an error: > > header_bin = header_hex.decode('hex') > AttributeError: 'str' object has no attribute 'decode' > > > The source of this code is from: > https://en.bitcoin.it/wiki/Block_hashing_algorithm Here is the the code: > >>> import hashlib >>> header_hex = ("01000000" + > "81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000" + > "e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b" + > "c7f5d74d" + "f2b9441a" + "42a14695") >>> header_bin = > header_hex.decode('hex') >>> hash = > hashlib.sha256(hashlib.sha256(header_bin).digest()).digest() >>> > hash.encode('hex_codec') > '1dbd981fe6985776b644b173a4d0385ddc1aa2a829688d1e0000000000000000' >>> > hash[::-1].encode('hex_codec') > '00000000000000001e8d6829a8a21adc5d38d0a473b144b6765798e61f98bd1d' > > I get the above error when I input this line by line into Win7 IDLE 3.3.3. > Hopefully somebody can point me in the right direction. Thanks. With the move from Python 2 to Python 3 string handling was changed py2 --> py3 ----------------- str --> bytes unicode --> str Also the encode decode methods have changed. bytes.decode() always gives you a str and str.encode() always returns bytes; there are no bytes.encode or str.decode methods. Unfortunately the bytes --> bytes conversion codecs in Python 2 have no convenient analog in Python 3 yet. This will change in Python 3.4, where you can use >>> import codecs >>> codecs.decode(b"ff10", "hex") b'\xff\x10' >>> codecs.encode(b"\xff\x10", "hex") b'ff10' But for now you are stuck with binascii.b2a_hex() etc. Converting the 2x code of your example to 3x gives >>> import hashlib >>> import binascii >>> header_hex = ( ... b"01000000" ... b"81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000" ... b"e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b" ... b"c7f5d74d" ... b"f2b9441a" ... b"42a14695") >>> header_bin = binascii.a2b_hex(header_hex) >>> hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest() >>> binascii.b2a_hex(hash) b'1dbd981fe6985776b644b173a4d0385ddc1aa2a829688d1e0000000000000000' >>> binascii.b2a_hex(hash[::-1]) b'00000000000000001e8d6829a8a21adc5d38d0a473b144b6765798e61f98bd1d' From matbioinfo at gmail.com Tue Feb 11 11:10:06 2014 From: matbioinfo at gmail.com (rahmad akbar) Date: Tue, 11 Feb 2014 11:10:06 +0100 Subject: [Tutor] if >= 0 In-Reply-To: <1392111086.35837.YahooMailNeo@web186004.mail.ir2.yahoo.com> References: <1392076708.10442.YahooMailNeo@web186002.mail.ir2.yahoo.com> <1392111086.35837.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: Alan, roger that and thanks a bunch. now replying with reply all, i am a super noob and thanks for the kind adivce On Tue, Feb 11, 2014 at 10:31 AM, ALAN GAULD wrote: > CCing the list. Please use Reply All when responding. > > > thanks Alan, i understand now zero is False. > > That's right. but... > > > so if one of the 'if' test is false, that 'for' loop is also halted? > > and does not proceed to the next element? > > This bit is wrong. > > > The for loop will continue to completion every time. > > > >>> for element in in_file: > >>> if element.find(LOCUS'): > > >>> locus += element > >>> elif element.find(...) > > What happens is that because the find(LOCUS) is the first test it will > almost > always be true. So the locus += element will be executed on almost every > line > Because that branch of the if construct is executed no other branch is > executed. > > In an if/elif/else structure only one branch ever gets executed in a given > iteration of the for loop. elif stands for "else if" so the test in the > elif statements > only get executed if all the preceding tests fail. So the order of the > tests is > very important. Now in your case the first branch nearly always succeeds > and so the subsequent branches never get executed. > > When you add the >=0 condition you stop the first test from catching > everything. > > So the lines that do not contain LOCUS now get tested for the other values > and as a result update their respective string variables. > > But the for loop continues regardless of which branch is used, it is only > controlled by the number of lines in the file. It does not care what the > code > inside the loop body does (unless it explicitly uses return or break or > continue). > > HTH > > Alan g. > -- many thanks mat -------------- next part -------------- An HTML attachment was scrubbed... URL: From duxbuz at hotmail.com Tue Feb 11 11:18:03 2014 From: duxbuz at hotmail.com (Ian D) Date: Tue, 11 Feb 2014 10:18:03 +0000 Subject: [Tutor] how can I exit a while loop in turtle graphics Message-ID: I am trying to exit a while loop whilst using turtle graphics. I don't seem to have the logic correct at all. I have tried a few different things These might seem a bit illogical to you guys but to me they make some sense, sadly I just don't really grasp these while loops and their usage.(obviously) I am trying to find a way to use a while loop with the turtle graphics import turtle as t import sys def f(): sys.exit() while True: t.fd(1) t.onkey(f, "Up") t.listen() ==== another go ==== import turtle as t import sys def f(): pass while True: t.fd(1) if t.onkey(f, "Up"): sys.exit() t.listen() ==== another go ==== import turtle as t import sys def f(): pass alive = True while alive: t.fd(1) if t.onkey(f, "Up"): alive = False t.listen() From __peter__ at web.de Tue Feb 11 11:41:31 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Feb 2014 11:41:31 +0100 Subject: [Tutor] how can I exit a while loop in turtle graphics References: Message-ID: Ian D wrote: > I am trying to exit a while loop whilst using turtle graphics. > I don't seem to have the logic correct at all. > I have tried a few different things > > These might seem a bit illogical to you guys but to me they make some > sense, sadly > > I just don't really grasp these while loops and their usage.(obviously) > > I am trying to find a way to use a while loop with the turtle graphics The following seems to work: import turtle def quit(): global more more = False turtle.onkey(quit, "Up") turtle.listen() more = True while more: turtle.left(100) turtle.forward(300) From duxbuz at hotmail.com Tue Feb 11 12:06:49 2014 From: duxbuz at hotmail.com (Ian D) Date: Tue, 11 Feb 2014 11:06:49 +0000 Subject: [Tutor] can I make a while loop true again Message-ID: Thanks for the help on the last one. Is it possible to restart a while loop? This doesn't work at all (surprise surprise) import turtle as t def start(): global more more = True def stop(): global more more = False more = True while True: while more: t.onkey(stop, "space") t.onkey(start, "Up") t.fd(1) t.listen() From alan.gauld at btinternet.com Tue Feb 11 12:55:30 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Feb 2014 11:55:30 +0000 Subject: [Tutor] can I make a while loop true again In-Reply-To: References: Message-ID: On 11/02/14 11:06, Ian D wrote: > Is it possible to restart a while loop? Sorry, I'm sure you know what you mean but I'm not clear. What do you mean by "restart a while loop"? Do you mean after you exited it? If so put the loop in a function and call the function again. Do you mean from inside the loop? If so use continue to jump back to the beginning. Do you mean reset a counter of some sort so the loop starts processing from the beginning? Maybe you should be using a for loop? I'm not clear what you want to do. > This doesn't work at all (surprise surprise) I'd expect it to work fine. Whether what it does is what you wanted it to do is a different question. What did you think it might do? What are you trying to do? I think you may want to add a test after the while more loop to reset more. But I'm not sure? while True: while more: # stuff here choice = input('do you want to go again?') if 'y' in choice.lower(): more = True else: break But I'm still not sure if that's really what you want? > import turtle as t > > def start(): > global more > more = True > > def stop(): > global more > more = False > > more = True > > while True: > while more: > t.onkey(stop, "space") > t.onkey(start, "Up") > t.fd(1) > t.listen() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Tue Feb 11 13:03:35 2014 From: davea at davea.name (Dave Angel) Date: Tue, 11 Feb 2014 07:03:35 -0500 (EST) Subject: [Tutor] can I make a while loop true again References: Message-ID: Ian D Wrote in message: > Thanks for the help on the last one. > > Is it possible to restart a while loop? This doesn't work at all (surprise surprise) > > import turtle as t > > def start(): > global more > more = True > > def stop(): > global more > more = False > > more = True > > while True: > while more: > > t.onkey(stop, "space") > t.onkey(start, "Up") > t.fd(1) > t.listen() > Sure. Follow the 'while more' loop with a 'while not more' one, still inside the 'while True' one. While True: while more: .... while not more: .... But you really should move those calls to onkey outside the loop. They are just confusing things there. How many times do you have to set the same event handler? -- DaveA From eryksun at gmail.com Tue Feb 11 13:24:30 2014 From: eryksun at gmail.com (eryksun) Date: Tue, 11 Feb 2014 07:24:30 -0500 Subject: [Tutor] Python .decode issue In-Reply-To: References: <1391838958.95990.YahooMailNeo@web125506.mail.ne1.yahoo.com> Message-ID: On Tue, Feb 11, 2014 at 3:42 AM, Peter Otten <__peter__ at web.de> wrote: > > Unfortunately the bytes --> bytes conversion codecs in Python 2 have no > convenient analog in Python 3 yet. > > This will change in Python 3.4, where you can use > >>>> import codecs >>>> codecs.decode(b"ff10", "hex") > b'\xff\x10' >>>> codecs.encode(b"\xff\x10", "hex") > b'ff10' 3.4 restores the "hex" alias to encodings.aliases.aliases. You can use "hex_codec" in earlier versions. >>> codecs.encode(b"\xff\x10", "hex_codec") b'ff10' >>> codecs.decode(b"ff10", "hex_codec") b'\xff\x10' > But for now you are stuck with binascii.b2a_hex() etc. The alternate names are binascii.hexlify and binascii.unhexlify. >>> binascii.hexlify(b'\xff\x10') # b2a_hex b'ff10' >>> binascii.unhexlify(b'ff10') # a2b_hex b'\xff\x10' From __peter__ at web.de Tue Feb 11 13:49:02 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Feb 2014 13:49:02 +0100 Subject: [Tutor] Python .decode issue References: <1391838958.95990.YahooMailNeo@web125506.mail.ne1.yahoo.com> Message-ID: eryksun wrote: > On Tue, Feb 11, 2014 at 3:42 AM, Peter Otten <__peter__ at web.de> wrote: >> >> Unfortunately the bytes --> bytes conversion codecs in Python 2 have no >> convenient analog in Python 3 yet. >> >> This will change in Python 3.4, where you can use >> >>>>> import codecs >>>>> codecs.decode(b"ff10", "hex") >> b'\xff\x10' >>>>> codecs.encode(b"\xff\x10", "hex") >> b'ff10' > > 3.4 restores the "hex" alias to encodings.aliases.aliases. You can use > "hex_codec" in earlier versions. > > >>> codecs.encode(b"\xff\x10", "hex_codec") > b'ff10' > >>> codecs.decode(b"ff10", "hex_codec") > b'\xff\x10' Thanks for the correction. >> But for now you are stuck with binascii.b2a_hex() etc. > > The alternate names are binascii.hexlify and binascii.unhexlify. > > >>> binascii.hexlify(b'\xff\x10') # b2a_hex > b'ff10' > >>> binascii.unhexlify(b'ff10') # a2b_hex > b'\xff\x10' From __peter__ at web.de Tue Feb 11 14:01:47 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Feb 2014 14:01:47 +0100 Subject: [Tutor] can I make a while loop true again References: Message-ID: Ian D wrote: > Thanks for the help on the last one. > > Is it possible to restart a while loop? This doesn't work at all (surprise > surprise) > > import turtle as t > > def start(): > global more > more = True > > def stop(): > global more > more = False > > more = True > > while True: > while more: > > t.onkey(stop, "space") > t.onkey(start, "Up") > t.fd(1) > t.listen() When you want your script to work like a typical GUI application you will soon reach the limits with turtle. turtle tries hard to hide it, but GUIs have an independent loop permanently running listening to user events and small functions to respond these events. To have the turtle start and stop I came up with the following which looks similar to normal GUI code. Instead of the explicit loop there is a function `step_forward` that may or may not reschedule itself depending on the state of the `running` flag. import turtle def step_forward(): if running: turtle.forward(5) # call step_forward() again after 100 milliseconds: turtle.ontimer(step_forward, 100) def start(): global running if not running: running = True step_forward() def turn_left(): turtle.left(10) def turn_right(): turtle.right(10) def stop(): global running running = False running = False turtle.delay(0) turtle.onkey(start, "Up") turtle.onkey(turn_left, "Left") turtle.onkey(turn_right, "Right") turtle.onkey(stop, "space") turtle.listen() turtle.mainloop() As a bonus the turtle changes its direction when you hit the left or right array. From __peter__ at web.de Tue Feb 11 14:12:22 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Feb 2014 14:12:22 +0100 Subject: [Tutor] can I make a while loop true again References: Message-ID: Peter Otten wrote: > As a bonus the turtle changes its direction when you hit the left or right > array. I think "arrow" and my fingers decide they'd rather write "array". I'll start proof-reading of these days... From linux at barrowhillfarm.org.uk Wed Feb 12 00:25:07 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Tue, 11 Feb 2014 23:25:07 +0000 Subject: [Tutor] Recommendation For A Complete Noob In-Reply-To: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> Message-ID: <52FAB153.303@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 09/02/14 22:37, Altrius wrote: > Hi, > > I?m completely new to programming in general and everything I have > read so far has pointed me to Python. I?ll put this another way: > All I know is that a programming language is a medium for a human > to tell a computer what to do. After that I?m kinda lost. I was > just hoping to get some input as to where I might start. I?m not > completely computer illiterate but you can reply to me as if I am. > What should I work on learning first. I?m good at doing my own > research and teaching myself but I need to know what I?m > researching and where to start. Any advice would be VERY much > appreciated. > > Thanks, Altrius > Hi Altrius, I'm also a noob. In addition to all the excellent recommendations already posted, I would suggest setting yourself a task to solve in python. It's far more interesting than working through the examples in most books - the challenge is solving each problem as you come across them. Google is excellent. The task I set myself is to write a script that interrogates the rsyncd.log file every day, to tell me if any new music has been added to my collection by my son. My linux machine is on 24/7. I have had to work out how to open the file, how to tell if it's been altered in the last 24 hours, if so how to extract the lines of interest, and how to slice those lines to get the artist and album names into a list. So far, so good but my output contains duplicates, so my final task is to work out how to get rid of them. You may find me popping up here again in a few days ;-) Good luck. Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 18:00pm up 1 day 22:01, 5 users, load average: 0.17, 0.17, 0.21 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlL6sVAACgkQ0Sr7eZJrmU54NgCeP+v3YJk7LxFBkYraOGUL3p94 h8YAn22UWIHzfnIutkk1yUNeMcPtfkgg =7Jq8 -----END PGP SIGNATURE----- From davea at davea.name Wed Feb 12 01:58:19 2014 From: davea at davea.name (Dave Angel) Date: Tue, 11 Feb 2014 19:58:19 -0500 (EST) Subject: [Tutor] Recommendation For A Complete Noob References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> <52FAB153.303@barrowhillfarm.org.uk> Message-ID: Bob Williams Wrote in message: > to slice those lines to get the artist and album > names into a list. > > So far, so good but my output contains duplicates, so my final task is > to work out how to get rid of them. > Hint: a set will contain only one of each item. So if you have a list of immutable items, the following will eliminate duplicates: newlist = list (set (oldlist)) Sometimes a dict is better, if only part of each item is to be made unique. This assumes that order doesn't matter. If it does, perhaps an ordered dict. -- DaveA From amonroe at columbus.rr.com Wed Feb 12 03:06:39 2014 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 11 Feb 2014 21:06:39 -0500 Subject: [Tutor] Better flow for this? Message-ID: <1469757453.20140211210639@columbus.rr.com> I started on an implementation of a solitaire board game simulating a B52 bombing run ( http://victorypointgames.com/details.php?prodId=119 ). It seems like there ought to be a better way to structure this program flow, but it's escaping me at the moment. (pseudo code) ----- playing=True while playing: #phase 1 - fly every turn, you might die if dead: playing=false break if you make it home intact: playing=false break #phase 2 - stuff shoots at you every turn, you might die if playing: try: for each thing that shoots at you: if dead: raise deaderror #this in particular seems horrible except deaderror: #since you can't nest "break"s playing=false break #phase 3 - may or may not get an event card, with certain cards you might die if playing: #stuff if dead: playing=false break #phase 4 - you drop bombs if you're over a target, you can't die here game over, print score ----- Alan From alan.gauld at btinternet.com Wed Feb 12 03:38:10 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Feb 2014 02:38:10 +0000 Subject: [Tutor] Better flow for this? In-Reply-To: <1469757453.20140211210639@columbus.rr.com> References: <1469757453.20140211210639@columbus.rr.com> Message-ID: On 12/02/14 02:06, R. Alan Monroe wrote: Based on a very quick look, its 2:36am!! > (pseudo code) > ----- > playing=True > while playing: > #phase 1 - fly every turn, you might die > if dead: > playing=false > break > if you make it home intact: > playing=false > break > #phase 2 - stuff shoots at you every turn, you might die > if playing: > try: You don;t need if playing since the false conditions both break. So you don;t need the try either... > for each thing that shoots at you: > if dead: > raise deaderror #this in particular seems horrible > except deaderror: #since you can't nest "break"s > playing=false > break And you don;t need the error, just make playing false and break > #phase 3 - may or may not get an event card, with certain cards you might die > if playing: > #stuff Again no need to check playing, you keep breaking... > if dead: > playing=false > break Not sure if you need this or not... > #phase 4 - you drop bombs if you're over a target, you can't die here > game over, print score > ----- HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From linux at barrowhillfarm.org.uk Wed Feb 12 10:47:09 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Wed, 12 Feb 2014 09:47:09 +0000 Subject: [Tutor] Recommendation For A Complete Noob In-Reply-To: References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> <52FAB153.303@barrowhillfarm.org.uk> Message-ID: <52FB431D.1060301@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 12/02/14 00:58, Dave Angel wrote: > Bob Williams Wrote in message: > > >> to slice those lines to get the artist and album names into a >> list. >> >> So far, so good but my output contains duplicates, so my final >> task is to work out how to get rid of them. >> > > > Hint: a set will contain only one of each item. So if you have a > list of immutable items, the following will eliminate duplicates: > > newlist = list (set (oldlist)) > > Sometimes a dict is better, if only part of each item is to be > made unique. > > This assumes that order doesn't matter. If it does, perhaps an > ordered dict. > Many thanks, Dave. That worked perfectly. Ordering doesn't matter in this case, but I might try it as an exercise. Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 06:00am up 2 days 10:01, 5 users, load average: 0.35, 0.31, 0.21 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlL7QxsACgkQ0Sr7eZJrmU6I+gCffgK34BBSBPQ02ZjAKm/TwlUQ VyoAn1etNjuywwWIa1e2fqx9YlGeXGu9 =NhPX -----END PGP SIGNATURE----- From denis.spir at gmail.com Wed Feb 12 10:51:59 2014 From: denis.spir at gmail.com (spir) Date: Wed, 12 Feb 2014 10:51:59 +0100 Subject: [Tutor] Better flow for this? In-Reply-To: <1469757453.20140211210639@columbus.rr.com> References: <1469757453.20140211210639@columbus.rr.com> Message-ID: <52FB443F.1040809@gmail.com> On 02/12/2014 03:06 AM, R. Alan Monroe wrote: > I started on an implementation of a solitaire board game simulating a > B52 bombing run ( http://victorypointgames.com/details.php?prodId=119 > ). It seems like there ought to be a better way to structure this > program flow, but it's escaping me at the moment. > > (pseudo code) Also explain the logic in plain words. Else, we can only guess. d From denis.spir at gmail.com Wed Feb 12 10:53:20 2014 From: denis.spir at gmail.com (spir) Date: Wed, 12 Feb 2014 10:53:20 +0100 Subject: [Tutor] Better flow for this? In-Reply-To: <52FB443F.1040809@gmail.com> References: <1469757453.20140211210639@columbus.rr.com> <52FB443F.1040809@gmail.com> Message-ID: <52FB4490.4090807@gmail.com> On 02/12/2014 10:51 AM, spir wrote: > On 02/12/2014 03:06 AM, R. Alan Monroe wrote: >> I started on an implementation of a solitaire board game simulating a >> B52 bombing run ( http://victorypointgames.com/details.php?prodId=119 >> ). It seems like there ought to be a better way to structure this >> program flow, but it's escaping me at the moment. >> >> (pseudo code) > > Also explain the logic in plain words. Else, we can only guess. > > d This will also help you and check the design. d From russel at winder.org.uk Wed Feb 12 11:06:23 2014 From: russel at winder.org.uk (Russel Winder) Date: Wed, 12 Feb 2014 10:06:23 +0000 Subject: [Tutor] Recommendation For A Complete Noob In-Reply-To: <52FAB153.303@barrowhillfarm.org.uk> References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> <52FAB153.303@barrowhillfarm.org.uk> Message-ID: <1392199583.8272.30.camel@anglides.winder.org.uk> On Tue, 2014-02-11 at 23:25 +0000, Bob Williams wrote: [?] > I'm also a noob. In addition to all the excellent recommendations > already posted, I would suggest setting yourself a task to solve in > python. It's far more interesting than working through the examples in > most books - the challenge is solving each problem as you come across > them. Google is excellent. Definitely. What you also need is to get feedback on your code from another person. Knowing whether your solution is good, Pythonic, or needs more work, is separate from does it pass its tests and does it do what it should. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder From amonroe at columbus.rr.com Wed Feb 12 15:37:56 2014 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 12 Feb 2014 09:37:56 -0500 Subject: [Tutor] Better flow for this? In-Reply-To: <52FB443F.1040809@gmail.com> References: <1469757453.20140211210639@columbus.rr.com> <52FB443F.1040809@gmail.com> Message-ID: <35468761.20140212093756@columbus.rr.com> > Also explain the logic in plain words. Else, we can only guess. Were the comments not enough? You keep taking turns until you get home or die. Each turn has 4 phases. while playing: #phase 1 - fly every turn, you might die #phase 2 - stuff shoots at you every turn, you might die #phase 3 - may or may not get an event card, with certain cards you might die #phase 4 - you drop bombs if you're over a target, you can't die here game over, print score Alan From chigga101 at gmail.com Wed Feb 12 16:11:43 2014 From: chigga101 at gmail.com (Matthew Ngaha) Date: Wed, 12 Feb 2014 15:11:43 +0000 Subject: [Tutor] Recommendation For A Complete Noob In-Reply-To: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> References: <42F37C01-8F48-4224-AEE4-88B92E0B8ECC@gmail.com> Message-ID: > Hi, > > I'm completely new to programming in general and everything I have read so far has pointed me to Python. I was just hoping to get some input as to where I might start. > Start with Python programming for the absolute beginner.... Great author. The book gives you lots of exercises at the end of each chapter to make sure you understood everything up to that point. From amonroe at columbus.rr.com Wed Feb 12 17:20:15 2014 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 12 Feb 2014 11:20:15 -0500 Subject: [Tutor] Better flow for this? In-Reply-To: <35468761.20140212093756@columbus.rr.com> References: <1469757453.20140211210639@columbus.rr.com> <52FB443F.1040809@gmail.com> <35468761.20140212093756@columbus.rr.com> Message-ID: <698349955.20140212112015@columbus.rr.com> > You keep taking turns until you get home or die. Each turn has 4 > phases. > while playing: > #phase 1 - fly every turn, you might die > #phase 2 - stuff shoots at you every turn, you might die > #phase 3 - may or may not get an event card, with certain cards you might die > #phase 4 - you drop bombs if you're over a target, you can't die here > game over, print score Thinking about this this morning, I struck upon this idea, which seems much cleaner: ------ def phase1(): #do stuff return boolSurvived def phase2(): #do stuff return boolSurvived def phase2(): #do stuff return boolSurvived def phase4(): #do stuff while playing: #phase 1 - fly every turn, you might die playing = phase1() #phase 2 - stuff shoots at you every turn, you might die if playing: playing=phase2() #phase 3 - may or may not get an event card, with certain cards you might die if playing: playing=phase3() #phase 4 - you drop bombs if you're over a target, you can't die here if playing: phase4() game over, print score ------ Alan From marc_eymard at hotmail.com Wed Feb 12 16:25:22 2014 From: marc_eymard at hotmail.com (Marc Eymard) Date: Wed, 12 Feb 2014 15:25:22 +0000 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug Message-ID: Hello there, I want to emulate a coin flip and count how many heads and tails when flipping it a hundred times. I first coded coinflip_WRONG.py with "count_flips += 1" statement within the if/else block. When running it, either returned values are wrong or the script seems to enter in an infinite loop showing no return values at all. coinflip.py is a corrected version I worked out myself. I moved "count_flips+= 1" out of if/else block and inserted it before if/else. However, I still don't understand the bug since, in my understanding, both files are incrementing variable count_flips each time until the loop becomes false. Can somebody explain the reason of the bug. Cheers, Marc -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: coinflip.py Type: text/x-script.phyton Size: 482 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: coinflip_WRONG.py Type: text/x-script.phyton Size: 486 bytes Desc: not available URL: From amonroe at columbus.rr.com Wed Feb 12 19:47:51 2014 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 12 Feb 2014 13:47:51 -0500 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: <1408009090.20140212134751@columbus.rr.com> > Can somebody explain the reason of the bug. I think you have an indentation goof on line 24 in the "wrong" version (the else clause). Alan From davea at davea.name Wed Feb 12 20:08:17 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 14:08:17 -0500 (EST) Subject: [Tutor] Beginner - explaining 'Flip a coin' bug References: Message-ID: Marc Eymard Wrote in message: > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Next time please post in text form rather than html, and actually include the code you're asking us to comment on. -- DaveA From alan.gauld at btinternet.com Wed Feb 12 20:05:52 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Feb 2014 19:05:52 +0000 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: On 12/02/14 15:25, Marc Eymard wrote: > However, I still don't understand the bug since, in my understanding, > both files are incrementing variable *count_flips* each time until the > loop becomes false. > count_heads = 0 > count_tails = 0 > count_flips = 0 > > while count_flips != 100: This is usually a bad idea since if count_flips gets incremented by 2 it could go over 100 and this test will still be true and it will loop forever... (see below). Its better to have a test like: while count_flips <100: > coin_side = random.randint(1,2) > > if coin_side == 1: > count_heads += 1 > count_flips += 1 > else: count_tails += 1 > > count_flips += 1 Because this is outside the else block it gets incremented twice every time a 1 gets 'thrown'. (see above) That's why your solution of incrementing only once before the if/else tests is better. Its a more accurate implementation of the logic and avoids the double increment problem with the while loop. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From zachary.ware+pytut at gmail.com Wed Feb 12 20:13:33 2014 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Wed, 12 Feb 2014 13:13:33 -0600 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: Hi Marc, On Wed, Feb 12, 2014 at 9:25 AM, Marc Eymard wrote: > Hello there, > > I want to emulate a coin flip and count how many heads and tails when > flipping it a hundred times. > > I first coded coinflip_WRONG.py with "count_flips += 1" statement within the > if/else block. > When running it, either returned values are wrong or the script seems to > enter in an infinite loop showing no return values at all. > > coinflip.py is a corrected version I worked out myself. I moved > "count_flips+= 1" out of if/else block and inserted it before if/else. > > However, I still don't understand the bug since, in my understanding, both > files are incrementing variable count_flips each time until the loop becomes > false. > > Can somebody explain the reason of the bug. The problem is that conflip_WRONG.py isn't doing what you think it's doing :). In particular, lines 23 and 24: """ else: count_tails += 1 count_flips += 1 """ While including a statement on the same line after "else:" is legal, it restricts you to only one statement in the block. So if we move that statement off of that line and into the block, we have this: """ else: count_tails += 1 count_flips += 1 """ I think you may be able to see what's going on from here, but to spell it out: instead of being executed in the else block, "count_flips +=1" is being executed unconditionally. Since there's also a "count_flips += 1" in the "if coin_side == 1" block, count_flips is incremented twice when coin_side == 1, and once otherwise. Since your loop condition is "coin_flips != 100", when you reach the point of coin_flips == 99 and coin_side comes up 1, coin_flips will be incremented to 101, and the loop condition will still be satisfied--hence your infinite loop. Having "count_flips += 1" outside the if/else construct is better code, since you want it to be done exactly once each time through the loop no matter what, and reduces repetition. There are several other ways to improve your code as well, but they'll come with experience (or from asking :)). Hope this helps, -- Zach From steve at pearwood.info Wed Feb 12 21:48:30 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Feb 2014 07:48:30 +1100 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: <20140212204830.GT3799@ando> On Wed, Feb 12, 2014 at 02:08:17PM -0500, Dave Angel wrote: > Marc Eymard Wrote in message: > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > Next time please post in text form rather than html, and actually > include the code you're asking us to comment on. Dave, your tools are letting you down. Marc did post in text, and did include his code, as you can see from the multipart attachments to his email: I 1 [multipa/alternativ, 7bit, 2.0K] I 2 ??> [text/plain, quoted, iso-8859-1, 0.7K] I 3 ??> [text/html, quoted, iso-8859-1, 1.0K] A 4 coinflip.py [text/x-script.p, base64, us-ascii, 0.6K] A 5 coinflip_WRONG.py [text/x-script.p, base64, us-ascii, 0.6K] I 6 [text/plain, 7bit, us-ascii, 0.2K] Perhaps it is time for you to give up on whatever tool you are using to read this mailing list, or at least to change your assumption when you see a contentless message from "Original poster didn't send email" to "I can't see the email". -- Steven From amonroe at columbus.rr.com Wed Feb 12 21:57:36 2014 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 12 Feb 2014 15:57:36 -0500 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: <703708332.20140212155736@columbus.rr.com> > When running it, either returned values are wrong or the script > seems to enter in an infinite loop showing no return values at all. One other tip: "for" loops are usually more practical when you know exactly how many times you want to loop (100 coin flips). "while" loops are usually more practical when you don't know in advance how many times it might loop. Alan From steve at pearwood.info Wed Feb 12 22:06:06 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Feb 2014 08:06:06 +1100 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: <20140212210606.GU3799@ando> On Wed, Feb 12, 2014 at 03:25:22PM +0000, Marc Eymard wrote: > However, I still don't understand the bug since, in my understanding, > both files are incrementing variable count_flips each time until the > loop becomes false. The problem with the "wrong" file is that it increments the count_flaps variable too many times. You have code: while count_flips != 100: coin_side = random.randint(1,2) #count_flips += 1 if coin_side == 1: count_heads += 1 count_flips += 1 else: count_tails += 1 count_flips += 1 where I have added the annotations A and B. So you can see that each time you flip Heads, the "if" statement runs the indented block with two lines: if coin_side == 1: count_heads += 1 count_flips += 1 then jumps past the "else" block with a single in-line statement: else: count_tails += 1 and continues running the code past the if...else block, but still inside the while block past: count_flips += 1 So every time you toss a Head, the number of flips is incremented TWICE instead of once. That means that sometimes you'll have fewer than 100 coin tosses, as seen by adding the number of Heads and Tails, e.g. you might have 30 Tails and 35 Heads (each Tail counts once, and each Head counts twice, giving 100 mis-counted flips). But occasionally, if you happen to toss Heads when the count is at 99, you'll jump to 101 skipping over 100, and the while-loop then will loop forever. In my next email, I'll explain how to better improve the code. -- Steven From steve at pearwood.info Wed Feb 12 22:14:51 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Feb 2014 08:14:51 +1100 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: <20140212211451.GV3799@ando> On Wed, Feb 12, 2014 at 03:25:22PM +0000, Marc Eymard wrote: > I want to emulate a coin flip and count how many heads and tails when > flipping it a hundred times. In my last reply, I said I'd next give you some pointers to improve the code. If you'd rather work on it yourself first, stop reading now! In your working code, you have (in part): count_heads = 0 count_tails = 0 count_flips = 0 while count_flips != 100: coin_side = random.randint(1,2) count_flips += 1 if coin_side == 1: count_heads += 1 #count_flips += 1 else: count_tails += 1 #count_flips += 1 The first thing to notice is that by the logic of the task, each flip must be either a Head or a Tail, so the number of Heads and the number of Tails should always add up to the number of flips. So you don't need to record all three variables, you only need two of them. The second thing is that since the number of flips is incremented by one every single time through the loop, regardsless of what happens, you don't need to manually increment that. You can get Python to do the counting for you, using a for-loop: for count_flips in range(1, 101): coin_side = random.randint(1,2) if coin_side == 1: count_heads += 1 At the end of the loop, you will have count_flips equal to 100 (can you see why?) and the number of Tails will be count_flips - count_heads. -- Steven From neilc at norwich.edu Wed Feb 12 22:30:22 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Wed, 12 Feb 2014 21:30:22 +0000 (UTC) Subject: [Tutor] Beginner - explaining 'Flip a coin' bug References: <20140212204830.GT3799@ando> Message-ID: On 2014-02-12, Steven D'Aprano wrote: > On Wed, Feb 12, 2014 at 02:08:17PM -0500, Dave Angel wrote: >> Next time please post in text form rather than html, and >> actually include the code you're asking us to comment on. > > Dave, your tools are letting you down. Marc did post in text, and did > include his code, as you can see from the multipart attachments to his > email: > > I 1 [multipa/alternativ, 7bit, 2.0K] > I 2 ??????> [text/plain, quoted, iso-8859-1, 0.7K] > I 3 ??????> [text/html, quoted, iso-8859-1, 1.0K] > A 4 coinflip.py [text/x-script.p, base64, us-ascii, 0.6K] > A 5 coinflip_WRONG.py [text/x-script.p, base64, us-ascii, 0.6K] > I 6 [text/plain, 7bit, us-ascii, 0.2K] > > > Perhaps it is time for you to give up on whatever tool you are > using to read this mailing list, or at least to change your > assumption when you see a contentless message from "Original > poster didn't send email" to "I can't see the email". This is also a USENET newsgroup, where attachements are not a thing. -- Neil Cerutti From denis.spir at gmail.com Wed Feb 12 22:31:51 2014 From: denis.spir at gmail.com (spir) Date: Wed, 12 Feb 2014 22:31:51 +0100 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: <20140212211451.GV3799@ando> References: <20140212211451.GV3799@ando> Message-ID: <52FBE847.8040409@gmail.com> On 02/12/2014 10:14 PM, Steven D'Aprano wrote: > On Wed, Feb 12, 2014 at 03:25:22PM +0000, Marc Eymard wrote: > >> I want to emulate a coin flip and count how many heads and tails when >> flipping it a hundred times. > > > In my last reply, I said I'd next give you some pointers to > improve the code. If you'd rather work on it yourself first, stop > reading now! > > In your working code, you have (in part): > > > count_heads = 0 > count_tails = 0 > count_flips = 0 > while count_flips != 100: > coin_side = random.randint(1,2) > count_flips += 1 > if coin_side == 1: > count_heads += 1 > #count_flips += 1 > else: count_tails += 1 > #count_flips += 1 > > > The first thing to notice is that by the logic of the task, each flip > must be either a Head or a Tail, so the number of Heads and the number > of Tails should always add up to the number of flips. So you don't need > to record all three variables, you only need two of them. > > The second thing is that since the number of flips is incremented by one > every single time through the loop, regardsless of what happens, you > don't need to manually increment that. You can get Python to do the > counting for you, using a for-loop: > > for count_flips in range(1, 101): > coin_side = random.randint(1,2) > if coin_side == 1: > count_heads += 1 > > > At the end of the loop, you will have count_flips equal to 100 (can you > see why?) and the number of Tails will be count_flips - count_heads. Actually, there are 2 distinct points: * That one doesn't need to count flips: right. * That one needs only to count one eveny kind is accidental, just because there are here only 2 event kinds, so that number of tails+heads=flips. In the general case, Marc's solution to count each even kind is just right. [To compare, there are people using bools to represent 2 distinct cases (eg black & white in a chass game), and it's conceptually wrong: white is not not(black).] d From davea at davea.name Wed Feb 12 23:26:26 2014 From: davea at davea.name (Dave Angel) Date: Wed, 12 Feb 2014 17:26:26 -0500 (EST) Subject: [Tutor] Beginner - explaining 'Flip a coin' bug References: <20140212204830.GT3799@ando> Message-ID: Steven D'Aprano Wrote in message: > On Wed, Feb 12, 2014 at 02:08:17PM -0500, Dave Angel wrote: >> Marc Eymard Wrote in message: >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> > https://mail.python.org/mailman/listinfo/tutor >> > >> Next time please post in text form rather than html, and actually >> include the code you're asking us to comment on. > > Dave, your tools are letting you down. Marc did post in text, and did > include his code, as you can see from the multipart attachments to his > email: > > I 1 [multipa/alternativ, 7bit, 2.0K] > I 2 ??????> [text/plain, quoted, iso-8859-1, 0.7K] > I 3 ??????> [text/html, quoted, iso-8859-1, 1.0K] > A 4 coinflip.py [text/x-script.p, base64, us-ascii, 0.6K] > A 5 coinflip_WRONG.py [text/x-script.p, base64, us-ascii, 0.6K] > I 6 [text/plain, 7bit, us-ascii, 0.2K] > > > Perhaps it is time for you to give up on whatever tool you are using to > read this mailing list, or at least to change your assumption when you > see a contentless message from "Original poster didn't send email" to "I > can't see the email". > He posted in html and included two attachments. His email program added added a text version, which we know is frequently bogus. The nntp news system tossed the attachments, I believe. Now, my newsreader (nntp NewsReader, which is the best I've found for my tablet) has bugs, but not as important as the ones I've stopped using. I can read the html version of the email, but when replying it quotes none of it. Sometimes I just give up, sometimes I use copypaste and sometimes I just mention it. But I don't mention it anymore if it's the only thing I have to say. Are you recommending we ignore newsreader usage, or am I permitted to object to attachments? Do you have another suggestion for me, other than: 1) switch to googlegroups 2) read and post only occasionally, when I get back to my laptop 3) write my own reader that runs on the Android -- DaveA From steve at pearwood.info Wed Feb 12 23:44:01 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Feb 2014 09:44:01 +1100 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: <20140212204830.GT3799@ando> Message-ID: <20140212224401.GW3799@ando> On Wed, Feb 12, 2014 at 09:30:22PM +0000, Neil Cerutti wrote: > > Perhaps it is time for you to give up on whatever tool you are > > using to read this mailing list, or at least to change your > > assumption when you see a contentless message from "Original > > poster didn't send email" to "I can't see the email". > > This is also a USENET newsgroup, where attachements are not a > thing. Not officially :-) There may be unofficial mirrors of this mailing list on Usenet, but officially (according to python.org) it is a mailing list. The canonical source and archive for this is here: https://mail.python.org/mailman/listinfo/tutor There are other unofficial mirrors, e.g. here: http://code.activestate.com/lists/python-tutor/99298/ and gmane.comp.python.tutor, which by the way shows Marc's post in full, all four of his plain text, HTML, and two .py parts, AND the plain text footer added by the mailman software. Of course attachments are "a thing" in Usenet. One of the reasons so few ISPs offer News services these days is because of the *huge* volume of attachments on binary news groups. Any news client that can't at least *receive* attachments is a major failure. -- Steven From steve at pearwood.info Thu Feb 13 00:02:05 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Feb 2014 10:02:05 +1100 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: <52FBE847.8040409@gmail.com> References: <20140212211451.GV3799@ando> <52FBE847.8040409@gmail.com> Message-ID: <20140212230205.GX3799@ando> On Wed, Feb 12, 2014 at 10:31:51PM +0100, spir wrote: > On 02/12/2014 10:14 PM, Steven D'Aprano wrote: > >The first thing to notice is that by the logic of the task, each flip > >must be either a Head or a Tail, so the number of Heads and the number > >of Tails should always add up to the number of flips. So you don't need > >to record all three variables, you only need two of them. [...] > * That one needs only to count one eveny kind is accidental, just because > there are here only 2 event kinds, so that number of tails+heads=flips. That is not accidental. That is fundamental to the idea of tossing a coin to get Heads or Tails. Even if you generalise to more than two different events, the sum of each event equals the total number of events. Unless you are forgetting to count some events, or counting other events twice, how can it be otherwise? > In > the general case, Marc's solution to count each even kind is just right. In the *general case* of counting events that occur in N different kinds, the total number of events is equal to the sum of each count. So if there are six different events, plus the total: heads tails hearts spades diamonds clubs total you don't need to record all seven counts (although of course you can if you wish) but just six of them, and work out the seventh: total = sum of heads, tails, hearts, spades, diamonds and clubs or heads = total - sum of tails, hearts, spades, diamonds and clubs for example. In the language of statistics, we say that there are six degrees of freedom here (the six kinds of events) but seven variables. Any one of those variables is completely determined by the other six. > [To compare, there are people using bools to represent 2 distinct cases (eg > black & white in a chass game), and it's conceptually wrong: white is not > not(black).] Of course it is. If x ? {White, Black}, then if x is not White, then it must be Black. There are no other options. There is a one:one correspondence between any two-element set and {White, Black}: white, black = ChessColour("white"), ChessColour("black") white, black = "white", "black" white, black = 0, 255 white, black = 255, 0 white, black = -1, 1 white, black = True, False whichever solution makes your code simpler, more efficient, more easily understood, etc. -- Steven From steve at pearwood.info Thu Feb 13 00:25:04 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Feb 2014 10:25:04 +1100 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: <20140212204830.GT3799@ando> Message-ID: <20140212232504.GY3799@ando> On Wed, Feb 12, 2014 at 05:26:26PM -0500, Dave Angel wrote: > He posted in html and included two attachments. His email program > added added a text version, which we know is frequently bogus. "Frequently?" I don't think so. I hardly ever see text parts which don't say the same thing as the html part, modulo changes to indentation. I can't say "never", as I have seen a few commercial emails (usually advertising) that say "If you cannot read the body of this email, upgrade your email program" instead of a formatting-free version of their HTML part. (Which, by the way, is incredibly rude of them.) But in general, the text part and the html part match very closely, if not exactly. > The nntp news system tossed the attachments, I believe. If you check out the gmane.comp.python.tutor mirror, you will see the attachments. > Now, my newsreader (nntp NewsReader, which is the best I've > found for my tablet) has bugs, but not as important as the ones > I've stopped using. I can read the html version of the email, but > when replying it quotes none of it. Sometimes I just give up, > sometimes I use copypaste and sometimes I just mention it. But I > don't mention it anymore if it's the only thing I have to > say. > > Are you recommending we ignore newsreader usage, or am I permitted > to object to attachments? > Do you have another suggestion for me, other than: > > 1) switch to googlegroups > 2) read and post only occasionally, when I get back to my laptop > 3) write my own reader that runs on the Android As I said in my earlier response, I think it's time for you to switch your default assumption from "the original poster didn't send a plain text message" to "unless other people on the mailing list complain, there probably is a plain text component, I just can't see it". I'm sorry that your technology is letting you down. I'm even more sorry that your current choice is the least worst of a bunch of even worse choices. (Googlegroups? Ew.) I'm afraid that the tech world is going to keep getting worse and worse in this regard, as more and more sites and programmers make unjustified assumptions about what technology is available to the reader. My pet bugbear is websites that don't degrade gracefully when Javascript is turned off, but are essentially unreadable. Worse, sites that are unusable unless you allow Facebook and other spyware sites to run code in your browser. But you've admitted that your tool of choice has limitations, and I don't think it is either fair or useful to rail against the sender for the limitations in your news reader. It's not 1990 any more, and the battle against HTML mail has well and truly be lost. (More's the pity, in my opinion.) I don't know if this works for you, but can you not get mail on your tablet? Perhaps you could read this via the mailing list? -- Steven From steve at pearwood.info Thu Feb 13 00:28:53 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Feb 2014 10:28:53 +1100 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: <20140212232504.GY3799@ando> References: <20140212204830.GT3799@ando> <20140212232504.GY3799@ando> Message-ID: <20140212232853.GZ3799@ando> On Thu, Feb 13, 2014 at 10:25:04AM +1100, Steven D'Aprano wrote: > On Wed, Feb 12, 2014 at 05:26:26PM -0500, Dave Angel wrote: > > The nntp news system tossed the attachments, I believe. > > If you check out the gmane.comp.python.tutor mirror, you will see the > attachments. Er, that is to say, if you check out the mirror using a newsreader that shows attachments, you will see the attachments. Anyway, enough metadiscussion about the technology used by this forum. -- Steven From rhce.san at gmail.com Thu Feb 13 07:44:59 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Thu, 13 Feb 2014 12:14:59 +0530 Subject: [Tutor] Regular expressions Message-ID: Hi all, I am using ipython. 1 ) Defined a string. In [88]: print string foo foobar 2) compiled the string to grab the "foo" word. In [89]: reg = re.compile("foo",re.IGNORECASE) 3) Now i am trying to match . In [90]: match = reg.match(string) 4) Now i print it. In [93]: print match.group() foo Correct me if i am wrong, i am expecting both "foo" and "foobar", why is it giving just "foo" Thanks, santosh -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Feb 13 08:24:28 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Feb 2014 08:24:28 +0100 Subject: [Tutor] Regular expressions References: Message-ID: Santosh Kumar wrote: > Hi all, > > I am using ipython. > > 1 ) Defined a string. > > In [88]: print string > foo foobar > > 2) compiled the string to grab the "foo" word. > > In [89]: reg = re.compile("foo",re.IGNORECASE) > > 3) Now i am trying to match . > > In [90]: match = reg.match(string) > > 4) Now i print it. > > In [93]: print match.group() > foo > > Correct me if i am wrong, i am expecting both "foo" and "foobar", why is > it giving > just "foo" re.match always gives at most one match, and that match has to start at the beginning of the string: >>> import re >>> r = re.compile("foo", re.I) >>> help(r.match) Help on built-in function match: match(...) match(string[, pos[, endpos]]) --> match object or None. Matches zero or more characters at the beginning of the string >>> r.match("bar foobar") >>> Use re.findall() if you need all matches >>> r.findall("foo FOObar") ['foo', 'FOO'] or re.finditer() if you need other information than just the matching string: >>> [m.start() for m in r.finditer("foo FOObar")] [0, 4] From duxbuz at hotmail.com Thu Feb 13 12:05:42 2014 From: duxbuz at hotmail.com (Ian D) Date: Thu, 13 Feb 2014 11:05:42 +0000 Subject: [Tutor] can I make a while loop true again In-Reply-To: References: , Message-ID: Hi It has taken me longer than I thought to get back to this topic. tut. Anyway thanks. I wondered why array was being mentioned ha ha So have I got this correct in that when I run a turtle program I am in fact using this forever loop, so I do not need to use a while True loop at all really in a turtle gui program? > To: tutor at python.org > From: __peter__ at web.de > Date: Tue, 11 Feb 2014 14:01:47 +0100 > Subject: Re: [Tutor] can I make a while loop true again > > Ian D wrote: > >> Thanks for the help on the last one. >> >> Is it possible to restart a while loop? This doesn't work at all (surprise >> surprise) >> >> import turtle as t >> >> def start(): >> global more >> more = True >> >> def stop(): >> global more >> more = False >> >> more = True >> >> while True: >> while more: >> >> t.onkey(stop, "space") >> t.onkey(start, "Up") >> t.fd(1) >> t.listen() > > When you want your script to work like a typical GUI application you will > soon reach the limits with turtle. turtle tries hard to hide it, but GUIs > have an independent loop permanently running listening to user events and > small functions to respond these events. > > To have the turtle start and stop I came up with the following which looks > similar to normal GUI code. Instead of the explicit loop there is a function > `step_forward` that may or may not reschedule itself depending on the state > of the `running` flag. > > > > import turtle > > def step_forward(): > if running: > turtle.forward(5) > # call step_forward() again after 100 milliseconds: > turtle.ontimer(step_forward, 100) > > def start(): > global running > > if not running: > running = True > step_forward() > > def turn_left(): > turtle.left(10) > > def turn_right(): > turtle.right(10) > > def stop(): > global running > running = False > > running = False > > turtle.delay(0) > turtle.onkey(start, "Up") > turtle.onkey(turn_left, "Left") > turtle.onkey(turn_right, "Right") > turtle.onkey(stop, "space") > > turtle.listen() > turtle.mainloop() > > As a bonus the turtle changes its direction when you hit the left or right > array. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From neilc at norwich.edu Thu Feb 13 15:19:29 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 13 Feb 2014 14:19:29 +0000 (UTC) Subject: [Tutor] Beginner - explaining 'Flip a coin' bug References: <20140212204830.GT3799@ando> <20140212224401.GW3799@ando> Message-ID: On 2014-02-12, Steven D'Aprano wrote: > Of course attachments are "a thing" in Usenet. One of the > reasons so few ISPs offer News services these days is because > of the *huge* volume of attachments on binary news groups. Any > news client that can't at least *receive* attachments is a > major failure. I'm living in the past, man! -- Neil Cerutti From wprins at gmail.com Thu Feb 13 18:17:00 2014 From: wprins at gmail.com (Walter Prins) Date: Thu, 13 Feb 2014 17:17:00 +0000 Subject: [Tutor] Regular expressions In-Reply-To: References: Message-ID: Hi, On 13 February 2014 06:44, Santosh Kumar wrote: > I am using ipython. > > 1 ) Defined a string. > > In [88]: print string > foo foobar > > 2) compiled the string to grab the "foo" word. > > In [89]: reg = re.compile("foo",re.IGNORECASE) > > 3) Now i am trying to match . > > In [90]: match = reg.match(string) > > 4) Now i print it. > > In [93]: print match.group() > foo > > Correct me if i am wrong, i am expecting both "foo" and "foobar", why is it > giving > just "foo" A small addition to Peter's already comprehensive reply: Your regular expression is not including what follows "foo", it is defined as *only* the string literal "foo", so it can only ever match and return the literal string "foo". Try specifying "foo.*" as the regular expression. Example session: Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 1.0.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. [C:/Src]|1> s='foo foobar' [C:/Src]|2> import re [C:/Src]|3> reg=re.compile('foo.*', re.IGNORECASE) [C:/Src]|4> match=reg.match(s) [C:/Src]|5> print match.group() foo foobar Walter From alan.gauld at btinternet.com Tue Feb 11 10:31:26 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 11 Feb 2014 09:31:26 +0000 (GMT) Subject: [Tutor] if >= 0 In-Reply-To: References: <1392076708.10442.YahooMailNeo@web186002.mail.ir2.yahoo.com> Message-ID: <1392111086.35837.YahooMailNeo@web186004.mail.ir2.yahoo.com> CCing the list. Please use Reply All when responding. >?thanks Alan, i understand now zero is False.? That's right. but... > so if one of the 'if' test is false, that 'for' loop is also halted?? > and does not proceed to the next element? This bit ?is wrong. The for loop will continue to completion every time. >>> for element in in_file: >>> ? if ?element.find(LOCUS'): >>> ? ? locus += element >>> ? elif element.find(...) What happens is that because the find(LOCUS) is the first test it will almost? always be true. So the locus += element will be executed on almost every line Because that branch of the if construct is executed no other branch is executed. In an if/elif/else structure only one branch ever gets executed in a given? iteration of the for loop. elif stands for "else if" so the test in the elif statements? only get executed if all the preceding tests fail. So the order of the tests is? very important.?Now in your case the first branch?nearly always succeeds ? and so the subsequent branches never get executed.? When you add the >=0 condition you stop the first test from catching everything. So the lines that do not contain LOCUS now get tested for the other values? and as a result update their respective string variables. But the for loop continues regardless of which branch is used, it is only? controlled by the number of lines in the file. It does not care what the code? inside the loop body does (unless it explicitly uses return or break or continue). HTH Alan g.? From __peter__ at web.de Fri Feb 14 10:53:05 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Feb 2014 10:53:05 +0100 Subject: [Tutor] can I make a while loop true again References: Message-ID: Ian D wrote: > Anyway thanks. I wondered why array was being mentioned ha ha > So have I got this correct in that when I run a turtle program I am in > fact using this forever loop, so I do not need to use a while True loop at > all really in a turtle gui program? Yes. From dwightdhutto at gmail.com Sat Feb 15 04:49:43 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Fri, 14 Feb 2014 22:49:43 -0500 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: Here is a problem I've come across, from empirical evidence, that also relates to your equation. We always assume that their are always two probabilities, that a coin can be either head or tails. However, there are dynamics within a third realm of the dimensionality of the coin...it's not a two dimensional plane. So the planar probabilities in relation to the 'surface are' hold another possibility...the 'edge'. The algorithm of applying the edge are up to you, but I've seen the coin land on it's curved edge more than once, so this function you've designed, should have more than two possibilities, within a complete algorithm to the real world functionality of the coin in question. On Wed, Feb 12, 2014 at 10:25 AM, Marc Eymard wrote: > Hello there, > > I want to emulate a coin flip and count how many heads and tails when > flipping it a hundred times. > > I first coded *coinflip_WRONG.py* with "count_flips += 1" statement > within the *if/else* block. > When running it, either returned values are wrong or the script seems to > enter in an infinite loop showing no return values at all. > > *coinflip.py* is a corrected version I worked out myself. I moved > "count_flips+= 1" out of *if/else* block and inserted it before* if/else*. > > However, I still don't understand the bug since, in my understanding, both > files are incrementing variable *count_flips* each time until the loop > becomes false. > > Can somebody explain the reason of the bug. > Cheers, > > Marc > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Feb 15 04:51:50 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Fri, 14 Feb 2014 22:51:50 -0500 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: On Fri, Feb 14, 2014 at 10:49 PM, David Hutto wrote: > Here is a problem I've come across, from empirical evidence, that also > relates to your equation. We always assume > that their are always two probabilities, that a coin can be either head > or tails. > > However, there are dynamics within a third realm of the dimensionality of > the coin...it's not a two dimensional plane. So the planar probabilities in > relation to the 'surface are' *surface area hold another possibility...the > 'edge'. > > The algorithm of applying the edge are up to you, but I've seen the coin > land on it's curved edge more than once, so this function you've designed, > should have more than two possibilities, within a complete algorithm to the > real world functionality of the coin in question. > > > On Wed, Feb 12, 2014 at 10:25 AM, Marc Eymard wrote: > >> Hello there, >> >> I want to emulate a coin flip and count how many heads and tails when >> flipping it a hundred times. >> >> I first coded *coinflip_WRONG.py* with "count_flips += 1" statement >> within the *if/else* block. >> When running it, either returned values are wrong or the script seems to >> enter in an infinite loop showing no return values at all. >> >> *coinflip.py* is a corrected version I worked out myself. I moved >> "count_flips+= 1" out of *if/else* block and inserted it before* if/else* >> . >> >> However, I still don't understand the bug since, in my understanding, >> both files are incrementing variable *count_flips* each time until the >> loop becomes false. >> >> Can somebody explain the reason of the bug. >> Cheers, >> >> Marc >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Best Regards, > David Hutto > *CEO:* *http://www.hitwebdevelopment.com > * > -- Best Regards, David Hutto *CEO:* *http://www.hitwebdevelopment.com * -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwightdhutto at gmail.com Sat Feb 15 05:03:05 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Fri, 14 Feb 2014 23:03:05 -0500 Subject: [Tutor] Beginner - explaining 'Flip a coin' bug In-Reply-To: References: Message-ID: Just to add a footnote to the above remember: http://en.wikipedia.org/wiki/Random_seed unless setting your own random seed algorithm is applied. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bunnysehgal101 at gmail.com Sat Feb 15 14:35:51 2014 From: bunnysehgal101 at gmail.com (Bunny Sehgal) Date: Sat, 15 Feb 2014 19:05:51 +0530 Subject: [Tutor] Need help with generators.... Message-ID: I am doing "Building Skills in Python". In the Generator Function example at [url] http://www.itmaybeahack.com/homepage/books/python/html/p02/p02c08_generators.html#generator-function-example[/url]i can't understand, how it is working properly. what i understood is as follows:> 1)First it makes count = 0 2)then it goes straight in for loop 3)Since the first color is red, it goes in else block and increment count to 1 and stop execution. 4)Now its next method is called using list comprehension, and it resumes its execution and yield its first value i.e. 1.Note that the yield statement is outside the for loop. 5)Now there is no further yield statement which can stop execution of countreds() function.So it raises StopExecution exception But this is not what is happening..... why? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 15 19:37:07 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Feb 2014 18:37:07 +0000 Subject: [Tutor] Need help with generators.... In-Reply-To: References: Message-ID: On 15/02/14 13:35, Bunny Sehgal wrote: > I am doing "Building Skills in Python". In the Generator Function > example at I assume you are talking about this one: spins = [('red', '18'), ('black', '13'), ('red', '7'), ('red', '5'), ('black', '13'), ('red', '25'), ('red', '9'), ('black', '26'), ('black', '15'), ('black', '20'), ('black', '31'), ('red', '3')] def countReds( aList ): count= 0 for color,number in aList: if color == 'black': yield count count= 0 else: count += 1 yield count gaps= [ gap for gap in countReds(spins) ] print gaps > what i understood is as follows:> > 1)First it makes count = 0 > 2)then it goes straight in for loop > 3)Since the first color is red, it goes in else block and increment > count to 1 and stop execution. What makes you think it stops? It carries on to the next iteration which is black and so enters the if block which yields the count which will be 1. > 4)Now its next method is called using list comprehension, and it resumes > its execution and yield its first value i.e. 1.Note that the yield > statement is outside the for loop. Not quite, Next time round it carries on from the yield so sets count back to zero and fetches the next two tuples before hitting another black. So this time it yields 2. Once the tuples are exhausted it yields the final count, which should be 1 > 5)Now there is no further yield statement which can stop execution of > countreds() function.So it raises StopExecution exception > > But this is not what is happening..... why? Your understanding was flawed. Assuming I've pasted the correct code listing... But there is an explanation right under the listing on the page. Assuming you read it, which bit of that did you not understand? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From marc_eymard at hotmail.com Sat Feb 15 16:40:06 2014 From: marc_eymard at hotmail.com (Marc Eymard) Date: Sat, 15 Feb 2014 15:40:06 +0000 Subject: [Tutor] thanks - Beginner - explaining 'Flip a coin' bug In-Reply-To: References: , Message-ID: Hi David, Thanks for your input about the logic of this little script of mine. I confess I omitted the edge possibility and assumed heads or taisl only. As I progress further with getting the foundation knowledge of the language itself, it is really appreciated to be corrected on what good programming is about regardless of the language. Please keep commenting/helping whenever necessary. Cheers, Marc Date: Fri, 14 Feb 2014 22:49:43 -0500 Subject: Re: [Tutor] Beginner - explaining 'Flip a coin' bug From: dwightdhutto at gmail.com To: marc_eymard at hotmail.com CC: tutor at python.org Here is a problem I've come across, from empirical evidence, that also relates to your equation. We always assume that their are always two probabilities, that a coin can be either head or tails. However, there are dynamics within a third realm of the dimensionality of the coin...it's not a two dimensional plane. So the planar probabilities in relation to the 'surface are' hold another possibility...the 'edge'. The algorithm of applying the edge are up to you, but I've seen the coin land on it's curved edge more than once, so this function you've designed, should have more than two possibilities, within a complete algorithm to the real world functionality of the coin in question. On Wed, Feb 12, 2014 at 10:25 AM, Marc Eymard wrote: Hello there, I want to emulate a coin flip and count how many heads and tails when flipping it a hundred times. I first coded coinflip_WRONG.py with "count_flips += 1" statement within the if/else block. When running it, either returned values are wrong or the script seems to enter in an infinite loop showing no return values at all. coinflip.py is a corrected version I worked out myself. I moved "count_flips+= 1" out of if/else block and inserted it before if/else. However, I still don't understand the bug since, in my understanding, both files are incrementing variable count_flips each time until the loop becomes false. Can somebody explain the reason of the bug. Cheers, Marc _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -- Best Regards, David Hutto CEO: http://www.hitwebdevelopment.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc_eymard at hotmail.com Sat Feb 15 17:25:34 2014 From: marc_eymard at hotmail.com (Marc Eymard) Date: Sat, 15 Feb 2014 16:25:34 +0000 Subject: [Tutor] Beginner - understanding randint arguments Message-ID: Hello Tutor, I need to generate a random integer between 0 and 100. The range is supposed to be adjusted by my two variables: low_range and high_range. The logic of using the variables as part of the function arguments is to manage to get a smaller range each time the function is called excluding the possible repeat of the return value of randint. Here is what happens in my script: >>> import random >>> low_range = -1 >>> high_range = 101 >>> random.randint(low_range + 1, high_range - 1) 56 >>> low_range -1 >>> high_range 101 I was rather expecting: >>> low_range 0 >>> high_range 100 Can somebody explain why both low_range and high_range are still returning their initial values ? Thanks, Marc -------------- next part -------------- An HTML attachment was scrubbed... URL: From jslozier at gmail.com Sat Feb 15 19:47:16 2014 From: jslozier at gmail.com (Jay Lozier) Date: Sat, 15 Feb 2014 13:47:16 -0500 Subject: [Tutor] Beginner - understanding randint arguments In-Reply-To: References: Message-ID: <52FFB634.1020109@gmail.com> On 02/15/2014 11:25 AM, Marc Eymard wrote: > Hello Tutor, > > I need to generate a random integer between 0 and 100. > > The range is supposed to be adjusted by my two variables: > low_range and high_range. > > The logic of using the variables as part of the function arguments is > to manage to get a smaller range each time the function is called > _excluding_ the possible repeat of the return value of randint. > > Here is what happens in my script: > > >>> import random > >>> low_range = -1 > >>> high_range = 101 > >>> random.randint(low_range + 1, high_range - 1) > 56 > >>> low_range > -1 > >>> high_range > 101* > * > > > I was rather expecting: > > >>> low_range > > 0 > > >>> high_range > > 100 > > > Can somebody explain why both low_range and high_range are still > returning their initial values ? > > Thanks, > Marc* > * The variables low_range and high_range are not modified. The arguments to random.randint do not change the initial values of the variables, only the actual values passed. -- Jay Lozier jslozier at gmail.com From alan.gauld at btinternet.com Sat Feb 15 19:50:59 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Feb 2014 18:50:59 +0000 Subject: [Tutor] Beginner - understanding randint arguments In-Reply-To: References: Message-ID: On 15/02/14 16:25, Marc Eymard wrote: > Here is what happens in my script: > > >>> import random > >>> low_range = -1 > >>> high_range = 101 > >>> random.randint(low_range + 1, high_range - 1) > 56 > >>> low_range > -1 > >>> high_range > 101* > > I was rather expecting: > > >>> low_range > 0 > >>> high_range > 100 Really? Why? You never change low_range or high_range so why would their values change? The help() for randint says: randint(self, a, b) method of random.Random instance Return random integer in range [a, b], including both end points. So the function doesn't change the values either it just returns a random number between them. > Can somebody explain why both low_range and high_range are still > returning their initial values ? Because you didn't change them. When you called randint you passed in two expressions: low_range+1 and high_range-1 which Python evaluated as 0 and 100. But that did not change your variable values in any way, it just created new values that were passed into randint() as 'a' and 'b' respectively. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sat Feb 15 21:03:55 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Feb 2014 07:03:55 +1100 Subject: [Tutor] Beginner - understanding randint arguments In-Reply-To: References: Message-ID: <20140215200355.GJ4281@ando> On Sat, Feb 15, 2014 at 04:25:34PM +0000, Marc Eymard wrote: > Can somebody explain why both low_range and high_range are still > returning their initial values ? Because you haven't changed either of them. Imagine the chaos if every time you did arithmetic on a variable, Python changed the variable: x = 1 y = x + 100 What is the value of y? 101, correct? What is the value of x? It should still be 1, not 101. The same applies when you get rid of the "y =" and just pass it to a function: x = 1 some_function(x + 100) What's the value of x? It needs to be 1, because you haven't changed it. The only way to change x is to explicitly change it: x = x + 100 -- Steven From rhce.san at gmail.com Sun Feb 16 05:32:52 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Sun, 16 Feb 2014 10:02:52 +0530 Subject: [Tutor] Regular expressions In-Reply-To: References: Message-ID: Thank you all. On Thu, Feb 13, 2014 at 10:47 PM, Walter Prins wrote: > Hi, > > On 13 February 2014 06:44, Santosh Kumar wrote: > > I am using ipython. > > > > 1 ) Defined a string. > > > > In [88]: print string > > foo foobar > > > > 2) compiled the string to grab the "foo" word. > > > > In [89]: reg = re.compile("foo",re.IGNORECASE) > > > > 3) Now i am trying to match . > > > > In [90]: match = reg.match(string) > > > > 4) Now i print it. > > > > In [93]: print match.group() > > foo > > > > Correct me if i am wrong, i am expecting both "foo" and "foobar", why is > it > > giving > > just "foo" > > A small addition to Peter's already comprehensive reply: Your regular > expression is not including what follows "foo", it is defined as > *only* the string literal "foo", so it can only ever match and return > the literal string "foo". > > Try specifying "foo.*" as the regular expression. Example session: > > Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] > Type "copyright", "credits" or "license" for more information. > > IPython 1.0.0 -- An enhanced Interactive Python. > ? -> Introduction and overview of IPython's features. > %quickref -> Quick reference. > help -> Python's own help system. > object? -> Details about 'object', use 'object??' for extra details. > > [C:/Src]|1> s='foo foobar' > > [C:/Src]|2> import re > > [C:/Src]|3> reg=re.compile('foo.*', re.IGNORECASE) > > [C:/Src]|4> match=reg.match(s) > > [C:/Src]|5> print match.group() > foo foobar > > > > Walter > -- D. Santosh Kumar RHCE | SCSA +91-9703206361 Every task has a unpleasant side .. But you must focus on the end result you are producing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rakeshsharma14 at hotmail.com Sun Feb 16 10:15:37 2014 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Sun, 16 Feb 2014 14:45:37 +0530 Subject: [Tutor] Upload a file using python Message-ID: Greetings!! Hi , I need to upload some file into a website. Its ajax based and so I managed to do using selenium.But I feel if i can use the http methods without involving any UI level automation things would be better.I have tried 'requests' library for this. Can't get how to upload a file. I performed it using post method. But dint get the required result.The uploaded file dint appear in the site. Any help anyone? thanks,rakesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 16 16:17:52 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Feb 2014 15:17:52 +0000 Subject: [Tutor] Upload a file using python In-Reply-To: References: Message-ID: On 16/02/14 09:15, rakesh sharma wrote: > But I feel if i can use the http methods without involving any UI level > automation things would be better. To use http the server at the other end needs to know what you are trying to do. Given it already publishes an Ajax interface I'd have thought it was unlikely to also have a raw http interface for file uploads. > file. I performed it using post method. But dint get the required result. > The uploaded file dint appear in the site. Does the server have a page that accepts post requests to upload files? If not it won't recognize your post request and possibly just ignore it or hopefully send you an http error back. Did you check the http error code returned? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From aaronmisquith at gmail.com Mon Feb 17 10:07:48 2014 From: aaronmisquith at gmail.com (Aaron Misquith) Date: Mon, 17 Feb 2014 14:37:48 +0530 Subject: [Tutor] Performing an union of two files containing keywords Message-ID: I have 2 different text files. File1.txt contains: file RAMPython parser File2.txt contains: file1234 program I want to perform an union of these both files such that i get an output file3.txt which contains: file RAMPython parser1234 program The program that i'm working on just combines two files. Any help on performing an union such that a keyword would not be repeated would be appreciated. Code: with open("C:\\File1.txt") as fin1: lines = fin1.readlines() with open("C:\\File2.txt") as fin2: lines.extend(fin2.readlines()) with open("D:\\file3.txt", "r+") as fout: fout.write('\n'.join(lines)) -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Feb 17 10:42:44 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 17 Feb 2014 09:42:44 +0000 Subject: [Tutor] Performing an union of two files containing keywords In-Reply-To: References: Message-ID: On 17/02/2014 09:07, Aaron Misquith wrote: > I have 2 different text files. > > File1.txt contains: > > |file > RAM > Python > parser| > > File2.txt contains: > > |file > 1234 > program| > > I want to perform an union of these both files such that i get an output > file3.txt which contains: > > |file > RAM > Python > parser > 1234 > program > | > The program that i'm working on just combines two files. Any help on > performing an union such that a keyword would not be repeated would be > appreciated. > > > Code: > with open("C:\\File1.txt") as fin1: lines = fin1.readlines() > with open("C:\\File2.txt") as fin2: lines.extend(fin2.readlines()) > with open("D:\\file3.txt", "r+") as fout: fout.write('\n'.join(lines)) > Use sets http://docs.python.org/3/library/stdtypes.html#set -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From __peter__ at web.de Mon Feb 17 10:46:15 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Feb 2014 10:46:15 +0100 Subject: [Tutor] Performing an union of two files containing keywords References: Message-ID: Aaron Misquith wrote: > I have 2 different text files. > > File1.txt contains: > > file > RAMPython > parser > > File2.txt contains: > > file1234 > program > > I want to perform an union of these both files such that i get an output > file3.txt which contains: > > file > RAMPython > parser1234 > program > > > > The program that i'm working on just combines two files. Any help on > performing an union such that a keyword would not be repeated would be > appreciated. Have a look at the set class and its update() method. > Code: > with open("C:\\File1.txt") as fin1: lines = fin1.readlines() > with open("C:\\File2.txt") as fin2: lines.extend(fin2.readlines()) > with open("D:\\file3.txt", "r+") as fout: fout.write('\n'.join(lines)) fout.write("\n".join(lines)) will add extra newlines to the already existing ones. Use fout.writelines(lines) instead. From denis.spir at gmail.com Mon Feb 17 11:29:57 2014 From: denis.spir at gmail.com (spir) Date: Mon, 17 Feb 2014 11:29:57 +0100 Subject: [Tutor] Performing an union of two files containing keywords In-Reply-To: References: Message-ID: <5301E4A5.30403@gmail.com> On 02/17/2014 10:07 AM, Aaron Misquith wrote: > I have 2 different text files. > > File1.txt contains: > > file > RAMPython > parser > > File2.txt contains: > > file1234 > program > > I want to perform an union of these both files such that i get an output > file3.txt which contains: > > file > RAMPython > parser1234 > program I don't understand the logic of your "union" (???) at all. Is your example correct? A naive union in the naive sense would _here_ keep all items, since they are all different, and certainly not compose a non-existant one "parser1234". d From oscar.j.benjamin at gmail.com Mon Feb 17 12:12:14 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Feb 2014 11:12:14 +0000 Subject: [Tutor] Performing an union of two files containing keywords In-Reply-To: References: Message-ID: On 17 February 2014 09:07, Aaron Misquith wrote: > > The program that i'm working on just combines two files. Any help on > performing an union such that a keyword would not be repeated would be > appreciated. > > Code: > with open("C:\\File1.txt") as fin1: lines = fin1.readlines() > with open("C:\\File2.txt") as fin2: lines.extend(fin2.readlines()) > with open("D:\\file3.txt", "r+") as fout: fout.write('\n'.join(lines)) Something like this: with open(r'D:\file3.txt', 'r+') as fout: keywords_seen = set() for filename in r'C:\File1.txt', r'C:\File2.txt': with open(filename) as fin: for line in fin: keyword = line.strip() if keyword not in keywords_seen: fout.write(line) keywords.add(keyword) Why are you opening the output file with mode 'r+'? Are you intending to only overwrite part of the file? I think you probably should use mode 'w' instead. Oscar From alan.gauld at btinternet.com Mon Feb 17 14:20:50 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Feb 2014 13:20:50 +0000 Subject: [Tutor] Performing an union of two files containing keywords In-Reply-To: <5301E4A5.30403@gmail.com> References: <5301E4A5.30403@gmail.com> Message-ID: On 17/02/14 10:29, spir wrote: >> I want to perform an union of these both files such that i get an output >> file3.txt which contains: >> >> file >> RAMPython >> parser1234 >> program > > I don't understand the logic of your "union" (???) at all. Is your > example correct? It's an email formatting issue, I saw the same thing originally (Android) but in Thunderbird all became clear! RAMPython -> RAM Pyhon and parser1234 -> parser 1234 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Mon Feb 17 11:59:33 2014 From: davea at davea.name (Dave Angel) Date: Mon, 17 Feb 2014 05:59:33 -0500 (EST) Subject: [Tutor] Performing an union of two files containing keywords References: Message-ID: Aaron Misquith Wrote in message: > As two others have said, a set is the simplest solution to avoid duplicates. There are other questions to ask, however. Primary is whether order matters. If it does not, then observe that list(set(mylist)) will produce a list from a list without duplicates. If order does matter, then I ask whether there was some constraint that forced you to do it 3 lines. If not, I would suggest that you write the output one line at a time, after checking each line against a set. If the line is not in the set, add it to the set and write it to the file. And watch out for newlines. What happens if one or both input files are missing their final newlines? -- DaveA From davea at davea.name Mon Feb 17 14:05:24 2014 From: davea at davea.name (Dave Angel) Date: Mon, 17 Feb 2014 08:05:24 -0500 Subject: [Tutor] Performing an union of two files containing keywords In-Reply-To: <5301E4A5.30403@gmail.com> References: <5301E4A5.30403@gmail.com> Message-ID: <53020914.2030006@davea.name> On 02/17/2014 05:29 AM, spir wrote: > On 02/17/2014 10:07 AM, Aaron Misquith wrote: >> I have 2 different text files. >> >> File1.txt contains: >> >> file >> RAMPython >> parser >> >> File2.txt contains: >> >> file1234 >> program >> >> I want to perform an union of these both files such that i get an output >> file3.txt which contains: >> >> file >> RAMPython >> parser1234 >> program > > I don't understand the logic of your "union" (???) at all. Is your > example correct? A naive union in the naive sense would _here_ keep all > items, since they are all different, and certainly not compose a > non-existant one "parser1234". > > d > AHA, the mysterious "html" conversion error strikes again. Since Aaron erroneously (and presumably unknowingly) posted in html, and you view it (as most do, and all should) as text, Aaron's email program erroneously lost some of the whitespace markings, and totally distorted the meaning. But "that ship has already sailed", so we have to live with it without mention. -- DaveA From davea at davea.name Mon Feb 17 14:16:13 2014 From: davea at davea.name (Dave Angel) Date: Mon, 17 Feb 2014 08:16:13 -0500 Subject: [Tutor] Performing an union of two files containing keywords In-Reply-To: References: Message-ID: <53020B9D.2030006@davea.name> On 02/17/2014 06:12 AM, Oscar Benjamin wrote: > On 17 February 2014 09:07, Aaron Misquith wrote: >> >> The program that i'm working on just combines two files. Any help on >> performing an union such that a keyword would not be repeated would be >> appreciated. >> >> Code: >> with open("C:\\File1.txt") as fin1: lines = fin1.readlines() >> with open("C:\\File2.txt") as fin2: lines.extend(fin2.readlines()) >> with open("D:\\file3.txt", "r+") as fout: fout.write('\n'.join(lines)) > > Something like this: > > with open(r'D:\file3.txt', 'r+') as fout: > keywords_seen = set() > for filename in r'C:\File1.txt', r'C:\File2.txt': > with open(filename) as fin: > for line in fin: > keyword = line.strip() > if keyword not in keywords_seen: > fout.write(line) > keywords.add(keyword) > > Why are you opening the output file with mode 'r+'? Are you intending > to only overwrite part of the file? I think you probably should use > mode 'w' instead. > You forgot to append the newline to strings in the write() method calls. fout.write(line + "\n") -- DaveA From emailkgnow at gmail.com Mon Feb 17 12:29:46 2014 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Mon, 17 Feb 2014 14:29:46 +0300 Subject: [Tutor] Regarding Exceptions Message-ID: Hi, in the following snippet, why is it I don't need to create an Exception object and I can use the class directly in raise my custom exception? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Mon Feb 17 12:44:36 2014 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Mon, 17 Feb 2014 14:44:36 +0300 Subject: [Tutor] Regarding Exceptions Message-ID: Hi, Why is it i can use mu custom class exception without creating an exception object first? Thanks 1. class ShortInputException(Exception): def __init__(self, length, atleast): 2. Exception.__init__(self) 3. self.length = length 4. self.atleast = atleast 5. try: 6. text = input() if len(text) < 3: 7. raise ShortInputException(len(text), 3) # Other work can continue as usual here 8. except EOFError: 9. print() 10. except ShortInputException as ex: 11. print(\ 12. .format(ex.length, ex.atleast)) else: 13. print() -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc_eymard at hotmail.com Mon Feb 17 12:39:29 2014 From: marc_eymard at hotmail.com (Marc Eymard) Date: Mon, 17 Feb 2014 11:39:29 +0000 Subject: [Tutor] Beginner - Clarifying 'understanding randint arguments' In-Reply-To: References: Message-ID: Hi Tutor, The previous elements I sent to the mailing list were incomplete and needs no answer from Tutor. To clarify and re-phrase my script issue: I want to code a game whereby the computer guesses either by luck or deduction a number I pick within [0, 100]. In attached machine_guess_number.py in which line 22 statement number = random.randint(low_range + 1, high_range - 1) doesn't narrow the range: - to allow number deduction... - ... avoiding ValueError: empty range for randrange() I also attached the output of the script leading to the error showing that the loop does not exit in time to avoid error by working out the answer based on a logical narrowing of the guessing range. Hope this clarifies my previous email (see further down this note). Thanks, Marc > Subject: Your message to Tutor awaits moderator approval > From: tutor-owner at python.org > To: marc_eymard at hotmail.com > Date: Sat, 15 Feb 2014 17:26:41 +0100 > > Your mail to 'Tutor' with the subject > > Beginner - understanding randint arguments > > Is being held until the list moderator can review it for approval. > > The reason it is being held: > > Post by non-member to a members-only list > > Either the message will get posted to the list, or you will receive > notification of the moderator's decision. If you would like to cancel > this posting, please visit the following URL: > > https://mail.python.org/mailman/confirm/tutor/8ee9ed6d473cbc6d77ddc7af36237a9cc3b1d4b3 > From: marc_eymard at hotmail.com To: tutor at python.org Subject: Beginner - understanding randint arguments Date: Sat, 15 Feb 2014 16:25:34 +0000 Hello Tutor, I need to generate a random integer between 0 and 100. The range is supposed to be adjusted by my two variables: low_range and high_range. The logic of using the variables as part of the function arguments is to manage to get a smaller range each time the function is called excluding the possible repeat of the return value of randint. Here is what happens in my script: >>> import random >>> low_range = -1 >>> high_range = 101 >>> random.randint(low_range + 1, high_range - 1) 56 >>> low_range -1 >>> high_range 101 I was rather expecting: >>> low_range 0 >>> high_range 100 Can somebody explain why both low_range and high_range are still returning their initial values ? Thanks, Marc -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: machine_guess_number.py Type: text/x-script.phyton Size: 1378 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: shell_output.py Type: text/x-script.phyton Size: 1423 bytes Desc: not available URL: From kwpolska at gmail.com Mon Feb 17 15:06:26 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Mon, 17 Feb 2014 15:06:26 +0100 Subject: [Tutor] Regarding Exceptions In-Reply-To: References: Message-ID: On Mon, Feb 17, 2014 at 12:44 PM, Khalid Al-Ghamdi wrote: > Hi, > > Why is it i can use mu custom class exception without creating an exception > object first? > > Thanks > > class ShortInputException(Exception): def __init__(self, length, atleast): > Exception.__init__(self) > self.length = length > self.atleast = atleast > try: > text = input() if len(text) < 3: > raise ShortInputException(len(text), 3) # Other work can continue as usual > here > except EOFError: > print() > except ShortInputException as ex: > print(\ > .format(ex.length, ex.atleast)) else: > print() Hello there! Unfortunately, the code you provided is invalid, and it seems not to contain required indentation, newlines, and has some other things that should break (eg. line 12) Please reply (using Reply All!) in plaintext, with the correct code. Also, do you mind phrasing your question more precisely? Do you need help with inheritance? What is the problem you?re having? -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From rakeshsharma14 at hotmail.com Mon Feb 17 15:29:30 2014 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Mon, 17 Feb 2014 19:59:30 +0530 Subject: [Tutor] Upload a file using python In-Reply-To: References: , Message-ID: Greetings!! Hi Alan, The error code was that of success. 200.Donno if the site supports a post method. It doesn't but is there any other way of automating the process.The issue of chrome 32 with selenium webdriver has stalled the show for me. Hence i had to fend for some other ways. thanks,rakesh > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sun, 16 Feb 2014 15:17:52 +0000 > Subject: Re: [Tutor] Upload a file using python > > On 16/02/14 09:15, rakesh sharma wrote: > > > But I feel if i can use the http methods without involving any UI level > > automation things would be better. > > To use http the server at the other end needs to know what you are > trying to do. Given it already publishes an Ajax interface I'd have > thought it was unlikely to also have a raw http interface for file uploads. > > > file. I performed it using post method. But dint get the required result. > > The uploaded file dint appear in the site. > > Does the server have a page that accepts post requests to upload files? > If not it won't recognize your post request and possibly just ignore > it or hopefully send you an http error back. Did you check the http > error code returned? > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 17 16:30:17 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Feb 2014 15:30:17 +0000 Subject: [Tutor] Regarding Exceptions In-Reply-To: References: Message-ID: On 17/02/14 11:44, Khalid Al-Ghamdi wrote: > Why is it i can use mu custom class exception without creating an > exception object first? There are formatting problems when I try to copy your code. I've tried to fix them below, apologies if I got it wrong. However you do create an instance when you raise it... > class ShortInputException(Exception): > def __init__(self, length, atleast): > Exception.__init__(self) > self.length = length > self.atleast = atleast >try: > text = input() > if len(text) < 3: > raise ShortInputException(len(text), 3) You have your class name followed by parens. That's how you create an instance. So you are raising an instance of your class. except ShortInputException as ex: print(... And you catch the instance as ex here... But remember that in Python classes are objects too... So you don't always need to create an instance to use a class. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Feb 17 16:33:27 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Feb 2014 15:33:27 +0000 Subject: [Tutor] Beginner - Clarifying 'understanding randint arguments' In-Reply-To: References: Message-ID: On 17/02/14 11:39, Marc Eymard wrote: > Hi Tutor, > > The previous elements I sent to the mailing list were incomplete and > needs no answer from Tutor. But you got several nonetheless. Did you read them? If so you will know that calling randint() does not change the two xxx_range variables. It simply returns a random number as requested. You will need to modify the range values yourself. > Hope this clarifies my previous email (see further down this note). > >>> import random > >>> low_range = -1 > >>> high_range = 101 > >>> random.randint(low_range + 1, high_range - 1) > 56 > >>> low_range > -1 > >>> high_range > 101* -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Feb 17 16:38:47 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Feb 2014 15:38:47 +0000 Subject: [Tutor] Upload a file using python In-Reply-To: References: , Message-ID: On 17/02/14 14:29, rakesh sharma wrote: > Greetings!! > > Hi Alan, > > The error code was that of success. 200. > Donno if the site supports a post method. It doesn't but is there any > other way of automating the process. > The issue of chrome 32 with selenium webdriver has stalled the show for me. > Hence i had to fend for some other ways. OK I misunderstood your previous mail. Its not that you don't want to use Ajax its that you don't want to drive it via the browser UI? In that case you should be able to call the Ajax API directly using urllib or cgi possibly some higher level Ajax module - I suspect one will exist somewhere! But at this point we probably need to see some code to see how you are trying to do it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Mon Feb 17 16:58:57 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 17 Feb 2014 15:58:57 +0000 Subject: [Tutor] Upload a file using python In-Reply-To: References: , Message-ID: On 17/02/2014 15:38, Alan Gauld wrote: > > In that case you should be able to call the Ajax API directly using > urllib or cgi possibly some higher level Ajax module - I suspect one > will exist somewhere! > First port of call for such things https://pypi.python.org/pypi -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From gb.gabrielebrambilla at gmail.com Mon Feb 17 17:05:00 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 17 Feb 2014 11:05:00 -0500 Subject: [Tutor] for: how to skip items Message-ID: Hi, I'm wondering how I can (if I can) make a for loop in which I don't use all the elements. for example a100 = list(range(100)) for a in a100: print(a) it print out to me all the numbers from 0 to 99 But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one every 10 elements) how can I do it WITHOUT defining a new list (my real case is not so simple) and WITHOUT building a list of indexes? thank you Gabriele -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Feb 17 17:06:10 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Feb 2014 16:06:10 +0000 Subject: [Tutor] Performing an union of two files containing keywords In-Reply-To: <53020B9D.2030006@davea.name> References: <53020B9D.2030006@davea.name> Message-ID: On 17 February 2014 13:16, Dave Angel wrote: > On 02/17/2014 06:12 AM, Oscar Benjamin wrote: >> >> Something like this: >> >> with open(r'D:\file3.txt', 'r+') as fout: >> keywords_seen = set() >> for filename in r'C:\File1.txt', r'C:\File2.txt': >> with open(filename) as fin: >> for line in fin: >> keyword = line.strip() >> if keyword not in keywords_seen: >> fout.write(line) >> keywords.add(keyword) The line above should obviously be keywords_seen.add(keyword) > You forgot to append the newline to strings in the write() method calls. > > fout.write(line + "\n") Iterating over a file keeps the newlines: >>> list(open('file1.txt')) ['file1\n', 'file2\n'] Oscar From oscar.j.benjamin at gmail.com Mon Feb 17 17:08:52 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Feb 2014 16:08:52 +0000 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: On 17 February 2014 16:05, Gabriele Brambilla wrote: > Hi, > > I'm wondering how I can (if I can) make a for loop in which I don't use all > the elements. > > for example > > a100 = list(range(100)) > > for a in a100: > print(a) > > it print out to me all the numbers from 0 to 99 > But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one every 10 > elements) how can I do it WITHOUT defining a new list (my real case is not > so simple) and WITHOUT building a list of indexes? for a in a100: if a % 10 == 9: print(a) Alternatively: for a in a100: if a % 10 == 9: continue print(a) Oscar From joel.goldstick at gmail.com Mon Feb 17 17:12:24 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 17 Feb 2014 11:12:24 -0500 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: On Feb 17, 2014 11:06 AM, "Gabriele Brambilla" < gb.gabrielebrambilla at gmail.com> wrote: > > Hi, > > I'm wondering how I can (if I can) make a for loop in which I don't use all the elements. > > for example > > a100 = list(range(100)) > > for a in a100: > print(a) > > it print out to me all the numbers from 0 to 99 > But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one every 10 elements) how can I do it WITHOUT defining a new list (my real case is not so simple) and WITHOUT building a list of indexes? > > thank you > > Gabriele > > __________since this is homework, study if statements and the modulo operator (%)_____________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gb.gabrielebrambilla at gmail.com Mon Feb 17 17:15:18 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 17 Feb 2014 11:15:18 -0500 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: Excuse me for the bad english: not "a random float numbers" but "random float numbers" Gabriele 2014-02-17 11:13 GMT-05:00 Gabriele Brambilla < gb.gabrielebrambilla at gmail.com>: > No sorry, > > it's because my problem is not so simple: > imagine that in a100 contains not integer sorted in a good way but a > random float numbers. > How could I display only one item every 10? > > thanks > > Gabriele > > > 2014-02-17 11:08 GMT-05:00 Oscar Benjamin : > > On 17 February 2014 16:05, Gabriele Brambilla >> wrote: >> > Hi, >> > >> > I'm wondering how I can (if I can) make a for loop in which I don't use >> all >> > the elements. >> > >> > for example >> > >> > a100 = list(range(100)) >> > >> > for a in a100: >> > print(a) >> > >> > it print out to me all the numbers from 0 to 99 >> > But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one >> every 10 >> > elements) how can I do it WITHOUT defining a new list (my real case is >> not >> > so simple) and WITHOUT building a list of indexes? >> >> for a in a100: >> if a % 10 == 9: >> print(a) >> >> Alternatively: >> >> for a in a100: >> if a % 10 == 9: >> continue >> print(a) >> >> >> Oscar >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dpalao.python at gmail.com Mon Feb 17 17:15:20 2014 From: dpalao.python at gmail.com (David Palao) Date: Mon, 17 Feb 2014 17:15:20 +0100 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: Hi Gabriele, Without knowing the details of what you are trying, I guess you could be interested in looking at how to define your own iterators. Regards 2014-02-17 17:05 GMT+01:00 Gabriele Brambilla : > Hi, > > I'm wondering how I can (if I can) make a for loop in which I don't use all > the elements. > > for example > > a100 = list(range(100)) > > for a in a100: > print(a) > > it print out to me all the numbers from 0 to 99 > But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one every 10 > elements) how can I do it WITHOUT defining a new list (my real case is not > so simple) and WITHOUT building a list of indexes? > > thank you > > Gabriele > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From gb.gabrielebrambilla at gmail.com Mon Feb 17 17:17:25 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 17 Feb 2014 11:17:25 -0500 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: Doesn't exist a way in Python to do like in C for i=0, i<100, i=i+10 ? without creating a list of index? Gabriele 2014-02-17 11:15 GMT-05:00 David Palao : > Hi Gabriele, > Without knowing the details of what you are trying, I guess you could > be interested in looking at how to define your own iterators. > > Regards > > 2014-02-17 17:05 GMT+01:00 Gabriele Brambilla < > gb.gabrielebrambilla at gmail.com>: > > Hi, > > > > I'm wondering how I can (if I can) make a for loop in which I don't use > all > > the elements. > > > > for example > > > > a100 = list(range(100)) > > > > for a in a100: > > print(a) > > > > it print out to me all the numbers from 0 to 99 > > But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one > every 10 > > elements) how can I do it WITHOUT defining a new list (my real case is > not > > so simple) and WITHOUT building a list of indexes? > > > > thank you > > > > Gabriele > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Feb 17 17:19:36 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Feb 2014 16:19:36 +0000 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: On 17 February 2014 16:13, Gabriele Brambilla wrote: > No sorry, > > it's because my problem is not so simple: > imagine that in a100 contains not integer sorted in a good way but a random > float numbers. > How could I display only one item every 10? for n, a in enumerate(a100): if n % 10 == 9: print(a) Oscar From gb.gabrielebrambilla at gmail.com Mon Feb 17 17:13:13 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 17 Feb 2014 11:13:13 -0500 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: No sorry, it's because my problem is not so simple: imagine that in a100 contains not integer sorted in a good way but a random float numbers. How could I display only one item every 10? thanks Gabriele 2014-02-17 11:08 GMT-05:00 Oscar Benjamin : > On 17 February 2014 16:05, Gabriele Brambilla > wrote: > > Hi, > > > > I'm wondering how I can (if I can) make a for loop in which I don't use > all > > the elements. > > > > for example > > > > a100 = list(range(100)) > > > > for a in a100: > > print(a) > > > > it print out to me all the numbers from 0 to 99 > > But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one > every 10 > > elements) how can I do it WITHOUT defining a new list (my real case is > not > > so simple) and WITHOUT building a list of indexes? > > for a in a100: > if a % 10 == 9: > print(a) > > Alternatively: > > for a in a100: > if a % 10 == 9: > continue > print(a) > > > Oscar > -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Feb 17 17:24:09 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Feb 2014 16:24:09 +0000 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: On 17 February 2014 16:17, Gabriele Brambilla wrote: > Doesn't exist a way in Python to do like in C > > for i=0, i<100, i=i+10 > > ? without creating a list of index? You haven't said which Python version you're using. In Python 2 the range function returns a list but the xrange function returns an iterator. In Python 3 the range function returns an iterator. Assuming you're using Python 3 then you can just do: for i in range(0, 100, 10): print(a100[i]) Oscar From gb.gabrielebrambilla at gmail.com Mon Feb 17 17:38:33 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Mon, 17 Feb 2014 11:38:33 -0500 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: thanks, in the end I'm using something like this and it works: zipPARApha = zip(Pampli, Pgamma, Pecut, Pb, g) for n, (a1,b1,c1,d1,pha) in enumerate(zipPARApha): where the arguments of zip are lists of the same size. Gabriele 2014-02-17 11:19 GMT-05:00 Oscar Benjamin : > On 17 February 2014 16:13, Gabriele Brambilla > wrote: > > No sorry, > > > > it's because my problem is not so simple: > > imagine that in a100 contains not integer sorted in a good way but a > random > > float numbers. > > How could I display only one item every 10? > > for n, a in enumerate(a100): > if n % 10 == 9: > print(a) > > > Oscar > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Feb 17 17:39:23 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 17 Feb 2014 16:39:23 +0000 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: On 17/02/2014 16:17, Gabriele Brambilla wrote: > Doesn't exist a way in Python to do like in C > > for i=0, i<100, i=i+10 > > ? without creating a list of index? > > Gabriele > > > 2014-02-17 11:15 GMT-05:00 David Palao >: > > Hi Gabriele, > Without knowing the details of what you are trying, I guess you could > be interested in looking at how to define your own iterators. > > Regards > > 2014-02-17 17:05 GMT+01:00 Gabriele Brambilla > >: > > Hi, > > > > I'm wondering how I can (if I can) make a for loop in which I > don't use all > > the elements. > > > > for example > > > > a100 = list(range(100)) > > > > for a in a100: > > print(a) > > > > it print out to me all the numbers from 0 to 99 > > But if I want to display only the numbers 0, 9, 19, 29, 39, > ...(one every 10 > > elements) how can I do it WITHOUT defining a new list (my real > case is not > > so simple) and WITHOUT building a list of indexes? > > > > thank you > > > > Gabriele > > Please don't top post on this list. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From emile at fenx.com Mon Feb 17 17:49:27 2014 From: emile at fenx.com (emile) Date: Mon, 17 Feb 2014 08:49:27 -0800 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: On 02/17/2014 08:05 AM, Gabriele Brambilla wrote: > Hi, > > I'm wondering how I can (if I can) make a for loop in which I don't use all > the elements. > > for example > > a100 = list(range(100)) > > for a in a100: > print(a) > > it print out to me all the numbers from 0 to 99 > But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one every > 10 elements) how can I do it WITHOUT defining a new list (my real case is > not so simple) and WITHOUT building a list of indexes? > Look into python's slice notation -- [root at whfw2 root]# python Python 2.7.1 (r271:86832, Dec 6 2010, 13:47:21) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a100 = list(range(100)) >>> a100[::10] [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] >>> HTH, Emile From ugajin at talktalk.net Mon Feb 17 18:01:17 2014 From: ugajin at talktalk.net (ugajin at talktalk.net) Date: Mon, 17 Feb 2014 12:01:17 -0500 Subject: [Tutor] Fwd: for: how to skip items In-Reply-To: References: Message-ID: <8D0FA18FDFB676D-EC0-11B87@webmail-vfrr03.sis.aol.com> 0, 9, 19, 29, 39, is not every 10th index If you want to output every 10th. index try: a100 = list(range(0,100,10)) for a in a100: print(a) -----Original Message----- From: Gabriele Brambilla To: python tutor Sent: Mon, 17 Feb 2014 16:06 Subject: [Tutor] for: how to skip items Hi, I'm wondering how I can (if I can) make a for loop in which I don't use all the elements. for example a100 = list(range(100)) for a in a100: print(a) it print out to me all the numbers from 0 to 99 But if I want to display only the numbers 0, 9, 19, 29, 39, ...(one every 10 elements) how can I do it WITHOUT defining a new list (my real case is not so simple) and WITHOUT building a list of indexes? thank you Gabriele _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Mon Feb 17 17:35:37 2014 From: andipersti at gmail.com (Andreas Perstinger) Date: Mon, 17 Feb 2014 17:35:37 +0100 Subject: [Tutor] for: how to skip items In-Reply-To: References: Message-ID: <20140217173537.49166eea@Hof> Gabriele Brambilla wrote: >it's because my problem is not so simple: >imagine that in a100 contains not integer sorted in a good way but a >random float numbers. >How could I display only one item every 10? You can provide a step size if you slice a list: >>> l = list(range(10)) >>> l[0:10:2] [0, 2, 4, 6, 8] >>> l[0:10:5] [0, 5] Is that what you want? Bye, Andreas From davea at davea.name Mon Feb 17 14:53:08 2014 From: davea at davea.name (Dave Angel) Date: Mon, 17 Feb 2014 08:53:08 -0500 Subject: [Tutor] Regarding Exceptions In-Reply-To: References: Message-ID: <53021444.4080606@davea.name> On 02/17/2014 06:44 AM, Khalid Al-Ghamdi wrote: > Hi, > > Why is it i can use mu custom class exception without creating an exception > object first? > > Thanks > > > 1. class ShortInputException(Exception): def __init__(self, length, > atleast): > 2. Exception.__init__(self) > 3. self.length = length > 4. self.atleast = atleast > 5. try: > 6. text = input() if len(text) < 3: > 7. raise ShortInputException(len(text), 3) # Other work can continue as > usual here > 8. except EOFError: > 9. print() > 10. except ShortInputException as ex: > 11. print(\ > 12. .format(ex.length, ex.atleast)) else: > 13. print() > > Your code posted here is totally broken. indentation is missing and lines are illegally combined. And somehow you added colors and incorrect line numbers besides. Please post here in plain text, not html, and without line numbers, colorizing or other nonsense. Now to your question. I don't know what you mean "without creating an exception object". You create one in the raise statement. It is dubious however to raise an exception in any __init__ routine, since that could perhaps mean that not all the intiialization has actually happened. And it could lead to infinite recursion, if the exception is the same class as you're initializing. I would also strenuously avoid doing input() or other blocking operations in the __init__ routine, but I'm not sure I know of any real reason why. if this is real code, and not just an experiment, could you explain (after formatting it in a text message so we can actually read it) just what does happen, and what you expected/wished to happen? (You might not see this message or my others for quite some time, as it seems I've been dropped from the approved posters by having joined the mailing list ???) -- DaveA From davea at davea.name Mon Feb 17 19:41:47 2014 From: davea at davea.name (Dave Angel) Date: Mon, 17 Feb 2014 13:41:47 -0500 (EST) Subject: [Tutor] Performing an union of two files containing keywords References: <53020B9D.2030006@davea.name> Message-ID: Oscar Benjamin Wrote in message: > On 17 February 2014 13:16, Dave Angel wrote: >> On 02/17/2014 06:12 AM, Oscar Benjamin wrote: >>> >>> Something like this: >>> >>> with open(r'D:\file3.txt', 'r+') as fout: >>> keywords_seen = set() >>> for filename in r'C:\File1.txt', r'C:\File2.txt': >>> with open(filename) as fin: >>> for line in fin: >>> keyword = line.strip() >>> if keyword not in keywords_seen: >>> fout.write(line) >>> keywords.add(keyword) > > The line above should obviously be keywords_seen.add(keyword) > >> You forgot to append the newline to strings in the write() method calls. >> >> fout.write(line + "\n") > > Iterating over a file keeps the newlines: > >>>> list(open('file1.txt')) > ['file1\n', 'file2\n'] > Sorry, I read your code too quickly and figured you had done an in-place strip(). Since you did not, you run the risk of encountering a file without trailing newline. I prefer to at least rstrip each line, then add the newline back in when writing. -- DaveA From davea at davea.name Mon Feb 17 19:54:59 2014 From: davea at davea.name (Dave Angel) Date: Mon, 17 Feb 2014 13:54:59 -0500 (EST) Subject: [Tutor] for: how to skip items References: Message-ID: Gabriele Brambilla Wrote in message: > in the end I'm using something like this and it works: > zipPARApha = zip(Pampli, Pgamma, Pecut, Pb, g) > for n, (a1,b1,c1,d1,pha) in enumerate(zipPARApha): > where the arguments of zip are lists of the same size. Simpler would be: for a1,b1,c1,d1,pha in zipPARApha[9::10]: or if the list is huge, the islice equivalent. The [9::10] syntax says you want to slice out elements 9, 19, etc. -- DaveA From walksloud at gmail.com Mon Feb 17 20:23:39 2014 From: walksloud at gmail.com (=?windows-1252?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ec?= =?windows-1252?Q?om=3E=22?=) Date: Mon, 17 Feb 2014 14:23:39 -0500 Subject: [Tutor] constructing semi-arbitrary functions Message-ID: Hello python tutors, I am utilizing a 3rd party numerical minimization routine. This routine requires an input function, which takes as arguments, only the variables with which to solve for. But I don?t want to define all possible input functions, in a giant switch, but rather, if I know I am fitting a polynomial, I would like to just pass a list of parameters and have the code know how to construct this function. To construct for example, a chisq function, you must pass not only the variables to solve for, but also the data, uncertainties, and perhaps other arguments. So it requires a little hacking to get it to work. With the help of my friends and looking at similar code, I have come up with two ways that work under my simple test cases, and I have a few questions about them. The 3rd party minimizer utilizes the .func_code.co_varnames and .func_code.co_argcount to determine the name and number of variables to minimize. eg. > g = lambda x,c_0,c_1: c_0 + c_1 * x > g.func_code.co_varnames ('x', 'c_0', 'c_1?) > g.func_code.co_argcount 3 so what is needed is a function > def f(c_0,c_1): > ?#construct chi_sq(c_0,c_1,x,y,?) ========= METHOD 1: make classes to define functions #create a function_structure which can be used to make the necessary func_code class FunctionStruct: def __init__(self, **kwds): self.__dict__.update(kwds) def __str__(self): return self.__dict__.__str__() def __repr__(self): return self.__str__() def __getitem__(self, s): return self.__dict__[s] # then make a polynomial class which constructs a polynomial of order len(pars) class PolynomialFunc: def __init__(self,x,pars): self.pars = pars self.func_code = FunctionStruct(#create the variables used by minimizer co_argcount = len(pars), co_varnames = tuple(['c_%i'%(i) for i in range(len(pars))]) ) def __call__(self): self.poly = 0. for n in range(self.func_code.co_argcount): self.poly += self.pars[n] * x **n return self.poly # eg create a polynomial of order (1) which can be used in the minimizer f = PolynomialFunc(x,[c_0,c_1]) f.func_code.co_varnames ('c_0', 'c_1?) ========= METHOD 2: use strings, exec and globals to construct function def minimize(pars,x,y,dy): global g_x, g_y, g_dy g_x = x; g_y = y; g_dy = dy argnames = ['c_%i'%(i) for i in range(len(pars))] funcargs = ", ".join(argnames) funcdef = 'def chisq_mn(' + funcargs + '):\n' funcdef += ' global g_x, g_y, g_dy\n' funcdef += ' return chisq(['+funcargs+'],g_x,g_y,g_dy)\n? #chisq is defined in same file # evaluate string and build function print "funcdef=", funcdef exec funcdef in globals() m = ThirdParty.setup_minimize(chisq_mn) for i in range(len(pars)): m.values[argnames[i]] = pars[i] m.errors[argnames[i]] = 0.1 * pars[i] return m # then we can define f = minimize(pars,x,y,dy,chisq_func) Question 1: Is there a better way to accomplish (my hopefully clear) goals? Question 2: In method 1, is there a way to combine the two classes, or is the FunctionStruct necessary? I want to do something *like* self.func_code.co_varnames = tuple(['c_%i'%(i) for i in range(len(pars))]) self.func_code.co_argcount = len(pars) but I was not sure how to first define ?self.func_code?. Can you define it as an empty container somehow (is that the right way to describe it)? Question 3: The 2nd method is in some sense simpler - I just hack together a string, but I need to use global variables, which I know can be problematic. Which method, 1 or 2, is in general better? One answer, is whatever works, but I am trying to also improve my programming skills, so I am wondering from a software perspective, which is preferable? Thanks, Andre From oscar.j.benjamin at gmail.com Mon Feb 17 20:58:00 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Feb 2014 19:58:00 +0000 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: On Feb 17, 2014 7:24 PM, ""Andr? Walker-Loud <walksloud at gmail.com>"" wrote: > > Question 1: > Is there a better way to accomplish (my hopefully clear) goals? I'm not sure that there is given the constraints you're under from the third party function. > Question 2: > In method 1, is there a way to combine the two classes, or is the FunctionStruct necessary? I want to do something *like* > > self.func_code.co_varnames = tuple(['c_%i'%(i) for i in range(len(pars))]) > self.func_code.co_argcount = len(pars) > > but I was not sure how to first define 'self.func_code'. Can you define it as an empty container somehow (is that the right way to describe it)? I'm not sure about the details of this. Maybe Eryksun will chime in there... > Question 3: > The 2nd method is in some sense simpler - I just hack together a string, but I need to use global variables, which I know can be problematic. Which method, 1 or 2, is in general better? One answer, is whatever works, but I am trying to also improve my programming skills, so I am wondering from a software perspective, which is preferable? Either solution if it works for this case seems fine to me. I'd be inclined to in for the simpler compile/exec approach. The "right" solution is to change the interface of the third party function. It is poorly designed and should not be inspecting those function attributes or it should at least provide an option for you to provide that information in a different way. Assuming it's open source you could try sending a patch. In the mean time you could copy that code and modify it to suit your purposes. Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Feb 17 21:13:14 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Feb 2014 21:13:14 +0100 Subject: [Tutor] constructing semi-arbitrary functions References: Message-ID: Andr? Walker-Loud wrote: > Hello python tutors, > > I am utilizing a 3rd party numerical minimization routine. This routine > requires an input function, which takes as arguments, only the variables > with which to solve for. But I don?t want to define all possible input > functions, in a giant switch, but rather, if I know I am fitting a > polynomial, I would like to just pass a list of parameters and have the > code know how to construct this function. > > To construct for example, a chisq function, you must pass not only the > variables to solve for, but also the data, uncertainties, and perhaps > other arguments. So it requires a little hacking to get it to work. With > the help of my friends and looking at similar code, I have come up with > two ways that work under my simple test cases, and I have a few questions > about them. > > The 3rd party minimizer utilizes the .func_code.co_varnames and > .func_code.co_argcount to determine the name and number of variables to > minimize. eg. > >> g = lambda x,c_0,c_1: c_0 + c_1 * x >> g.func_code.co_varnames > ('x', 'c_0', 'c_1?) >> g.func_code.co_argcount > 3 > > so what is needed is a function >> def f(c_0,c_1): >> ?#construct chi_sq(c_0,c_1,x,y,?) > > ========= > METHOD 1: make classes to define functions > #create a function_structure which can be used to make the necessary > #func_code > class FunctionStruct: > def __init__(self, **kwds): > self.__dict__.update(kwds) > def __str__(self): > return self.__dict__.__str__() > def __repr__(self): > return self.__str__() > def __getitem__(self, s): > return self.__dict__[s] > > # then make a polynomial class which constructs a polynomial of order > # len(pars) > class PolynomialFunc: > def __init__(self,x,pars): > self.pars = pars > self.func_code = FunctionStruct(#create the variables used by > minimizer > co_argcount = len(pars), > co_varnames = tuple(['c_%i'%(i) for i in range(len(pars))]) > ) > def __call__(self): > self.poly = 0. > for n in range(self.func_code.co_argcount): > self.poly += self.pars[n] * x **n > return self.poly > # eg create a polynomial of order (1) which can be used in the minimizer > f = PolynomialFunc(x,[c_0,c_1]) > f.func_code.co_varnames > ('c_0', 'c_1?) > > ========= > METHOD 2: use strings, exec and globals to construct function > def minimize(pars,x,y,dy): > global g_x, g_y, g_dy > g_x = x; g_y = y; g_dy = dy > argnames = ['c_%i'%(i) for i in range(len(pars))] > funcargs = ", ".join(argnames) > funcdef = 'def chisq_mn(' + funcargs + '):\n' > funcdef += ' global g_x, g_y, g_dy\n' > funcdef += ' return chisq(['+funcargs+'],g_x,g_y,g_dy)\n? #chisq is > defined in same file > # evaluate string and build function > print "funcdef=", funcdef > exec funcdef in globals() > > m = ThirdParty.setup_minimize(chisq_mn) > for i in range(len(pars)): > m.values[argnames[i]] = pars[i] > m.errors[argnames[i]] = 0.1 * pars[i] > return m > # then we can define > f = minimize(pars,x,y,dy,chisq_func) > > Question 1: > Is there a better way to accomplish (my hopefully clear) goals? I think you are looking for closures: def make_poly(coeff): def poly(x): return sum(c * x ** n for n, c in enumerate(coeff)) return poly def minimize(x, y, dy): def chisq_mn(*args): return chisq(args, x, y, dy) return chisq_mn >>> def make_poly(coeff): ... def poly(x): ... return sum(c * x ** n for n, c in enumerate(coeff)) ... return poly ... >>> p = make_poly([1, 0, 1]) >>> for i in range(-4, 5): ... x = i*.25 ... print x, "->", p(x) ... -1.0 -> 2.0 -0.75 -> 1.5625 -0.5 -> 1.25 -0.25 -> 1.0625 0.0 -> 1.0 0.25 -> 1.0625 0.5 -> 1.25 0.75 -> 1.5625 1.0 -> 2.0 From ben+python at benfinney.id.au Mon Feb 17 21:30:58 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Feb 2014 07:30:58 +1100 Subject: [Tutor] when is "pythondontwritebytecode" useful? References: <1390214577.37433.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: <85r4714h31.fsf@benfinney.id.au> Albert-Jan Roskam writes: > I know what it does > (http://docs.python.org/2/using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE), > i.e. no pyc or pyo fiules are written, but WHY is that sometimes a > good thing? There are numerous reasons why one might not want files to suddenly be written when a source file gets compiled. > The only useful scenario I can think of is when you don't have write > rights to create pyc files but you want to use a package anyway. Another reason: The file is named such that adding the letter ?c? at the end is unhelpful. When writing a program to be invoked by a command name, on Unix the convention is to name the program file with the name of the command. So the command ?foo? is implemented in a file named ?foo?, no suffix. This program file needs unit tests, and the test runner will import that file. At which point Python will compile it, and normally create a bytecode file. The bytecode file will be named by appending ?c? to the name of the source file, resulting in the filename ?fooc?. That filename makes no sense, so I want to disable the writing of that bytecode file when that source file is imported. That is just one example, of the more general case that one doesn't want a file arbitrarily appearing in a directory with properties partially outside one's control. Can you think of others? -- \ ?Buy not what you want, but what you need; what you do not need | `\ is expensive at a penny.? ?Cato, 234?149 BCE, Relique | _o__) | Ben Finney From oscar.j.benjamin at gmail.com Mon Feb 17 22:07:31 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Feb 2014 21:07:31 +0000 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: On 17 February 2014 20:13, Peter Otten <__peter__ at web.de> wrote: > Andr? Walker-Loud wrote: >> >> The 3rd party minimizer utilizes the .func_code.co_varnames and >> .func_code.co_argcount to determine the name and number of variables to >> minimize. eg. >> >> ========= >> METHOD 2: use strings, exec and globals to construct function >> def minimize(pars,x,y,dy): >> global g_x, g_y, g_dy >> g_x = x; g_y = y; g_dy = dy >> argnames = ['c_%i'%(i) for i in range(len(pars))] >> funcargs = ", ".join(argnames) >> funcdef = 'def chisq_mn(' + funcargs + '):\n' >> funcdef += ' global g_x, g_y, g_dy\n' >> funcdef += ' return chisq(['+funcargs+'],g_x,g_y,g_dy)\n' #chisq is >> defined in same file >> # evaluate string and build function >> print "funcdef=", funcdef >> exec funcdef in globals() > > I think you are looking for closures: Closures would be a good fit for this if the third-party minimisation routine didn't assume that it always receives a function whose formal parameters are the variables to be minimised and have the names that are intended for display. This one would work (assuming that we want to minimise over x): > def make_poly(coeff): > def poly(x): > return sum(c * x ** n for n, c in enumerate(coeff)) > return poly This one won't work: > def minimize(x, y, dy): > def chisq_mn(*args): > return chisq(args, x, y, dy) > return chisq_mn >>> def minimize(x, y, dy): ... def chisq_mn(*args): ... return chisq(args, x, y, dy) ... return chisq_mn ... >>> f = minimize(2, 4, 0.1) >>> f.func_code.co_varnames ('args',) >>> f.func_code.co_argcount 0 The OP wants to pass this function to a routine that looks like: def minimise(func): num = func.func_code.co_argcount names = func.func_code.co_varnames # Actual minimisation code return _minimise(func, num, names) If it's as simple as above then it may be straightforward to just import the underlying _minimise routine and rewrite the minimise function so that it looks like: def minimise(func, parameter_names=None): if parameter_names is not None: num = func.func_code.co_argcount names = func.func_code.co_varnames else: num = len(parameter_names) # Actual minimisation code return _minimise(func, num, names) Oscar From walksloud at gmail.com Mon Feb 17 22:18:47 2014 From: walksloud at gmail.com (=?windows-1252?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ec?= =?windows-1252?Q?om=3E=22?=) Date: Mon, 17 Feb 2014 16:18:47 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: Hi Oscar, Let me clear up my description of one point - I don?t want to pick on the third party software guys. > The "right" solution is to change the interface of the third party function. It is poorly designed and should not be inspecting those function attributes or it should at least provide an option for you to provide that information in a different way. Assuming it's open source you could try sending a patch. In the mean time you could copy that code and modify it to suit your purposes. The issue has to do with making a general polynomial function, not passing the args of a ?simple? function. If I define def f(c_0,c_1): return chisq(c_0,c_1,x,y,dy) there is no problem using this function, the variables are all passed correctly. What I am trying to avoid is having to write a special case for each order of polynomial I want. I tried the following def poly(x,pars): val = 0. for i,ci in enumerate(pars): val += x**i * ci return val def f_lambda(x,pars): return lambda x,*pars: poly(x,*pars) x = np.array([1,2,3]) f = f_lambda(x,[-.5,2.]) f(x,[-.5,2.]) array([ 1.5, 3.5, 5.5]) f(x,[-.5,3.]) array([ 2.5, 5.5, 8.5]) etc. This function correctly gives me a polynomial of arbitrary order, but f.func_code.co_varnames ('x', 'pars?) so I can not pass this to the third party minimizer, as it does not know how to interpret ?pars'. You can probably see trying to replicate the lambda function method for an arbitrary polynomial is what naturally led to the string/exec option. Thanks, Andre From steve at pearwood.info Mon Feb 17 22:22:56 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 18 Feb 2014 08:22:56 +1100 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: <20140217212256.GO4519@ando> On Mon, Feb 17, 2014 at 07:58:00PM +0000, Oscar Benjamin wrote: > The "right" solution is to change the interface of the third party > function. It is poorly designed and should not be inspecting those function > attributes or it should at least provide an option for you to provide that > information in a different way. Assuming it's open source you could try > sending a patch. In the mean time you could copy that code and modify it to > suit your purposes. This may be a good case for some of the Design Patterns so popular in the Java world. I think what you want is an Adaptor: http://en.wikipedia.org/wiki/Adapter_pattern only written for a function rather than a class. -- Steven From davea at davea.name Mon Feb 17 22:56:38 2014 From: davea at davea.name (Dave Angel) Date: Mon, 17 Feb 2014 16:56:38 -0500 (EST) Subject: [Tutor] constructing semi-arbitrary functions References: Message-ID: Peter Otten <__peter__ at web.de> Wrote in message: > Andr?? Walker-Loud wrote: > >> Hello python tutors, >> >> I am utilizing a 3rd party numerical minimization routine. This routine >> requires an input function, which takes as arguments, only the variables >> with which to solve for. But I don???t want to define all possible input >> functions, in a giant switch, but rather, if I know I am fitting a >> polynomial, I would like to just pass a list of parameters and have the >> code know how to construct this function. >> >> To construct for example, a chisq function, you must pass not only the >> variables to solve for, but also the data, uncertainties, and perhaps >> other arguments. So it requires a little hacking to get it to work. With >> the help of my friends and looking at similar code, I have come up with >> two ways that work under my simple test cases, and I have a few questions >> about them. >> >> The 3rd party minimizer utilizes the .func_code.co_varnames and >> .func_code.co_argcount to determine the name and number of variables to >> minimize. eg. >> >>> g = lambda x,c_0,c_1: c_0 + c_1 * x >>> g.func_code.co_varnames >> ('x', 'c_0', 'c_1???) >>> g.func_code.co_argcount >> 3 >> >> so what is needed is a function >>> def f(c_0,c_1): >>> ???#construct chi_sq(c_0,c_1,x,y,???) >> >> >> >> Question 1: >> Is there a better way to accomplish (my hopefully clear) goals? > > I think you are looking for closures: > > def make_poly(coeff): > I would also recommend closures, but the particular case seems to fit partial pretty well. http://docs.python.org/2/library/functools.html#functools.partial -- DaveA From ben+python at benfinney.id.au Mon Feb 17 22:55:59 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Feb 2014 08:55:59 +1100 Subject: [Tutor] Assignment, references, binding (was: is an alias a variable) References: Message-ID: <85mwhp4d5c.fsf@benfinney.id.au> Ian D writes: > is > import longModuleName as lmn > > or > > lmn = longModuleName > > creating an alias or assigning to a variable..... or both? Assignment and import both bind a name to an object. NAmes are one (common) kind of reference. The only way to get at objects is by using a reference. So, this distinction you're drawing doesn't exist in Python. When you use a name, you're using a reference to an object. When you assign (or, when ?import? assigns) the same object to a different name, the names are both references to the same object, without any name having a special status. -- \ ?True greatness is measured by how much freedom you give to | `\ others, not by how much you can coerce others to do what you | _o__) want.? ?Larry Wall | Ben Finney From oscar.j.benjamin at gmail.com Mon Feb 17 23:01:53 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Feb 2014 22:01:53 +0000 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: On 17 February 2014 21:18, "Andr? Walker-Loud " wrote: > > What I am trying to avoid is having to write a special case for each order of polynomial I want. I tried the following > > def poly(x,pars): > val = 0. > for i,ci in enumerate(pars): > val += x**i * ci > return val > def f_lambda(x,pars): > return lambda x,*pars: poly(x,*pars) > x = np.array([1,2,3]) > f = f_lambda(x,[-.5,2.]) > f(x,[-.5,2.]) > array([ 1.5, 3.5, 5.5]) > > f(x,[-.5,3.]) > array([ 2.5, 5.5, 8.5]) > etc. > > This function correctly gives me a polynomial of arbitrary order, but > > f.func_code.co_varnames > ('x', 'pars') > > so I can not pass this to the third party minimizer, as it does not know how to interpret 'pars'. You can probably see trying to replicate the lambda function method for an arbitrary polynomial is what naturally led to the string/exec option. This particular case is easily solved: def f_lambda(x,pars): return lambda x: poly(x,*pars) You let the closure take care of pars and return a function that takes exactly one argument x. Oscar From walksloud at gmail.com Mon Feb 17 23:15:09 2014 From: walksloud at gmail.com (=?windows-1252?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ec?= =?windows-1252?Q?om=3E=22?=) Date: Mon, 17 Feb 2014 17:15:09 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: > This particular case is easily solved: > > def f_lambda(x,pars): > return lambda x: poly(x,*pars) > > You let the closure take care of pars and return a function that takes > exactly one argument x. Hi Oscar, This is the opposite of what I am trying to do. In the example, x represents the data and pars represent the parameters I want to determine, so it is the pars which I need passed into the ?func_code.co_varnames? part of f. Maybe your suggestion gets me in that direction, but I don?t see how. Thanks, Andre From oscar.j.benjamin at gmail.com Tue Feb 18 00:02:14 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Feb 2014 23:02:14 +0000 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: On 17 February 2014 22:15, "Andr? Walker-Loud " wrote: >> This particular case is easily solved: >> >> def f_lambda(x,pars): >> return lambda x: poly(x,*pars) >> >> You let the closure take care of pars and return a function that takes >> exactly one argument x. > > Hi Oscar, > > This is the opposite of what I am trying to do. In the example, x represents the data and pars represent the parameters I want to determine, so it is the pars which I need passed into the "func_code.co_varnames" part of f. > > Maybe your suggestion gets me in that direction, but I don't see how. No, you're right. I misunderstood this example. Are you able to see/alter the source code of the 3rd party function? As I said earlier my preferred solution would be to rewrite the outermost part of that. The core inner minimisation routine will (I'm guessing) be something that really doesn't care about the names of these parameters and just needs to know the dimensionality of the space it is exploring. If you can access that routine directly then you can bypass the (IMO unfortunate) interface that you're currently trying to contort your problems into. Oscar From oscar.j.benjamin at gmail.com Tue Feb 18 01:03:22 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 18 Feb 2014 00:03:22 +0000 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: On 17 February 2014 22:15, "Andr? Walker-Loud " wrote: >> This particular case is easily solved: >> >> def f_lambda(x,pars): >> return lambda x: poly(x,*pars) >> >> You let the closure take care of pars and return a function that takes >> exactly one argument x. > > Hi Oscar, > > This is the opposite of what I am trying to do. In the example, x represents the data and pars represent the parameters I want to determine, so it is the pars which I need passed into the "func_code.co_varnames" part of f. BTW if you're trying to fit the coefficients of a polynomial then a general purpose optimisation function is probably not what you want to use. I would probably solve (in a least squares sense and after suitable scaling) the Vandermonde matrix. (I can explain that more if desired.) Oscar From walksloud at gmail.com Tue Feb 18 01:34:13 2014 From: walksloud at gmail.com (=?windows-1252?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ec?= =?windows-1252?Q?om=3E=22?=) Date: Mon, 17 Feb 2014 19:34:13 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: <8E16C5B6-BDE9-4506-BB0A-664B94840589@gmail.com> Hi Oscar, On Feb 17, 2014, at 6:02 PM, Oscar Benjamin wrote: > On 17 February 2014 22:15, "Andr? Walker-Loud " > wrote: >>> This particular case is easily solved: >>> >>> def f_lambda(x,pars): >>> return lambda x: poly(x,*pars) >>> >>> You let the closure take care of pars and return a function that takes >>> exactly one argument x. >> >> Hi Oscar, >> >> This is the opposite of what I am trying to do. In the example, x represents the data and pars represent the parameters I want to determine, so it is the pars which I need passed into the "func_code.co_varnames" part of f. >> >> Maybe your suggestion gets me in that direction, but I don't see how. > > No, you're right. I misunderstood this example. > > Are you able to see/alter the source code of the 3rd party function? > As I said earlier my preferred solution would be to rewrite the > outermost part of that. > > The core inner minimisation routine will (I'm guessing) be something > that really doesn't care about the names of these parameters and just > needs to know the dimensionality of the space it is exploring. If you > can access that routine directly then you can bypass the (IMO > unfortunate) interface that you're currently trying to contort your > problems into. Thanks for the advice. At the moment, that sounds a bit too daunting to look into, but worth the effort in the long run. The code is all available. It is in fact a python wrapper around a sophisticated c++ minimizer (Minuit if you?ve heard of it). I am not sure if the python wrapper design was just a choice, or forced upon the designer by the interface to Minuit. That will involve a bit of research. Thanks, Andre From walksloud at gmail.com Tue Feb 18 01:51:00 2014 From: walksloud at gmail.com (=?windows-1252?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ec?= =?windows-1252?Q?om=3E=22?=) Date: Mon, 17 Feb 2014 19:51:00 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: <7C0CBDAF-AB67-4A4D-9DFF-A02A6D2EFD46@gmail.com> Hi Oscar, On Feb 17, 2014, at 7:03 PM, Oscar Benjamin wrote: > On 17 February 2014 22:15, "Andr? Walker-Loud " > wrote: >>> This particular case is easily solved: >>> >>> def f_lambda(x,pars): >>> return lambda x: poly(x,*pars) >>> >>> You let the closure take care of pars and return a function that takes >>> exactly one argument x. >> >> Hi Oscar, >> >> This is the opposite of what I am trying to do. In the example, x represents the data and pars represent the parameters I want to determine, so it is the pars which I need passed into the "func_code.co_varnames" part of f. > > BTW if you're trying to fit the coefficients of a polynomial then a > general purpose optimisation function is probably not what you want to > use. I would probably solve (in a least squares sense and after > suitable scaling) the Vandermonde matrix. > > (I can explain that more if desired.) That looks interesting (just reading the wikipedia entry on the Vandermonde matrix). Is there a good algorithm for picking the values the polynomial is evaluated at to construct the matrix? Is there a benefit to this method vs a standard linear least squares? Given the Vandermonde matrix, how do you determine the uncertainty in the resulting parameters? I guess yes, I am interested to learn more. The most common problem I am solving is fitting a sum of real exponentials to noisy data, with the model function C(t) = sum_n A_n e^{- E_n t} the quantities of most interest are E_n, followed by A_n so I solve this with non-linear regression. To stabilize the fit, I usually do a linear-least squares for the A_n first, solving as a function of the E_n, and then do a non-linear fit for the E_n. Often, we construct multiple data sets which share values of E_n but have different A_n, where A_n is promoted to a matrix, sometimes square, sometimes not. So I want a wrapper on my chisq which can take the input parameter values and deduce the fit function, and pass the variable names to my current minimizer - hence my original question, and why I don?t want to write a special case for each possible combination of n_max, and the shape of A_n. Cheers, Andre From denis.spir at gmail.com Tue Feb 18 15:30:30 2014 From: denis.spir at gmail.com (spir) Date: Tue, 18 Feb 2014 15:30:30 +0100 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: <53036E86.3050503@gmail.com> On 02/17/2014 08:23 PM, "Andr? Walker-Loud " wrote: > Hello python tutors, > > I am utilizing a 3rd party numerical minimization routine. This routine requires an input function, which takes as arguments, only the variables with which to solve for. But I don?t want to define all possible input functions, in a giant switch, but rather, if I know I am fitting a polynomial, I would like to just pass a list of parameters and have the code know how to construct this function. > > To construct for example, a chisq function, you must pass not only the variables to solve for, but also the data, uncertainties, and perhaps other arguments. So it requires a little hacking to get it to work. With the help of my friends and looking at similar code, I have come up with two ways that work under my simple test cases, and I have a few questions about them. > > The 3rd party minimizer utilizes the .func_code.co_varnames and .func_code.co_argcount to determine the name and number of variables to minimize. eg. > >> g = lambda x,c_0,c_1: c_0 + c_1 * x >> g.func_code.co_varnames > ('x', 'c_0', 'c_1?) >> g.func_code.co_argcount > 3 > > so what is needed is a function >> def f(c_0,c_1): >> ?#construct chi_sq(c_0,c_1,x,y,?) What prevents you to make a simple function factory (see example below) is that the 3rd party module needs to use func_code.co_varnames & func_code.co_argcount, right? If yes, it is indeed annoying... and I have no good solution. # func factory example: def poly (*coefs): # coefs are here in reverse order for simplicity # but we could iterate backward below n = len(coefs) def f (x): y = 0 for i in range(n): y += coefs[i] * x**i return y return f # y = 3 + 2*x + 1*x^2 poly3 = poly(3,2,1) print(poly3(1)) # 6 print(poly3(2)) # 11 print(poly3(3)) # 18 d From denis.spir at gmail.com Tue Feb 18 15:36:51 2014 From: denis.spir at gmail.com (spir) Date: Tue, 18 Feb 2014 15:36:51 +0100 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: <53037003.1080807@gmail.com> On 02/18/2014 12:02 AM, Oscar Benjamin wrote: > On 17 February 2014 22:15, "Andr? Walker-Loud " > wrote: >>> This particular case is easily solved: >>> >>> def f_lambda(x,pars): >>> return lambda x: poly(x,*pars) >>> >>> You let the closure take care of pars and return a function that takes >>> exactly one argument x. >> >> Hi Oscar, >> >> This is the opposite of what I am trying to do. In the example, x represents the data and pars represent the parameters I want to determine, so it is the pars which I need passed into the "func_code.co_varnames" part of f. >> >> Maybe your suggestion gets me in that direction, but I don't see how. > > No, you're right. I misunderstood this example. > > Are you able to see/alter the source code of the 3rd party function? > As I said earlier my preferred solution would be to rewrite the > outermost part of that. > > The core inner minimisation routine will (I'm guessing) be something > that really doesn't care about the names of these parameters and just > needs to know the dimensionality of the space it is exploring. If you > can access that routine directly then you can bypass the (IMO > unfortunate) interface that you're currently trying to contort your > problems into. I think so. However it works, the minimising algo only needs values, not names (but it needs to know which meaning/role each value corresponds to, indeed). It is also infortunate that it looks for this information in the (conceptually private) metadata of the function itself, instead of having a dedicated input slot in its interface. d From neilc at norwich.edu Tue Feb 18 15:53:02 2014 From: neilc at norwich.edu (Neil Cerutti) Date: Tue, 18 Feb 2014 14:53:02 +0000 (UTC) Subject: [Tutor] for: how to skip items References: Message-ID: On 2014-02-17, Oscar Benjamin wrote: > On 17 February 2014 16:17, Gabriele Brambilla > wrote: >> Doesn't exist a way in Python to do like in C >> >> for i=0, i<100, i=i+10 >> >> ? without creating a list of index? > > You haven't said which Python version you're using. In Python 2 > the range function returns a list but the xrange function > returns an iterator. In Python 3 the range function returns an > iterator. In Python 3 it range returns a range object, which is a sequence type. >>> x = range(100) >>> x range(0, 100) You can use slice notation on range objects. >>> x[::10] range(0, 100, 10) So we've got *that* going for us. -- Neil Cerutti From oscar.j.benjamin at gmail.com Tue Feb 18 16:09:41 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 18 Feb 2014 15:09:41 +0000 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: <7C0CBDAF-AB67-4A4D-9DFF-A02A6D2EFD46@gmail.com> References: <7C0CBDAF-AB67-4A4D-9DFF-A02A6D2EFD46@gmail.com> Message-ID: On 18 February 2014 00:51, "Andr? Walker-Loud " wrote: >> >> BTW if you're trying to fit the coefficients of a polynomial then a >> general purpose optimisation function is probably not what you want to >> use. I would probably solve (in a least squares sense and after >> suitable scaling) the Vandermonde matrix. >> >> (I can explain that more if desired.) > > That looks interesting (just reading the wikipedia entry on the Vandermonde matrix). > Is there a good algorithm for picking the values the polynomial is evaluated at to construct the matrix? If I understand correctly your data points are given and it is the polynomial coefficients you are trying to solve for. In that case you would use your data points. So if I have data points (x1, y1), ... (x4, y4) and I want to fit a quadratic polynomial of the form y = f(x) then I can choose to minimise the squared error in estimating yi from xi and the coefficients. That is: a * x1^2 + b * x1 + c = y1e ... a * x4^2 + b * x4 + c = y4e And you want to choose a, b and c to minimise the total squared error E = |y1 - y1e|^2 + ... + |y4 - y4e|^2. We can write this as a matrix equation that you want to solve in a least squares sense: |x1^2 x1 1 | | y1 | |x2^2 x2 1 | | a | | y2 | |x3^2 x3 1 | | b | = | y3 | |x4^2 x4 1 | | c | | y4 | Or in other words M(x) k = y where M(x) is the Vandermonde matrix of the x coordinates, y is a column vector of the y coordinates (in the same order) and k is a column vector of the coefficients. You want the least squares solution of this linear system of equations which is the exact solution of: M' M c = M' y where M' means the transpose of M. I mentioned scaling as the Vandermonde matrix can be badly scaled if the x values are either much smaller than or much bigger than which leads to numerical instability. If you rescale your x values to between zero and one before doing this you may get a more accurate result. > Is there a benefit to this method vs a standard linear least squares? It's the same except that you're using an analytic solution rather than a black box solver. > Given the Vandermonde matrix, how do you determine the uncertainty in the resulting parameters? Assuming that you have confidence in the accuracy of your input data: http://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)#Parameter_confidence_limits > I guess yes, I am interested to learn more. > > The most common problem I am solving is fitting a sum of real exponentials to noisy data, with the model function > > C(t) = sum_n A_n e^{- E_n t} > > the quantities of most interest are E_n, followed by A_n so I solve this with non-linear regression. > To stabilize the fit, I usually do a linear-least squares for the A_n first, solving as a function of the E_n, and then do a non-linear fit for the E_n. That doesn't sound optimal to me. Maybe I've misunderstood but fitting over one variable and then over another is not in any way guaranteed to produce an optimal fit. Let's say I want to choose x* and y* to minimise f(x, y). If I choose y0 as a guess and then find x1 that minimises f(x, y0) and then I use that x1 and find the y that minimises f(x1, y) then I have my guess x1 and y1. These are unlikely to be close to the true optimal choices x* and y*. If you continue the algorithm choosing x2 to minimise f(x, y1) and y2 to minimise f(x2, y) generating x2, y2, x3, y3 and so on then it will eventually converge (if the problem is convex). In the xy plane this algorithm would be zig-zagging horizontally and vertically down a valley towards the optimal solution. You can see a picture of this on page 414 of this (free online) book: http://apps.nrbook.com/c/index.html > Often, we construct multiple data sets which share values of E_n but have different A_n, where A_n is promoted to a matrix, sometimes square, sometimes not. So I want a wrapper on my chisq which can take the input parameter values and deduce the fit function, and pass the variable names to my current minimizer - hence my original question, and why I don't want to write a special case for each possible combination of n_max, and the shape of A_n. Well it sounds like your approach so far is working for now but as I say the real fix is to improve or bypass the interface you're using. One limitation that you may at some point hit is that in Python you can't have an unbounded number of formal parameters for a function: $ python3 tmp2.py File "tmp2.py", line 1 def f(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, ^ SyntaxError: more than 255 arguments Oscar From chinex at live.com Tue Feb 18 17:37:29 2014 From: chinex at live.com (Chinanu 'Chinex' Onyekachi) Date: Tue, 18 Feb 2014 16:37:29 +0000 Subject: [Tutor] =?utf-8?q?Using_for_loops_for_combinations?= Message-ID: Find all possible combinations of a specific word (string) using any combination of upper case and lower case letters with a for loop (no itertools). An example: string_input = hat comboination = ['hat', 'Hat', 'HAt', 'HAT', 'hAT', 'haT', 'HaT', 'hAt'] What I've tried so far, I?m trying to do this using knowledge from loops, if and else, strings and lists. gear = ['hat'] for i in range(len(gear[0])): gearlist1 = list(gear[0]) gearlist2 = [c.upper() for c in gearlist1] gearlist3 = [gearlist1[0].join(gearlist2)] print 'list is: %r' % (gearlist3 ,), -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Tue Feb 18 16:16:58 2014 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Tue, 18 Feb 2014 18:16:58 +0300 Subject: [Tutor] OCR Library Message-ID: Hi, Do you have any recommendations regarding a good OCR library (preferably Py3)? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From k.s.robinson at btinternet.com Tue Feb 18 12:59:53 2014 From: k.s.robinson at btinternet.com (KEVIN ROBINSON) Date: Tue, 18 Feb 2014 11:59:53 +0000 (GMT) Subject: [Tutor] cx_freeze windows 7 python 3.3 Message-ID: <1392724793.49605.YahooMailNeo@web186003.mail.ir2.yahoo.com> I am new to this site so please forgive me if I am forwarding this question to the wrong person. ? I am trying to use cx_freeze on windows 7 with python 3.3. ? I can create a build folder and a dist folder using the command line without any problems. ? When I click on the created .exe file I receive the following error:- ? "Cannot import traceback module. Exception:cannot import name MAXREPEAT Original Exception:cannot import name MAXREPEAT" ? I have looked for a solution but cannot find one. ? Can anyone please help. ? Thanks Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhce.san at gmail.com Tue Feb 18 18:52:49 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Tue, 18 Feb 2014 23:22:49 +0530 Subject: [Tutor] Regular expression - I Message-ID: Hi All, If you notice the below example, case I is working as expected. Case I: In [41]: string = "test" In [42]: re.match('',string).group() Out[42]: '' But why is the raw string 'r' not working as expected ? Case II: In [43]: re.match(r'',string).group() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () ----> 1 re.match(r'',string).group() AttributeError: 'NoneType' object has no attribute 'group' In [44]: re.match(r'',string) Thanks, santosh -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Feb 18 18:59:53 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 Feb 2014 18:59:53 +0100 Subject: [Tutor] constructing semi-arbitrary functions References: Message-ID: Oscar Benjamin wrote: > On 17 February 2014 20:13, Peter Otten <__peter__ at web.de> wrote: >> Andr? Walker-Loud wrote: >>> >>> The 3rd party minimizer utilizes the .func_code.co_varnames and >>> .func_code.co_argcount to determine the name and number of variables to >>> minimize. eg. >>> >>> ========= >>> METHOD 2: use strings, exec and globals to construct function >>> def minimize(pars,x,y,dy): >>> global g_x, g_y, g_dy >>> g_x = x; g_y = y; g_dy = dy >>> argnames = ['c_%i'%(i) for i in range(len(pars))] >>> funcargs = ", ".join(argnames) >>> funcdef = 'def chisq_mn(' + funcargs + '):\n' >>> funcdef += ' global g_x, g_y, g_dy\n' >>> funcdef += ' return chisq(['+funcargs+'],g_x,g_y,g_dy)\n' #chisq >>> is defined in same file >>> # evaluate string and build function >>> print "funcdef=", funcdef >>> exec funcdef in globals() >> >> I think you are looking for closures: > > Closures would be a good fit for this if the third-party minimisation > routine didn't assume that it always receives a function whose formal > parameters are the variables to be minimised and have the names that > are intended for display. Thank you for reading the OP more thoroughly and for taking the time to explain to those who don't ;) > This one would work (assuming that we want to minimise over x): > >> def make_poly(coeff): >> def poly(x): >> return sum(c * x ** n for n, c in enumerate(coeff)) >> return poly > > This one won't work: > >> def minimize(x, y, dy): >> def chisq_mn(*args): >> return chisq(args, x, y, dy) >> return chisq_mn > >>>> def minimize(x, y, dy): > ... def chisq_mn(*args): > ... return chisq(args, x, y, dy) > ... return chisq_mn > ... >>>> f = minimize(2, 4, 0.1) >>>> f.func_code.co_varnames > ('args',) >>>> f.func_code.co_argcount > 0 > > The OP wants to pass this function to a routine that looks like: > > def minimise(func): > num = func.func_code.co_argcount > names = func.func_code.co_varnames > # Actual minimisation code > return _minimise(func, num, names) I don't know if the OP may use it, but there seems to be a version of minuit that allows to override the function signature: """ class iminuit.Minuit Minuit(fcn, throw_nan=False, pedantic=True, frontend=None, forced_parameters=None, print_level=1, errordef=None, **kwds) Construct minuit object from given fcn Arguments: [...] forced_parameters: tell Minuit not to do function signature detection and use this argument instead. (Default None (automagically detect signature) """ http://iminuit.github.io/iminuit/api.html From rhce.san at gmail.com Tue Feb 18 19:09:02 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Tue, 18 Feb 2014 23:39:02 +0530 Subject: [Tutor] Regular expression - I In-Reply-To: <089DADDD-0364-4C97-B79E-9B4D25FD938A@alchemy.com> References: <089DADDD-0364-4C97-B79E-9B4D25FD938A@alchemy.com> Message-ID: Steve, i am trying to under r - raw string notation. Am i understanding it wrong. Rather than using "\", it says we can use the "r" option. http://docs.python.org/2/library/re.html Check the first paragraph for the above link. Thanks, santosh On Tue, Feb 18, 2014 at 11:33 PM, Steve Willoughby wrote: > Because the regular expression means ?match an angle-bracket > character, zero or more H characters, followed by a close angle-bracket > character? and your string does not match that pattern. > > This is why it?s best to check that the match succeeded before going ahead > to call group() on the result (since in this case there is no result). > > > On 18-Feb-2014, at 09:52, Santosh Kumar wrote: > > > > > Hi All, > > > > If you notice the below example, case I is working as expected. > > > > Case I: > > In [41]: string = "test" > > > > In [42]: re.match('',string).group() > > Out[42]: '' > > > > But why is the raw string 'r' not working as expected ? > > > > Case II: > > > > In [43]: re.match(r'',string).group() > > > --------------------------------------------------------------------------- > > AttributeError Traceback (most recent call > last) > > in () > > ----> 1 re.match(r'',string).group() > > > > AttributeError: 'NoneType' object has no attribute 'group' > > > > In [44]: re.match(r'',string) > > > > > > > > Thanks, > > santosh > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > -- D. Santosh Kumar RHCE | SCSA +91-9703206361 Every task has a unpleasant side .. But you must focus on the end result you are producing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Feb 18 19:20:09 2014 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 18 Feb 2014 10:20:09 -0800 Subject: [Tutor] Regular expression - I In-Reply-To: References: <089DADDD-0364-4C97-B79E-9B4D25FD938A@alchemy.com> Message-ID: <2D08CE3C-AA44-4FEF-A779-B2166A8CBD54@alchemy.com> The problem is not the use of the raw string, but rather the regular expression inside it. In regular expressions, the * means that whatever appears before it may be repeated zero or more times. So if you say H* that means zero or more H?s in a row. I think you mean an H followed by any number of other characters which would be H.* (the . matches any single character, so .* means zero or more of any characters). On the other hand, H\* means to match an H followed by a literal asterisk character. Does that help clarify why one matched and the other doesn?t? steve On 18-Feb-2014, at 10:09, Santosh Kumar wrote: > Steve, > > i am trying to under r - raw string notation. Am i understanding it wrong. > Rather than using "\", it says we can use the "r" option. > > http://docs.python.org/2/library/re.html > > Check the first paragraph for the above link. > > Thanks, > santosh > > > > On Tue, Feb 18, 2014 at 11:33 PM, Steve Willoughby wrote: > Because the regular expression means ?match an angle-bracket character, zero or more H characters, followed by a close angle-bracket character? and your string does not match that pattern. > > This is why it?s best to check that the match succeeded before going ahead to call group() on the result (since in this case there is no result). > > > On 18-Feb-2014, at 09:52, Santosh Kumar wrote: > > > > > Hi All, > > > > If you notice the below example, case I is working as expected. > > > > Case I: > > In [41]: string = "test" > > > > In [42]: re.match('',string).group() > > Out[42]: '' > > > > But why is the raw string 'r' not working as expected ? > > > > Case II: > > > > In [43]: re.match(r'',string).group() > > --------------------------------------------------------------------------- > > AttributeError Traceback (most recent call last) > > in () > > ----> 1 re.match(r'',string).group() > > > > AttributeError: 'NoneType' object has no attribute 'group' > > > > In [44]: re.match(r'',string) > > > > > > > > Thanks, > > santosh > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > > > -- > D. Santosh Kumar > RHCE | SCSA > +91-9703206361 > > > Every task has a unpleasant side .. But you must focus on the end result you are producing. > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 842 bytes Desc: Message signed with OpenPGP using GPGMail URL: From steve at alchemy.com Tue Feb 18 19:03:22 2014 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 18 Feb 2014 10:03:22 -0800 Subject: [Tutor] Regular expression - I In-Reply-To: References: Message-ID: <089DADDD-0364-4C97-B79E-9B4D25FD938A@alchemy.com> Because the regular expression means ?match an angle-bracket character, zero or more H characters, followed by a close angle-bracket character? and your string does not match that pattern. This is why it?s best to check that the match succeeded before going ahead to call group() on the result (since in this case there is no result). On 18-Feb-2014, at 09:52, Santosh Kumar wrote: > > Hi All, > > If you notice the below example, case I is working as expected. > > Case I: > In [41]: string = "test" > > In [42]: re.match('',string).group() > Out[42]: '' > > But why is the raw string 'r' not working as expected ? > > Case II: > > In [43]: re.match(r'',string).group() > --------------------------------------------------------------------------- > AttributeError Traceback (most recent call last) > in () > ----> 1 re.match(r'',string).group() > > AttributeError: 'NoneType' object has no attribute 'group' > > In [44]: re.match(r'',string) > > > > Thanks, > santosh > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From dyoo at hashcollision.org Tue Feb 18 20:11:59 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 18 Feb 2014 11:11:59 -0800 Subject: [Tutor] OCR Library In-Reply-To: References: Message-ID: On Tue, Feb 18, 2014 at 7:16 AM, Khalid Al-Ghamdi wrote: > Hi, > > Do you have any recommendations regarding a good OCR library (preferably > Py3)? Unsure. This is somewhat of a specialized question, and probably not beginner material. You might want to check up with the general discussion mailing list for this one. https://mail.python.org/mailman/listinfo/python-list Preliminary Google searches suggest that "pytesser" might be an interesting library. You probably want to talk with folks who have direct experience with OCR though; Tutor might not be the best place to find OCR experts. Good luck! From dyoo at hashcollision.org Tue Feb 18 20:18:48 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 18 Feb 2014 11:18:48 -0800 Subject: [Tutor] Using for loops for combinations In-Reply-To: References: Message-ID: On Tue, Feb 18, 2014 at 8:37 AM, Chinanu 'Chinex' Onyekachi wrote: > Find all possible combinations of a specific word (string) using any > combination of upper case and lower case letters with a for loop (no > itertools). > > > An example: > > string_input = hat > > comboination = ['hat', 'Hat', 'HAt', 'HAT', 'hAT', 'haT', 'HaT', 'hAt'] [code cut] This appears to be homework, so unfortunately the help that can be provided will need to be limited; otherwise there's a risk of violating your institution's Honor Code. Can you talk more about what difficulty are you running into? From dyoo at hashcollision.org Tue Feb 18 20:05:45 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 18 Feb 2014 11:05:45 -0800 Subject: [Tutor] cx_freeze windows 7 python 3.3 In-Reply-To: <1392724793.49605.YahooMailNeo@web186003.mail.ir2.yahoo.com> References: <1392724793.49605.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: On Tue, Feb 18, 2014 at 3:59 AM, KEVIN ROBINSON wrote: > I am new to this site so please forgive me if I am forwarding this question > to the wrong person. > > I am trying to use cx_freeze on windows 7 with python 3.3. Unfortunately, this may not be the best mailing list to help with cx_freeze issues. You may want to check with the cx_freeze_users mailing list: http://sourceforge.net/mailarchive/forum.php?forum_name=cx-freeze-users From zachary.ware+pytut at gmail.com Tue Feb 18 20:39:55 2014 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Tue, 18 Feb 2014 11:39:55 -0800 Subject: [Tutor] Regular expression - I In-Reply-To: References: Message-ID: Hi Santosh, On Tue, Feb 18, 2014 at 9:52 AM, Santosh Kumar wrote: > > Hi All, > > If you notice the below example, case I is working as expected. > > Case I: > In [41]: string = "test" > > In [42]: re.match('',string).group() > Out[42]: '' > > But why is the raw string 'r' not working as expected ? > > Case II: > > In [43]: re.match(r'',string).group() > --------------------------------------------------------------------------- > AttributeError Traceback (most recent call last) > in () > ----> 1 re.match(r'',string).group() > > AttributeError: 'NoneType' object has no attribute 'group' > > In [44]: re.match(r'',string) It is working as expected, but you're not expecting the right thing ;). Raw strings don't escape anything, they just prevent backslash escapes from expanding. Case I works because "\*" is not a special character to Python (like "\n" or "\t"), so it leaves the backslash in place: >>> '' '' The equivalent raw string is exactly the same in this case: >>> r'' '' The raw string you provided doesn't have the backslash, and Python will not add backslashes for you: >>> r'' '' The purpose of raw strings is to prevent Python from recognizing backslash escapes. For example: >>> path = 'C:\temp\new\dir' # Windows paths are notorious... >>> path # it looks mostly ok... [1] 'C:\temp\new\\dir' >>> print(path) # until you try to use it C: emp ew\dir >>> path = r'C:\temp\new\dir' # now try a raw string >>> path # Now it looks like it's stuffed full of backslashes [2] 'C:\\temp\\new\\dir' >>> print(path) # but it works properly! C:\temp\new\dir [1] Count the backslashes in the repr of 'path'. Notice that there is only one before the 't' and the 'n', but two before the 'd'. "\d" is not a special character, so Python didn't do anything to it. There are two backslashes in the repr of "\d", because that's the only way to distinguish a real backslash; the "\t" and "\n" are actually the TAB and LINE FEED characters, as seen when printing 'path'. [2] Because they are all real backslashes now, so they have to be shown escaped ("\\") in the repr. In your regex, since you're looking for, literally, "", you'll need to backslash escape the "*" since it is a special character *in regular expressions*. To avoid having to keep track of what's special to Python as well as regular expressions, you'll need to make sure the backslash itself is escaped, to make sure the regex sees "\*", and the easiest way to do that is a raw string: >>> re.match(r'', string).group() '' I hope this makes some amount of sense; I've had to write it up piecemeal and will never get it posted at all if I don't go ahead and post :). If you still have questions, I'm happy to try again. You may also want to have a look at the Regex HowTo in the Python docs: http://docs.python.org/3/howto/regex.html Hope this helps, -- Zach From breamoreboy at yahoo.co.uk Tue Feb 18 20:42:43 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 18 Feb 2014 19:42:43 +0000 Subject: [Tutor] Regular expression - I In-Reply-To: <089DADDD-0364-4C97-B79E-9B4D25FD938A@alchemy.com> References: <089DADDD-0364-4C97-B79E-9B4D25FD938A@alchemy.com> Message-ID: On 18/02/2014 18:03, Steve Willoughby wrote: > Because the regular expression means ?match an angle-bracket character, zero or more H characters, followed by a close angle-bracket character? and your string does not match that pattern. > > This is why it?s best to check that the match succeeded before going ahead to call group() on the result (since in this case there is no result). > > > On 18-Feb-2014, at 09:52, Santosh Kumar wrote: > >> >> Hi All, >> >> If you notice the below example, case I is working as expected. >> >> Case I: >> In [41]: string = "test" >> >> In [42]: re.match('',string).group() >> Out[42]: '' >> >> But why is the raw string 'r' not working as expected ? >> >> Case II: >> >> In [43]: re.match(r'',string).group() >> --------------------------------------------------------------------------- >> AttributeError Traceback (most recent call last) >> in () >> ----> 1 re.match(r'',string).group() >> >> AttributeError: 'NoneType' object has no attribute 'group' >> >> In [44]: re.match(r'',string) >> >> >> >> Thanks, >> santosh >> Please do not top post on this list. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From zachary.ware+pytut at gmail.com Tue Feb 18 20:42:09 2014 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Tue, 18 Feb 2014 11:42:09 -0800 Subject: [Tutor] Regular expression - I In-Reply-To: References: Message-ID: On Tue, Feb 18, 2014 at 11:39 AM, Zachary Ware wrote: > >>> '' > '' > > The equivalent raw string is exactly the same in this case: > > >>> r'' > '' Oops, I mistyped both of these. The repr should be '' in both cases. Sorry for the confusion! -- Zach From stareq13 at yahoo.com Tue Feb 18 20:58:51 2014 From: stareq13 at yahoo.com (S Tareq) Date: Tue, 18 Feb 2014 19:58:51 +0000 (GMT) Subject: [Tutor] Regular expression - I In-Reply-To: References: Message-ID: <1392753531.17168.YahooMailNeo@web133106.mail.ir2.yahoo.com> does any one know how to use 2to3 program to convert 2.7 coding 3.X please i need help sorry? On Tuesday, 18 February 2014, 19:50, Zachary Ware wrote: On Tue, Feb 18, 2014 at 11:39 AM, Zachary Ware wrote: >? ? >>> '' >? ? '' > > The equivalent raw string is exactly the same in this case: > >? ? >>> r'' >? ? '' Oops, I mistyped both of these.? The repr should be '' in both cases. Sorry for the confusion! -- Zach _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Tue Feb 18 20:57:20 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 18 Feb 2014 11:57:20 -0800 (PST) Subject: [Tutor] Regular expression - I In-Reply-To: <089DADDD-0364-4C97-B79E-9B4D25FD938A@alchemy.com> References: <089DADDD-0364-4C97-B79E-9B4D25FD938A@alchemy.com> Message-ID: <1392753440.84550.YahooMailNeo@web163801.mail.gq1.yahoo.com> _____________________________ > From: Steve Willoughby >To: Santosh Kumar >Cc: python mail list >Sent: Tuesday, February 18, 2014 7:03 PM >Subject: Re: [Tutor] Regular expression - I > > >Because the regular expression means ?match an angle-bracket character, zero or more H characters, followed by a close angle-bracket character? and your string does not match that pattern. > >This is why it?s best to check that the match succeeded before going ahead to call group() on the result (since in this case there is no result). > > >On 18-Feb-2014, at 09:52, Santosh Kumar wrote: You also might want to consider making it a non-greedy match. The explanation http://docs.python.org/2/howto/regex.html covers an example almost identical to yours: Greedy versus Non-Greedy When repeating a regular expression, as in a*, the resulting action is to consume as much of the pattern as possible. This fact often bites you when you?re trying to match a pair of balanced delimiters, such as the angle brackets surrounding an HTML tag. The naive pattern for matching a single HTML tag doesn?t work because of the greedy nature of .*. >>> >>> s = 'Title' >>> len(s) 32 >>> print re.match('<.*>', s).span() (0, 32) >>> print re.match('<.*>', s).group() Title The RE matches the '<' in , and the .* consumes the rest of the string. There?s still more left in the RE, though, and the > can?t match at the end of the string, so the regular expression engine has to backtrack character by character until it finds a match for the >. The final match extends from the '<' in to the '>' in , which isn?t what you want. In this case, the solution is to use the non-greedy qualifiers *?, +?, ??, or {m,n}?, which match as little text as possible. In the above example, the '>' is tried immediately after the first '<' matches, and when it fails, the engine advances a character at a time, retrying the '>' at every step. This produces just the right result: >>> >>> print re.match('<.*?>', s).group() From stareq13 at yahoo.com Tue Feb 18 21:06:08 2014 From: stareq13 at yahoo.com (S Tareq) Date: Tue, 18 Feb 2014 20:06:08 +0000 (GMT) Subject: [Tutor] cx_freeze windows 7 python 3.3 In-Reply-To: References: <1392724793.49605.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: <1392753968.14998.YahooMailNeo@web133101.mail.ir2.yahoo.com> does any one know how to use 2to3 program to convert 2.7 python coding 3.X please i need help sorry??thank you? -------------- next part -------------- An HTML attachment was scrubbed... URL: From stareq13 at yahoo.com Tue Feb 18 21:06:17 2014 From: stareq13 at yahoo.com (S Tareq) Date: Tue, 18 Feb 2014 20:06:17 +0000 (GMT) Subject: [Tutor] Using for loops for combinations In-Reply-To: References: Message-ID: <1392753977.48806.YahooMailNeo@web133101.mail.ir2.yahoo.com> does any one know how to use 2to3 program to convert 2.7 python coding 3.X please i need help sorry??thank you? On Tuesday, 18 February 2014, 19:18, Danny Yoo wrote: On Tue, Feb 18, 2014 at 8:37 AM, Chinanu 'Chinex' Onyekachi wrote: > Find all possible combinations of a specific word (string) using any > combination of upper case and lower case letters with a for loop (no > itertools). > > > An example: > > string_input = hat > > comboination = ['hat', 'Hat', 'HAt', 'HAT', 'hAT', 'haT', 'HaT', 'hAt'] [code cut] This appears to be homework, so unfortunately the help that can be provided will need to be limited; otherwise there's a risk of violating your institution's Honor Code. Can you talk more about what difficulty are you running into? _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Feb 18 21:14:54 2014 From: emile at fenx.com (Emile van Sebille) Date: Tue, 18 Feb 2014 12:14:54 -0800 Subject: [Tutor] Regular expression - I In-Reply-To: References: <089DADDD-0364-4C97-B79E-9B4D25FD938A@alchemy.com> Message-ID: On 2/18/2014 11:42 AM, Mark Lawrence wrote: > On 18/02/2014 18:03, Steve Willoughby wrote: >> Because the regular expression means ?match an angle-bracket > Please do not top post on this list. Appropriate trimming is also appreciated. Emile From stareq13 at yahoo.com Tue Feb 18 21:18:02 2014 From: stareq13 at yahoo.com (S Tareq) Date: Tue, 18 Feb 2014 20:18:02 +0000 (GMT) Subject: [Tutor] could please convert this code to 3.X by using 2to3 Message-ID: <1392754682.19163.YahooMailNeo@web133104.mail.ir2.yahoo.com> i am to convert coding to python 3.X. and some one told me to use 2to3 program but ?i don't how to use 2to3 program i was reading and followed the rules in python website ( http://docs.python.org/3/library/2to3.html?highlight=2to3#module-lib2to3 ) but it says error and don't work. is there any other way to convert. the original coding is used 2.7 python version. can you please help to convert this in any way. **sorry for bad English** ?this is the coding: ? def quiz(): ? ? print ("welcome") ? ? print ("""This is a quiz which will help you to learn and revise the different Biology keywords and their definitions. The question will be ?repeated continuously until you have correctly matched every keyword with its definition exactly twice. Good luck! """) ? ? choose = int(input("1) Start Quiz ?2) Exit Program ")) ? ? if choose == 1: ? ? ? ? quiz2() ? ? elif choose == 2: ? ? ? ? quit() def quiz2(): ? ? # Import statements ? ? import random ? ? import datetime ? ? #Arrays to store the definitions and keywords read from the file ? ? keywords=[]; ? ? definition=[]; ? ? correctAnswer=[]; ? ? #Counter for the wrong Answer and counter of number of definition in ? ? wrongAnswer=0; ? ? counter=0; ? ? # Taking User input for accepting the file name to be read ? ? filename= raw_input("Enter the File Name with extension ?") ? ? #Reading the file from start to the end ? ? for line in open(filename,'r').readlines(): ? ? ? ? if(counter%2==0): ? ? ? ? ? ? keywords.append(line); ? ? ? ? ? ? counter=counter+1; ? ? ? ? ? ? correctAnswer.append(0) ? ? ? ? else: ? ? ? ? ? ? definition.append(line); ? ? ? ? ? ? keys=[]; ? ? ? ? ? ? keys=line.split(" "); ? ? ? ? ? ? counter=counter+1; ? ? # Running two while loops to make the pattern recursive ? ? while True: ? ? # Starting the time for quiz and also, creating variables to make sure that same sequences and answers are not repeated ? ? ? ? a = datetime.datetime.now().replace(microsecond=0) ? ? ? ? prevWord=0 ? ? ? ? prevSeq=0 ? ? ? ? # While loop to run the code till each answer is correctly answered ? ? ? ? while correctAnswer.count(2)!=(counter/2): ? ? ? ? ? ? #While loop to generate an different random number from one the generated previously ? ? ? ? ? ? while True: ? ? ? ? ? ? ? ? word=random.randint(0,(counter/2)-1) ? ? ? ? ? ? ? ? if(correctAnswer[word]!=2): ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? ? if(prevWord==word): ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? # Displaying the new keyword each time. ? ? ? ? ? ? print "Please Select the number which is the correct definition of the word:" ,keywords[word] ? ? ? ? ? ? #Generating an new sequence each time different from previous one ? ? ? ? ? ? while True: ? ? ? ? ? ? ? ? sequences =random.randint(0,2) ? ? ? ? ? ? ? ? if(prevSeq==sequences): ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? ? ? break ? ? ? ? ? ? #Generating an new incorrect answer each time different from previous one ? ? ? ? ? ? while True: ? ? ? ? ? ? ? ? incorrectAnswer=random.randint(0,len(correctAnswer)-1) ? ? ? ? ? ? ? ? if(incorrectAnswer==word): ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? else : ? ? ? ? ? ? ? ? ? ? break ? ? ? ? ? ? #Generating an new incorrect answer ?each time different from previous one ? ? ? ? ? ? while True: ? ? ? ? ? ? ? ? incorrectAnswerSecond=random.randint(0,len(correctAnswer)-1); ? ? ? ? ? ? ? ? if (incorrectAnswer==incorrectAnswerSecond): ? ? ? ? ? ? ? ? ? ? continue ? ? ? ? ? ? ? ? if(incorrectAnswerSecond==word): ? ? ? ? ? ? ? ? ? ? continue ? ? ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? ? ? break ? ? ? ? ? ? # Displaying the options to the user based on the sequence number generated ? ? ? ? ? ? if (sequences==0): ? ? ? ? ? ? ? ? print "1.",definition[word] ? ? ? ? ? ? ? ? print "2.",definition[incorrectAnswer] ? ? ? ? ? ? ? ? print "3.",definition[incorrectAnswerSecond] ? ? ? ? ? ? elif (sequences==1): ? ? ? ? ? ? ? ? print "1.",definition[incorrectAnswer] ? ? ? ? ? ? ? ? print "2.",definition[incorrectAnswerSecond] ? ? ? ? ? ? ? ? print "3.",definition[word] ? ? ? ? ? ? elif (sequences==2): ? ? ? ? ? ? ? ? print "1.",definition[incorrectAnswerSecond] ? ? ? ? ? ? ? ? print "2.",definition[word] ? ? ? ? ? ? ? ? print "3.",definition[incorrectAnswer] ? ? ? ? ? ? #Taking the answer from user ? ? ? ? ? ? answer = raw_input("Enter the Correct Number between 1 to 3 ") ? ? ? ? ? ? # Assign the seq and word to preseq and word ? ? ? ? ? ? prevSeq=sequences ? ? ? ? ? ? prevWord=word ? ? ? ? ? ? #Checking the answer if they are corret. ? ? ? ? ? ? if(0 == sequences): ? ? ? ? ? ? ? ? if(answer == "1"): ? ? ? ? ? ? ? ? ? ? print "success" ? ? ? ? ? ? ? ? ? ? correctAnswer[word]=correctAnswer[word]+1 ? ? ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? ? ? print "Wrong Answer" ? ? ? ? ? ? ? ? ? ? print "Correct Answer: " ,definition[word] ? ? ? ? ? ? ? ? ? ? wrongAnswer=wrongAnswer+1; ? ? ? ? ? ? elif(1 == sequences): ? ? ? ? ? ? ? ? if(answer == "3"): ? ? ? ? ? ? ? ? ? ? print "success" ? ? ? ? ? ? ? ? ? ? correctAnswer[word]=correctAnswer[word]+1 ? ? ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? ? ? print "Wrong Answer" ? ? ? ? ? ? ? ? ? ? print "Correct Answer: " ,definition[word] ? ? ? ? ? ? ? ? ? ? wrongAnswer=wrongAnswer+1; ? ? ? ? ? ? elif(2 == sequences): ? ? ? ? ? ? ? ? if(answer == "2"): ? ? ? ? ? ? ? ? ? ? print "success" ? ? ? ? ? ? ? ? ? ? correctAnswer[word]=correctAnswer[word]+1 ? ? ? ? ? ? ? ? else: ? ? ? ? ? ? ? ? ? ? print "Wrong Answer" ? ? ? ? ? ? ? ? ? ? print "Correct Answer: " ,definition[word] ? ? ? ? ? ? ? ? ? ? wrongAnswer=wrongAnswer+1 ? ? ? ? # Stopping the time of the clock ? ? ? ? b = datetime.datetime.now().replace(microsecond=0) ? ? ? ? # displaying number of wrong answer and total quiz time ? ? ? ? print "Total Number of Wrong Answer:", wrongAnswer ? ? ? ? print "Total Quiz Time", (b-a) ? ? ? ? #asking user to reenter ? ? ? ? restart= raw_input("Do You want to start the quiz again Yes or No ") ? ? ? ? if(restart=="No"): ? ? ? ? ? ? print "Thanks for quiz" ? ? ? ? ? ? break; ? ? ? ? elif(restart=="Yes"): ? ? ? ? ? ? wrongAnswer=0 ? ? ? ? ? ? correctAnswer=[]; ? ? ? ? ? ? i=0 ? ? ? ? ? ? while (i<(counter/2)): ? ? ? ? ? ? ? ? i=i+1 ? ? ? ? ? ? ? ? correctAnswer.append(0) quiz() -------------- next part -------------- An HTML attachment was scrubbed... URL: From zachary.ware+pytut at gmail.com Tue Feb 18 21:41:27 2014 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Tue, 18 Feb 2014 12:41:27 -0800 Subject: [Tutor] could please convert this code to 3.X by using 2to3 In-Reply-To: <1392754682.19163.YahooMailNeo@web133104.mail.ir2.yahoo.com> References: <1392754682.19163.YahooMailNeo@web133104.mail.ir2.yahoo.com> Message-ID: On Tue, Feb 18, 2014 at 12:18 PM, S Tareq wrote: > i am to convert coding to python 3.X. and some one told me to use 2to3 > program but i don't how to use 2to3 program i was reading and followed the > rules in python website ( > http://docs.python.org/3/library/2to3.html?highlight=2to3#module-lib2to3 ) > but it says error and don't work. is there any other way to convert. the > original coding is used 2.7 python version. can you please help to convert > this in any way. **sorry for bad English** this is the coding: A few general points to try to help you: - Don't spam the same question in several different threads, and especially don't privately email list participants with the same question. Doing so is likely to get you ignored by people who would otherwise be quite happy to help you. - Don't ask people on this list to do something for you. We're here to teach, not do. - When you have an error, post the exact error, in context. If it's a shell (including Windows Command Prompt) error, give the command line you tried. If it's a Python traceback, give the whole traceback. Don't try to retype the error, copy and paste it. If you're on Windows and can't copy from the Command Prompt, use "Mark" from the right click menu, and press Enter when you have highlighted what you want to copy. Without knowing what the error is, "it says error and don't work" could mean any number of things. - Try reading this: http://docs.python.org/3/howto/pyporting.html#use-2to3 - Keep in mind that there are some things that the 2to3 tool can't convert, and so you may have to do some editing before or after conversion, or both. - Post in plain text, not HTML. Some responders here don't get the message at all if it includes HTML, and it's annoying to several others. We try to be friendly around here, but sometimes the most friendliness we (individually) can muster is to ignore posts that annoy us. Help us help you, and we'll be happy to teach you whatever you need to know! -- Zach From stareq13 at yahoo.com Tue Feb 18 21:57:32 2014 From: stareq13 at yahoo.com (S Tareq) Date: Tue, 18 Feb 2014 20:57:32 +0000 (GMT) Subject: [Tutor] could please convert this code to 3.X by using 2to3 In-Reply-To: References: <1392754682.19163.YahooMailNeo@web133104.mail.ir2.yahoo.com> Message-ID: <1392757052.56881.YahooMailNeo@web133103.mail.ir2.yahoo.com> sorry, is there any other way to convert the coding On Tuesday, 18 February 2014, 20:41, Zachary Ware wrote: On Tue, Feb 18, 2014 at 12:18 PM, S Tareq wrote: > i am to convert coding to python 3.X. and some one told me to use 2to3 > program but? i don't how to use 2to3 program i was reading and followed the > rules in python website ( > http://docs.python.org/3/library/2to3.html?highlight=2to3#module-lib2to3 ) > but it says error and don't work. is there any other way to convert. the > original coding is used 2.7 python version. can you please help to convert > this in any way. **sorry for bad English**? this is the coding: A few general points to try to help you: - Don't spam the same question in several different threads, and especially don't privately email list participants with the same question.? Doing so is likely to get you ignored by people who would otherwise be quite happy to help you. - Don't ask people on this list to do something for you.? We're here to teach, not do. - When you have an error, post the exact error, in context.? If it's a shell (including Windows Command Prompt) error, give the command line you tried.? If it's a Python traceback, give the whole traceback. Don't try to retype the error, copy and paste it.? If you're on Windows and can't copy from the Command Prompt, use "Mark" from the right click menu, and press Enter when you have highlighted what you want to copy.? Without knowing what the error is, "it says error and don't work" could mean any number of things. - Try reading this: http://docs.python.org/3/howto/pyporting.html#use-2to3 - Keep in mind that there are some things that the 2to3 tool can't convert, and so you may have to do some editing before or after conversion, or both. - Post in plain text, not HTML.? Some responders here don't get the message at all if it includes HTML, and it's annoying to several others.? We try to be friendly around here, but sometimes the most friendliness we (individually) can muster is to ignore posts that annoy us.? Help us help you, and we'll be happy to teach you whatever you need to know! -- Zach _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Tue Feb 18 22:35:18 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 18 Feb 2014 21:35:18 +0000 Subject: [Tutor] could please convert this code to 3.X by using 2to3 In-Reply-To: <1392757052.56881.YahooMailNeo@web133103.mail.ir2.yahoo.com> References: <1392754682.19163.YahooMailNeo@web133104.mail.ir2.yahoo.com> <1392757052.56881.YahooMailNeo@web133103.mail.ir2.yahoo.com> Message-ID: On 18/02/2014 20:57, S Tareq wrote: > sorry, is there any other way to convert the coding > Use an editor? Or try this:- c:\Users\Mark>2to3 --help Usage: 2to3 [options] file|dir ... Options: -h, --help show this help message and exit -d, --doctests_only Fix up doctests only -f FIX, --fix=FIX Each FIX specifies a transformation; default: all -j PROCESSES, --processes=PROCESSES Run 2to3 concurrently -x NOFIX, --nofix=NOFIX Prevent a transformation from being run -l, --list-fixes List available transformations -p, --print-function Modify the grammar so that print() is a function -v, --verbose More verbose logging --no-diffs Don't show diffs of the refactoring -w, --write Write back modified files -n, --nobackups Don't write backups for modified files -o OUTPUT_DIR, --output-dir=OUTPUT_DIR Put output files in this directory instead of overwriting the input files. Requires -n. -W, --write-unchanged-files Also write files even if no changes were required (useful with --output-dir); implies -w. --add-suffix=ADD_SUFFIX Append this string to all output filenames. Requires -n if non-empty. ex: --add-suffix='3' will generate .py3 files. And please *DON'T* top post. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From dyoo at hashcollision.org Tue Feb 18 22:57:26 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 18 Feb 2014 13:57:26 -0800 Subject: [Tutor] could please convert this code to 3.X by using 2to3 In-Reply-To: References: <1392754682.19163.YahooMailNeo@web133104.mail.ir2.yahoo.com> Message-ID: > > - Don't spam the same question in several different threads, and > especially don't privately email list participants with the same > question. Doing so is likely to get you ignored by people who would > otherwise be quite happy to help you. I'd like to make that comment stronger: by repeating the same question over and over, the questioner is giving the impression of a petulant child. I _know_ that's not the intent of the original questioner. But I have to say exactly what kind of impression I'm getting from this. Sometimes the person making the mistake doesn't realize how bad of a mistake they're making. The guidelines in: http://www.catb.org/~esr/faqs/smart-questions.html are that: just guidelines. But there's a good reason they're there, because violating them makes it much more difficult to get good answers from a group of enthusiast volunteers. It makes them less enthusiastic. I don't think there's been any other changes to the question as originally asked since back in January, right? https://mail.python.org/pipermail/tutor/2014-January/099466.html In fact, when the question was asked again a few days later, I tried the automatic 2to3 translator on the program. I had no problem with it: it translated directly. https://mail.python.org/pipermail/tutor/2014-January/099591.html So it begs the question: doesn't that kill the problem? The natural followup would be: why isn't the original questioner using 2to3? Are they having a problem with the tool? So we asked, but we never got a satisfactory answer to that question: the original questioner ignored us. And again, the original questioner asked the same exact question a few days later: https://mail.python.org/pipermail/tutor/2014-January/099708.html with a similar response. So I'm inclined to give it one more shot. S Tareq, why not use "2to3"? From denis.spir at gmail.com Tue Feb 18 23:55:46 2014 From: denis.spir at gmail.com (spir) Date: Tue, 18 Feb 2014 23:55:46 +0100 Subject: [Tutor] Regular expression - I In-Reply-To: References: Message-ID: <5303E4F2.9090404@gmail.com> On 02/18/2014 08:39 PM, Zachary Ware wrote: > Hi Santosh, > > On Tue, Feb 18, 2014 at 9:52 AM, Santosh Kumar wrote: >> >> Hi All, >> >> If you notice the below example, case I is working as expected. >> >> Case I: >> In [41]: string = "test" >> >> In [42]: re.match('',string).group() >> Out[42]: '' >> >> But why is the raw string 'r' not working as expected ? >> >> Case II: >> >> In [43]: re.match(r'',string).group() >> --------------------------------------------------------------------------- >> AttributeError Traceback (most recent call last) >> in () >> ----> 1 re.match(r'',string).group() >> >> AttributeError: 'NoneType' object has no attribute 'group' >> >> In [44]: re.match(r'',string) > > It is working as expected, but you're not expecting the right thing > ;). Raw strings don't escape anything, they just prevent backslash > escapes from expanding. Case I works because "\*" is not a special > character to Python (like "\n" or "\t"), so it leaves the backslash in > place: > > >>> '' > '' > > The equivalent raw string is exactly the same in this case: > > >>> r'' > '' > > The raw string you provided doesn't have the backslash, and Python > will not add backslashes for you: > > >>> r'' > '' > > The purpose of raw strings is to prevent Python from recognizing > backslash escapes. For example: > > >>> path = 'C:\temp\new\dir' # Windows paths are notorious... > >>> path # it looks mostly ok... [1] > 'C:\temp\new\\dir' > >>> print(path) # until you try to use it > C: emp > ew\dir > >>> path = r'C:\temp\new\dir' # now try a raw string > >>> path # Now it looks like it's stuffed full of backslashes [2] > 'C:\\temp\\new\\dir' > >>> print(path) # but it works properly! > C:\temp\new\dir > > [1] Count the backslashes in the repr of 'path'. Notice that there is > only one before the 't' and the 'n', but two before the 'd'. "\d" is > not a special character, so Python didn't do anything to it. There > are two backslashes in the repr of "\d", because that's the only way > to distinguish a real backslash; the "\t" and "\n" are actually the > TAB and LINE FEED characters, as seen when printing 'path'. > > [2] Because they are all real backslashes now, so they have to be > shown escaped ("\\") in the repr. > > In your regex, since you're looking for, literally, "", you'll > need to backslash escape the "*" since it is a special character *in > regular expressions*. To avoid having to keep track of what's special > to Python as well as regular expressions, you'll need to make sure the > backslash itself is escaped, to make sure the regex sees "\*", and the > easiest way to do that is a raw string: > > >>> re.match(r'', string).group() > '' > > I hope this makes some amount of sense; I've had to write it up > piecemeal and will never get it posted at all if I don't go ahead and > post :). If you still have questions, I'm happy to try again. You > may also want to have a look at the Regex HowTo in the Python docs: > http://docs.python.org/3/howto/regex.html In addition to all this: * You may confuse raw strings with "regex escaping" (a tool func that escapes special regex characters for you). * For simplicity, always use raw strings for regex formats (as in your second example); this does not prevent you to escape special characters, but you only have to do it once! d From dyoo at hashcollision.org Wed Feb 19 03:14:45 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 18 Feb 2014 18:14:45 -0800 Subject: [Tutor] Using for loops for combinations In-Reply-To: References: Message-ID: On Tue, Feb 18, 2014 at 5:15 PM, Chinanu 'Chinex' Onyekachi wrote: > I?m having difficulties uppercasing a single portion (e.g. hAt) and two > portions (e.g. HaT) of the string. [Adding tutor at python.org to CC. Please use reply-to-all in future emails on this list. Thanks!] Hi Chinanu, There is a crucial key to this problem. You must work with a _simpler problem_ and a _partial solution_, and keeping it up to date as you learn more and more about the problem and solution. What does a "simpler problem" mean here? What does a "partial solution" mean? Let's take the case where we're trying to compute the combinations for "hat". Let's call this C("hat"). From your problem statement about, we know what C("hat") looks like. Here's a subquestion of C("hat"): what are the combinations for "h"? That is, what do we know about C("h")? C("h") --> ["h", "H"] Trivial case, but worth thinking about. Here's another subquestion of C("hat"): what are the combinations for "ha"? That is, what do we know about C("ha")? C("ha") --> ["ha", "Ha", "hA", "HA"] This we know without having to do any coding. But it's worth thinking: can we get C("ha") easily out of C("h")? Yes. Just take the results of C("h"), and put "a" or "A" at the end of each. C("h") --> ["h", "H"] C("ha") --> ["ha", "hA", "Ha", "HA"] Here's another subquestion of C("hat"): what are the combinations for "hat"? But it's worth thinking: can we get C("hat") easily out of C("ha")? Yes. Hopefully that sketches out what I think is the intent of this problem. From dyoo at hashcollision.org Wed Feb 19 03:56:24 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 18 Feb 2014 18:56:24 -0800 Subject: [Tutor] Using for loops for combinations In-Reply-To: References: Message-ID: On Tue, Feb 18, 2014 at 6:34 PM, Chinanu 'Chinex' Onyekachi wrote: > Thanks for taking you time to explain. > > minus = ['subtract'] #creates a list for subtract > > > for i in minus: > > minuslist1 = [i[0].upper() + i[1:]] > > minuslist2 = [i[0] + i[1].upper() + i[2:]] > > minuslist3 = [i[0:].upper()] > > minus.extend(minuslist1) > > minus.extend(minuslist2) > > minus.extend(minuslist3) > > print 'list is: %r' % (minus ,), > > I get this output ['subtract', 'Subtract', 'sUbtract', 'SUBTRACT'] > but I feel it is going to take ages to do it this way and get all the > possible combinations. Would use another for loop be the only way to speed > things up, and if so how? I?m clearly struggling at forming loops. Please read: http://www.catb.org/~esr/faqs/smart-questions.html#uselists Also, if you have worked all night on this particular problem, as mentioned in the Stack Overflow question you posted, http://stackoverflow.com/questions/21856705/find-all-possible-combinations-of-a-specific-word-string-using-any-combination then know that you are probably not in a good frame of mind for understanding the problem. Take a break from it today, and talk to your instructor the next day if you are still confused. Also note that if you are trying to normalize input, it's usually the case that you want to clean it up, rather than have to deal with it with all its messiness. For example, if you're trying to read: "uppercase" or "UpperCase" or "UPPERCASE" or ... in all its varieties in a uniform way, then just upper() the input. Normalize it. That kind of data digestion makes case analysis easier sometimes. Why do you think that computer systems use UPPERCASE sometimes? From rhce.san at gmail.com Wed Feb 19 04:36:43 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Wed, 19 Feb 2014 09:06:43 +0530 Subject: [Tutor] Regular expression - I In-Reply-To: <5303E4F2.9090404@gmail.com> References: <5303E4F2.9090404@gmail.com> Message-ID: Thank you all. I got it. :) I need to read more between lines . On Wed, Feb 19, 2014 at 4:25 AM, spir wrote: > On 02/18/2014 08:39 PM, Zachary Ware wrote: > >> Hi Santosh, >> >> On Tue, Feb 18, 2014 at 9:52 AM, Santosh Kumar >> wrote: >> >>> >>> Hi All, >>> >>> If you notice the below example, case I is working as expected. >>> >>> Case I: >>> In [41]: string = "test" >>> >>> In [42]: re.match('',string).group() >>> Out[42]: '' >>> >>> But why is the raw string 'r' not working as expected ? >>> >>> Case II: >>> >>> In [43]: re.match(r'',string).group() >>> ------------------------------------------------------------ >>> --------------- >>> AttributeError Traceback (most recent call >>> last) >>> in () >>> ----> 1 re.match(r'',string).group() >>> >>> AttributeError: 'NoneType' object has no attribute 'group' >>> >>> In [44]: re.match(r'',string) >>> >> >> It is working as expected, but you're not expecting the right thing >> ;). Raw strings don't escape anything, they just prevent backslash >> escapes from expanding. Case I works because "\*" is not a special >> character to Python (like "\n" or "\t"), so it leaves the backslash in >> place: >> >> >>> '' >> '' >> >> The equivalent raw string is exactly the same in this case: >> >> >>> r'' >> '' >> >> The raw string you provided doesn't have the backslash, and Python >> will not add backslashes for you: >> >> >>> r'' >> '' >> >> The purpose of raw strings is to prevent Python from recognizing >> backslash escapes. For example: >> >> >>> path = 'C:\temp\new\dir' # Windows paths are notorious... >> >>> path # it looks mostly ok... [1] >> 'C:\temp\new\\dir' >> >>> print(path) # until you try to use it >> C: emp >> ew\dir >> >>> path = r'C:\temp\new\dir' # now try a raw string >> >>> path # Now it looks like it's stuffed full of backslashes [2] >> 'C:\\temp\\new\\dir' >> >>> print(path) # but it works properly! >> C:\temp\new\dir >> >> [1] Count the backslashes in the repr of 'path'. Notice that there is >> only one before the 't' and the 'n', but two before the 'd'. "\d" is >> not a special character, so Python didn't do anything to it. There >> are two backslashes in the repr of "\d", because that's the only way >> to distinguish a real backslash; the "\t" and "\n" are actually the >> TAB and LINE FEED characters, as seen when printing 'path'. >> >> [2] Because they are all real backslashes now, so they have to be >> shown escaped ("\\") in the repr. >> >> In your regex, since you're looking for, literally, "", you'll >> need to backslash escape the "*" since it is a special character *in >> regular expressions*. To avoid having to keep track of what's special >> to Python as well as regular expressions, you'll need to make sure the >> backslash itself is escaped, to make sure the regex sees "\*", and the >> easiest way to do that is a raw string: >> >> >>> re.match(r'', string).group() >> '' >> >> I hope this makes some amount of sense; I've had to write it up >> piecemeal and will never get it posted at all if I don't go ahead and >> post :). If you still have questions, I'm happy to try again. You >> may also want to have a look at the Regex HowTo in the Python docs: >> http://docs.python.org/3/howto/regex.html >> > > In addition to all this: > * You may confuse raw strings with "regex escaping" (a tool func that > escapes special regex characters for you). > * For simplicity, always use raw strings for regex formats (as in your > second example); this does not prevent you to escape special characters, > but you only have to do it once! > > > d > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- D. Santosh Kumar RHCE | SCSA +91-9703206361 Every task has a unpleasant side .. But you must focus on the end result you are producing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Wed Feb 19 13:33:21 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 19 Feb 2014 12:33:21 +0000 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: On 18 February 2014 17:59, Peter Otten <__peter__ at web.de> wrote: > > I don't know if the OP may use it, but there seems to be a version of minuit > that allows to override the function signature: > > """ > forced_parameters: tell Minuit not to do function signature detection and > use this argument instead. (Default None (automagically detect signature) > """ Interesting. I don't really understand why it works that way though. Looking here http://iminuit.github.io/iminuit/api.html#function-sig-label I find the suggestion to do instead: """ f = lambda x,m,c: m*x+c #the beauty here is that all you need to build #a Chi^2 is just your function and data class GenericChi2: def __init__(self, f, x, y): self.f = f args = describe(f)#extract function signature self.func_code = Struct( co_varnames = args[1:],#dock off independent param co_argcount = len(args)-1 ) def __call__(self, *arg): return sum((self.f(x,*arg)-y)**2 for x,y in zip(self.x, self.y)) m = Minuit(GenericChi2(f,x,y)) """ But that just seems a bit ridiculous to me. If it were my library I would probably be aiming to handle complex cases with a closure-based solution like this: def make_chisq(f, xdata, ydata): def chisq(m, c): return sum((self.f(x,m, c)-y)**2 for x,y in zip(xdata, ydata)) return chisq f = lambda x,m,c: m*x+c m = Minuit(make_chisq(xdata, ydata), names=['m', 'c']) At the least I don't understand why it needs both the argument names and the number of arguments as independent quantities. Surely len(names) would be the number of arguments... Or am I missing something? BTW to the OP the functions in scipy.optimize don't do any of this. You just pass in the function and an initial guess at the parameter values. It doesn't care about the names and infers the number of parameters from the initial guess. Also numpy has a polyfit function that you can just call with polyfit(xdata, ydata, deg) where deg is the degree of the polynomial you want to fit. Under the hood it solves the scaled Vandermonde matrix as I described earlier: https://github.com/numpy/numpy/blob/master/numpy/polynomial/polynomial.py#L1351 Oscar From davea at davea.name Wed Feb 19 13:57:04 2014 From: davea at davea.name (Dave Angel) Date: Wed, 19 Feb 2014 07:57:04 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: <5304AA20.4050101@davea.name> On 02/19/2014 07:33 AM, Oscar Benjamin wrote: > > At the least I don't understand why it needs both the argument names > and the number of arguments as independent quantities. Surely > len(names) would be the number of arguments... Or am I missing > something? > In the standard library, the attributes are func_code.co_varnames and func_code.co_argcount Note that varnames will include all the locals, not just the formal parameters. So the count tells you how many of them are parameters. -- DaveA From eryksun at gmail.com Wed Feb 19 16:17:46 2014 From: eryksun at gmail.com (eryksun) Date: Wed, 19 Feb 2014 10:17:46 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: On Wed, Feb 19, 2014 at 7:33 AM, Oscar Benjamin wrote: > I don't really understand why it works that way though. > Looking here > > http://iminuit.github.io/iminuit/api.html#function-sig-label This API is unusual, but co_argcount and co_varnames should be available and defined as per the spec: http://docs.python.org/2/reference/datamodel#index-59 CPython/PyPy Jython ========================= co_name * co_argcount * co_nlocals * co_varnames * co_cellvars * co_freevars * co_filename * co_firstlineno * co_flags * co_code co_consts co_names co_lnotab co_stacksize The last few attributes aren't relevant to Jython since it's using the JVM. To its credit, util.better_arg_spec does fall back on inspect.getargspec. But then, its ultimate fallback is regex magic: util.arguments_from_docstring. Wow. I guess it's convenient to specify initial values, step size, limits, etc, as keyword arguments for named parameters. I haven't read this whole thread, but here are some source links if the OP is using this iminuit package. The `describe` function is in util.py. https://github.com/iminuit/iminuit/blob/master/iminuit/util.py https://github.com/iminuit/iminuit/blob/master/iminuit/_libiminuit.pyx Some snippets from Minuit.__init__: args = describe(fcn) if forced_parameters is None\ else forced_parameters # ... self.initialvalue = {x:maplookup(kwds,x,0.) for x in args} self.initialerror = \ {x:maplookup(kwds,'error_'+x,1.) for x in args} self.initiallimit = \ {x:maplookup(kwds,'limit_'+x,None) for x in args} self.initialfix = \ {x:maplookup(kwds,'fix_'+x,False) for x in args} # ... self.parameters = args self.args = tuple(self.initialvalue[k] for k in args) self.values = {k:self.initialvalue[k] for k in args} self.errors = {k:self.initialerror[k] for k in args} From nupurgoel at qainfotech.net Wed Feb 19 14:22:09 2014 From: nupurgoel at qainfotech.net (Nupur Goel) Date: Wed, 19 Feb 2014 18:52:09 +0530 Subject: [Tutor] How to write Sikuli scripts using Python in Eclipse (Pydev Environment.) Message-ID: Hi, Could you please tell me how to write Sikuli scripts using Python in Eclipse (Pydev Environment.) For Example: I want to open Adobe Reader using Sikuli and wants to perform different action on it. I had already integrated Python in Eclipse and also provide path for Jython Interpreter. Please provide me steps to import Sikuli Api's or other extra things needed to do my assignment. Thanks a lot in advance. Nupur -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 19 18:34:35 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Feb 2014 17:34:35 +0000 Subject: [Tutor] How to write Sikuli scripts using Python in Eclipse (Pydev Environment.) In-Reply-To: References: Message-ID: On 19/02/14 13:22, Nupur Goel wrote: > Could you please tell me how to write *Sikuli* scripts using *Python in > Eclipse (Pydev Environment.)* This list is for teaching the core Python language and its standard library. For support for third party libraries and tools you are usually better off asking on a dedicated forum or list. > I want to open Adobe Reader using Sikuli and wants to perform different > action on it. > I had already integrated Python in Eclipse and also provide path for > Jython Interpreter. Sikuli, Eclipse and Jython are all off topic for this list. You might be lucky enough to find somebody with some experience but I suspect you will be better off asking elsewhere, possibly even on the main python mailing list/newsgroup. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From walksloud at gmail.com Wed Feb 19 20:46:42 2014 From: walksloud at gmail.com (=?windows-1252?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ec?= =?windows-1252?Q?om=3E=22?=) Date: Wed, 19 Feb 2014 14:46:42 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: <7C0CBDAF-AB67-4A4D-9DFF-A02A6D2EFD46@gmail.com> Message-ID: <5A438E59-B714-4AAC-AE1A-CFD95B4066E8@gmail.com> Hi Oscar, >> Is there a benefit to this method vs a standard linear least squares? > > It's the same except that you're using an analytic solution rather > than a black box solver. OK. Interesting. I usually construct the analytic solution by just differentiating the chi^2, which sets up, I am guessing, a similar matrix equation. When I solve with chi^2, I see clearly how to put the uncertainties in, and use them for estimating the uncertainties on the coefficients. The parameter uncertainties are simply related to the double-derrivatives of the chi^2 for linear least squares. But it is not clear to me if knowing the Vandermonde matrix automatically gives these parameter uncertainties as well. >> The most common problem I am solving is fitting a sum of real exponentials to noisy data, with the model function >> >> C(t) = sum_n A_n e^{- E_n t} >> >> the quantities of most interest are E_n, followed by A_n so I solve this with non-linear regression. >> To stabilize the fit, I usually do a linear-least squares for the A_n first, solving as a function of the E_n, and then do a non-linear fit for the E_n. > > That doesn't sound optimal to me. Maybe I've misunderstood but fitting > over one variable and then over another is not in any way guaranteed > to produce an optimal fit. I have not been precise enough. The first solve for A_n is using an analytic linear-least squares algorithm, so it is gauranteed to be correct. The solution will depend upon the E_n, but in a known way. The point is that the numerical minimization of sums of exponentials is a hard problem. So why ask the numerical minimizer to do all the extra work of also minimizing the coefficients? This can make it very unstable. So by first applying the analytic linear-least squares to the coefficients, the numerical minimization over the smaller set of E_n is more likely to converge. Usually, in my cases, we have of order 2-10 times more A_n than E_n, as we really solve a matrix C_{ij}(t) = sum_n A^n_{ij} exp(-E_n t) the linear least squares gives A^n_{ij} = analytically solvable matrix function (E_n) > Well it sounds like your approach so far is working for now but as I > say the real fix is to improve or bypass the interface you're using. > One limitation that you may at some point hit is that in Python you > can't have an unbounded number of formal parameters for a function: > > $ python3 tmp2.py > File "tmp2.py", line 1 > def f(x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, > x12, x13, x14, > ^ > SyntaxError: more than 255 arguments In my work, it is unlikely I will ever need to minimize in so many parameters. I?ll worry about that when I run into it. Thanks for the info. Andre From walksloud at gmail.com Wed Feb 19 20:56:19 2014 From: walksloud at gmail.com (=?iso-8859-1?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ecom?= =?iso-8859-1?Q?=3E=22?=) Date: Wed, 19 Feb 2014 14:56:19 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: Hi eryksun, Indeed, I am using iminuit to interface with Minuit. That is where I am learning to make my own classes to set up my functions to pass into the minimizer. I also happened to get the string-hack to work (which requires using global variables). Instead of just copying (since it works) I am also trying to improve my programming knowledge at the same time - hence this whole thread. Minuit is a sophisticated minimizer, which means it is important to set initial values, expected uncertainties on the parameters, etc. Minuit uses your estimate of the parameter uncertainties to set up the grid step-size it uses to search the parameter space. So sloppiness here can screw up the minimization getting one stuck in a local min (to small error estimate) or spend too much time wondering around (too large error estimate). Cheers, Andre On Feb 19, 2014, at 10:17 AM, eryksun wrote: > On Wed, Feb 19, 2014 at 7:33 AM, Oscar Benjamin > wrote: >> I don't really understand why it works that way though. >> Looking here >> >> http://iminuit.github.io/iminuit/api.html#function-sig-label > > This API is unusual, but co_argcount and co_varnames should be > available and defined as per the spec: > > http://docs.python.org/2/reference/datamodel#index-59 > > CPython/PyPy Jython > ========================= > co_name * > co_argcount * > co_nlocals * > co_varnames * > co_cellvars * > co_freevars * > co_filename * > co_firstlineno * > co_flags * > co_code > co_consts > co_names > co_lnotab > co_stacksize > > The last few attributes aren't relevant to Jython since it's using the JVM. > > To its credit, util.better_arg_spec does fall back on > inspect.getargspec. But then, its ultimate fallback is regex magic: > util.arguments_from_docstring. Wow. I guess it's convenient to specify > initial values, step size, limits, etc, as keyword arguments for named > parameters. > > I haven't read this whole thread, but here are some source links if > the OP is using this iminuit package. The `describe` function is in > util.py. > > https://github.com/iminuit/iminuit/blob/master/iminuit/util.py > https://github.com/iminuit/iminuit/blob/master/iminuit/_libiminuit.pyx > > Some snippets from Minuit.__init__: > > args = describe(fcn) if forced_parameters is None\ > else forced_parameters > > # ... > > self.initialvalue = {x:maplookup(kwds,x,0.) for x in args} > self.initialerror = \ > {x:maplookup(kwds,'error_'+x,1.) for x in args} > self.initiallimit = \ > {x:maplookup(kwds,'limit_'+x,None) for x in args} > self.initialfix = \ > {x:maplookup(kwds,'fix_'+x,False) for x in args} > > # ... > > self.parameters = args > self.args = tuple(self.initialvalue[k] for k in args) > self.values = {k:self.initialvalue[k] for k in args} > self.errors = {k:self.initialerror[k] for k in args} From eryksun at gmail.com Wed Feb 19 22:56:31 2014 From: eryksun at gmail.com (eryksun) Date: Wed, 19 Feb 2014 16:56:31 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: On Wed, Feb 19, 2014 at 2:56 PM, "Andr? Walker-Loud " wrote: > > I also happened to get the string-hack to work (which requires > using global variables). Functions load unassigned names from the global/builtins scopes, so there's no need to declare the g* variables global in chisq_mn. Also, implicit string concatenation and string formatting will make the definition easier to read, IMO: def make_chisq_mn(pars, x, y, dy): global _gx, _gy, _gdy _gx, _gy, _gdy = x, y, dy names = ['c_%d' % i for i in xrange(len(pars))] src = ('def chisq_mn(%(p)s):\n' ' return chisq([%(p)s], _gx, _gy, _gdy)' % {'p': ', '.join(names)}) print 'funcdef=\n', src exec src in globals() You can use a custom dict with exec to avoid contaminating the module's global namespace: def make_chisq_mn(pars, x, y, dy): ns = {'x': x, 'y': y, 'dy': dy, 'chisq': chisq} names = ['c_%d' % i for i in xrange(len(pars))] src = ('def chisq_mn(%(p)s):\n' ' return chisq([%(p)s], x, y, dy)' % {'p': ', '.join(names)}) print 'funcdef=\n', src exec src in ns return ns['chisq_mn'] This version of chisq_mn uses the ns dict as its func_globals: >>> chisq = lambda *a: None # dummy >>> chisq_mn = make_chisq_mn([1,2,3], 10, 20, 30) funcdef= def chisq_mn(c_0, c_1, c_2): return chisq([c_0, c_1, c_2], x, y, dy) >>> sorted(chisq_mn.func_globals) ['__builtins__', 'chisq', 'chisq_mn', 'dy', 'x', 'y'] >>> dis.dis(chisq_mn) 2 0 LOAD_GLOBAL 0 (chisq) 3 LOAD_FAST 0 (c_0) 6 LOAD_FAST 1 (c_1) 9 LOAD_FAST 2 (c_2) 12 BUILD_LIST 3 15 LOAD_GLOBAL 1 (x) 18 LOAD_GLOBAL 2 (y) 21 LOAD_GLOBAL 3 (dy) 24 CALL_FUNCTION 4 27 RETURN_VALUE From walksloud at gmail.com Thu Feb 20 00:59:57 2014 From: walksloud at gmail.com (=?iso-8859-1?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ecom?= =?iso-8859-1?Q?=3E=22?=) Date: Wed, 19 Feb 2014 18:59:57 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: Message-ID: <4C4959CB-ACDF-4BEB-BC3E-24E54FFD40F1@gmail.com> Hi eryksun, Thanks - this is great. Also, since you are chiming in, do you have an opinion in general about which approach you prefer? The string hacking vs class method (for lack of better way to describe them)? Cheers, Andre On Feb 19, 2014, at 4:56 PM, eryksun wrote: > On Wed, Feb 19, 2014 at 2:56 PM, "Andr? Walker-Loud > " wrote: >> >> I also happened to get the string-hack to work (which requires >> using global variables). > > Functions load unassigned names from the global/builtins scopes, so > there's no need to declare the g* variables global in chisq_mn. Also, > implicit string concatenation and string formatting will make the > definition easier to read, IMO: > > def make_chisq_mn(pars, x, y, dy): > global _gx, _gy, _gdy > _gx, _gy, _gdy = x, y, dy > names = ['c_%d' % i for i in xrange(len(pars))] > src = ('def chisq_mn(%(p)s):\n' > ' return chisq([%(p)s], _gx, _gy, _gdy)' % > {'p': ', '.join(names)}) > print 'funcdef=\n', src > exec src in globals() > > > You can use a custom dict with exec to avoid contaminating the > module's global namespace: > > def make_chisq_mn(pars, x, y, dy): > ns = {'x': x, 'y': y, 'dy': dy, 'chisq': chisq} > names = ['c_%d' % i for i in xrange(len(pars))] > src = ('def chisq_mn(%(p)s):\n' > ' return chisq([%(p)s], x, y, dy)' % > {'p': ', '.join(names)}) > print 'funcdef=\n', src > exec src in ns > return ns['chisq_mn'] > > > This version of chisq_mn uses the ns dict as its func_globals: > >>>> chisq = lambda *a: None # dummy >>>> chisq_mn = make_chisq_mn([1,2,3], 10, 20, 30) > funcdef= > def chisq_mn(c_0, c_1, c_2): > return chisq([c_0, c_1, c_2], x, y, dy) > >>>> sorted(chisq_mn.func_globals) > ['__builtins__', 'chisq', 'chisq_mn', 'dy', 'x', 'y'] > >>>> dis.dis(chisq_mn) > 2 0 LOAD_GLOBAL 0 (chisq) > 3 LOAD_FAST 0 (c_0) > 6 LOAD_FAST 1 (c_1) > 9 LOAD_FAST 2 (c_2) > 12 BUILD_LIST 3 > 15 LOAD_GLOBAL 1 (x) > 18 LOAD_GLOBAL 2 (y) > 21 LOAD_GLOBAL 3 (dy) > 24 CALL_FUNCTION 4 > 27 RETURN_VALUE From alan.gauld at btinternet.com Thu Feb 20 01:16:01 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Feb 2014 00:16:01 +0000 Subject: [Tutor] How to write Sikuli scripts using Python in Eclipse (Pydev Environment.) In-Reply-To: References: Message-ID: On 19/02/14 17:34, Alan Gauld wrote: > Sikuli, Eclipse and Jython are all off topic for this list. Correcting myself. Jython is not off topic if it's about how to program with Jython. It's the details of using Jython in the context of Eclipse etc that is off topic for tutor. I don't want to scare away any Jython lurkers out there. :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From aurelien at hackers.guru Wed Feb 19 20:53:23 2014 From: aurelien at hackers.guru (=?utf-8?Q?Aur=C3=A9lien_DESBRI=C3=88RES?=) Date: Wed, 19 Feb 2014 20:53:23 +0100 Subject: [Tutor] Looking for IAC solutions in Python Message-ID: <87ppmikhfw.fsf@unicorn.home> Hi, I am looking for IAC - Intelligent Adaptive Curiosity solutions in Python. Have you got any idea of project / algorithm / source code based on that type of things ? Best regards -- Aur?lien DESBRI?RES Run Free - Run GNU.org From breamoreboy at yahoo.co.uk Thu Feb 20 01:27:27 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 20 Feb 2014 00:27:27 +0000 Subject: [Tutor] Looking for IAC solutions in Python In-Reply-To: <87ppmikhfw.fsf@unicorn.home> References: <87ppmikhfw.fsf@unicorn.home> Message-ID: On 19/02/2014 19:53, Aur?lien DESBRI?RES wrote: > > Hi, > > I am looking for IAC - Intelligent Adaptive Curiosity solutions in > Python. > > Have you got any idea of project / algorithm / source code based on that > type of things ? > > Best regards > > Haven't a clue to be quite blunt, I suggest that you try the main Python mailing list/newsgroup rather than this tutor list. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From eryksun at gmail.com Thu Feb 20 01:21:35 2014 From: eryksun at gmail.com (eryksun) Date: Wed, 19 Feb 2014 19:21:35 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: <4C4959CB-ACDF-4BEB-BC3E-24E54FFD40F1@gmail.com> References: <4C4959CB-ACDF-4BEB-BC3E-24E54FFD40F1@gmail.com> Message-ID: On Wed, Feb 19, 2014 at 6:59 PM, "Andr? Walker-Loud " wrote: > > Also, since you are chiming in, do you have an opinion in general about > which approach you prefer? The string hacking vs class method (for lack > of better way to describe them)? I've never used iminuit before. I'd ask on a support forum to see what other people are doing. That said, if possible I'd use a closure like Peter showed: def make_chisq_mn(x, y, dy): def chisq_mn(*args): return chisq(args, x, y, dy) return chisq_mn Then combine that with the forced_parameters option that Peter mentioned. This seems simplest to me. From walksloud at gmail.com Thu Feb 20 01:45:16 2014 From: walksloud at gmail.com (=?windows-1252?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ec?= =?windows-1252?Q?om=3E=22?=) Date: Wed, 19 Feb 2014 19:45:16 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: References: <4C4959CB-ACDF-4BEB-BC3E-24E54FFD40F1@gmail.com> Message-ID: <09E29FD5-537C-4D6B-AB2F-DFF200AEB951@gmail.com> OK - I have not seen an email from Peter. So I looked up the thread online, and see I did not receive half the emails on this thread :O My first inclination was to blame my mac mavericks mail gmail syncing problem. but logging into gmail, I see no record of the emails there either. I currently receive the tutor emails in the digest mode - thought I was paying attention to all the digests - but I seems to have missed many. I apologize to all those who offered input whose emails I missed - I certainly wasn?t ignoring them. Andre On Feb 19, 2014, at 7:21 PM, eryksun wrote: > On Wed, Feb 19, 2014 at 6:59 PM, "Andr? Walker-Loud > " wrote: >> >> Also, since you are chiming in, do you have an opinion in general about >> which approach you prefer? The string hacking vs class method (for lack >> of better way to describe them)? > > I've never used iminuit before. I'd ask on a support forum to see what > other people are doing. That said, if possible I'd use a closure like > Peter showed: > > def make_chisq_mn(x, y, dy): > def chisq_mn(*args): > return chisq(args, x, y, dy) > return chisq_mn > > Then combine that with the forced_parameters option that Peter > mentioned. This seems simplest to me. From walksloud at gmail.com Thu Feb 20 01:56:37 2014 From: walksloud at gmail.com (=?windows-1252?Q?=22Andr=E9_Walker-Loud_=3Cwalksloud=40gmail=2Ec?= =?windows-1252?Q?om=3E=22?=) Date: Wed, 19 Feb 2014 19:56:37 -0500 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: <09E29FD5-537C-4D6B-AB2F-DFF200AEB951@gmail.com> References: <4C4959CB-ACDF-4BEB-BC3E-24E54FFD40F1@gmail.com> <09E29FD5-537C-4D6B-AB2F-DFF200AEB951@gmail.com> Message-ID: <83AFA654-A26E-4675-9562-2C6C2299D596@gmail.com> On Feb 19, 2014, at 7:45 PM, Andr? Walker-Loud wrote: > OK - I have not seen an email from Peter. > So I looked up the thread online, and see I did not receive half the emails on this thread :O > > My first inclination was to blame my mac mavericks mail gmail syncing problem. but logging into gmail, I see no record of the emails there either. > > I currently receive the tutor emails in the digest mode - thought I was paying attention to all the digests - but I seems to have missed many. > > I apologize to all those who offered input whose emails I missed - I certainly wasn?t ignoring them. and as a follow up - is there a way to download a thread from the tutor archive? I am guessing the answers are one of 1) write a python script to grab the emails associated with the threads from the web 2) download the whole gzip?d text and use python to grab only the parts I want but 1) I haven?t done that before and unfortunately don?t have time to learn now 2) some combination of being too busy and lazy prevents me from this option? cheers, andre From breamoreboy at yahoo.co.uk Thu Feb 20 02:15:55 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 20 Feb 2014 01:15:55 +0000 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: <83AFA654-A26E-4675-9562-2C6C2299D596@gmail.com> References: <4C4959CB-ACDF-4BEB-BC3E-24E54FFD40F1@gmail.com> <09E29FD5-537C-4D6B-AB2F-DFF200AEB951@gmail.com> <83AFA654-A26E-4675-9562-2C6C2299D596@gmail.com> Message-ID: On 20/02/2014 00:56, "Andr? Walker-Loud " wrote: > On Feb 19, 2014, at 7:45 PM, Andr? Walker-Loud wrote: > >> OK - I have not seen an email from Peter. >> So I looked up the thread online, and see I did not receive half the emails on this thread :O >> >> My first inclination was to blame my mac mavericks mail gmail syncing problem. but logging into gmail, I see no record of the emails there either. >> >> I currently receive the tutor emails in the digest mode - thought I was paying attention to all the digests - but I seems to have missed many. >> >> I apologize to all those who offered input whose emails I missed - I certainly wasn?t ignoring them. > > and as a follow up - is there a way to download a thread from the tutor archive? > I am guessing the answers are one of > 1) write a python script to grab the emails associated with the threads from the web > 2) download the whole gzip?d text and use python to grab only the parts I want > > but 1) I haven?t done that before and unfortunately don?t have time to learn now > 2) some combination of being too busy and lazy prevents me from this option? > > > cheers, > > andre > See here for where this list is archived https://mail.python.org/mailman/listinfo/tutor, looks as if your choices are activestate or gmane, I'm unsure as to whether or not you can grab gzip'd text. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From oscar.j.benjamin at gmail.com Thu Feb 20 02:21:55 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 20 Feb 2014 01:21:55 +0000 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: <83AFA654-A26E-4675-9562-2C6C2299D596@gmail.com> References: <4C4959CB-ACDF-4BEB-BC3E-24E54FFD40F1@gmail.com> <09E29FD5-537C-4D6B-AB2F-DFF200AEB951@gmail.com> <83AFA654-A26E-4675-9562-2C6C2299D596@gmail.com> Message-ID: On 20 February 2014 00:56, "Andr? Walker-Loud " wrote: > On Feb 19, 2014, at 7:45 PM, Andr? Walker-Loud wrote: > >> OK - I have not seen an email from Peter. >> So I looked up the thread online, and see I did not receive half the emails on this thread :O >> >> My first inclination was to blame my mac mavericks mail gmail syncing problem. but logging into gmail, I see no record of the emails there either. >> >> I currently receive the tutor emails in the digest mode - thought I was paying attention to all the digests - but I seems to have missed many. >> >> I apologize to all those who offered input whose emails I missed - I certainly wasn't ignoring them. > > and as a follow up - is there a way to download a thread from the tutor archive? > I am guessing the answers are one of > 1) write a python script to grab the emails associated with the threads from the web > 2) download the whole gzip'd text and use python to grab only the parts I want > > but 1) I haven't done that before and unfortunately don't have time to learn now > 2) some combination of being too busy and lazy prevents me from this option... I'm sure there is a way to do it (I don't know how exactly) but for now you have the archive here: https://mail.python.org/pipermail/tutor/2014-February/100213.html I would suggest not to receive the digest. Peter's messages were sent to the list and not CC'ed to you (which is often considered the correct way) so you would only have seen them in the digest but it's not so easy to follow a thread that way. I also use gmail and what I do is to set a filter that sends all the tutor emails into a particular folder (skip inbox, don't mark as read) and then there's no problem with the emails cluttering up my inbox and no need to receive a digest. When I feel like looking at tutor emails they're in a particular folder for me to look at. When I feel like processing work-related emails etc. then they're in different folders. When I do look at the messages they are threaded by gmail so I don't miss anything in a particular thread. Oscar From ben+python at benfinney.id.au Thu Feb 20 03:00:26 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 20 Feb 2014 13:00:26 +1100 Subject: [Tutor] Programmatic access to email archives (was: constructing semi-arbitrary functions) References: <4C4959CB-ACDF-4BEB-BC3E-24E54FFD40F1@gmail.com> <09E29FD5-537C-4D6B-AB2F-DFF200AEB951@gmail.com> <83AFA654-A26E-4675-9562-2C6C2299D596@gmail.com> Message-ID: <851tyy4k79.fsf_-_@benfinney.id.au> "Andr? Walker-Loud " writes: > and as a follow up - is there a way to download a thread from the > tutor archive? You've indicated you know this, but for other readers: The mailing list archives are available in compressed ?mbox? format, by month. > 2) download the whole gzip?d text and use python to grab only the > parts I want A decent email client (such as Mutt, Gnus, Thunderbird, etc.) will be able to open an mbox-format archive as a folder, and from there you can filter and reply to messages as normal. For programmatic access, the Python standard library ?mailbox? module supports reading ?mbox?, and you then have all the Mailbox methods to select and extract messages. -- \ ?Human reason is snatching everything to itself, leaving | `\ nothing for faith.? ?Saint Bernard, 1090?1153 | _o__) | Ben Finney From zakiakhmad at gmail.com Thu Feb 20 09:23:45 2014 From: zakiakhmad at gmail.com (Zaki Akhmad) Date: Thu, 20 Feb 2014 15:23:45 +0700 Subject: [Tutor] Responding Tweet: A Twitter Bot Message-ID: Hello, I am trying to create a twitter bot which respond mentions as soon as possible. Here's the detail. If @someone mention my account @example then in t seconds I would respond @someone tweet. I am hoping to get this t less than 60 seconds. I would utilize the Mike Verdone twitter API python[1]. My question is how to get the mentions as soon as possible, as @someone mention @example? Any python library could help me? Hint please. Previously, I use cron to search for tweets that mentioned @example account. [1]https://pypi.python.org/pypi/twitter Thank you, -- Zaki Akhmad From denis.spir at gmail.com Thu Feb 20 14:17:41 2014 From: denis.spir at gmail.com (spir) Date: Thu, 20 Feb 2014 14:17:41 +0100 Subject: [Tutor] constructing semi-arbitrary functions In-Reply-To: <83AFA654-A26E-4675-9562-2C6C2299D596@gmail.com> References: <4C4959CB-ACDF-4BEB-BC3E-24E54FFD40F1@gmail.com> <09E29FD5-537C-4D6B-AB2F-DFF200AEB951@gmail.com> <83AFA654-A26E-4675-9562-2C6C2299D596@gmail.com> Message-ID: <53060075.60103@gmail.com> On 02/20/2014 01:56 AM, "Andr? Walker-Loud " wrote: > On Feb 19, 2014, at 7:45 PM, Andr? Walker-Loud wrote: > >> OK - I have not seen an email from Peter. >> So I looked up the thread online, and see I did not receive half the emails on this thread :O >> >> My first inclination was to blame my mac mavericks mail gmail syncing problem. but logging into gmail, I see no record of the emails there either. >> >> I currently receive the tutor emails in the digest mode - thought I was paying attention to all the digests - but I seems to have missed many. >> >> I apologize to all those who offered input whose emails I missed - I certainly wasn?t ignoring them. > > and as a follow up - is there a way to download a thread from the tutor archive? > I am guessing the answers are one of > 1) write a python script to grab the emails associated with the threads from the web > 2) download the whole gzip?d text and use python to grab only the parts I want > > but 1) I haven?t done that before and unfortunately don?t have time to learn now > 2) some combination of being too busy and lazy prevents me from this option? Your local email client, if any, may do 90% of the job for you if you set: * normal, non-digest mode * threaded view locally then just press 'del' on every other thread. As a side-note, since you are now subscribed to the python-tutor list, by not pressing 'del' (too quiclkly), you may learn much about python and programming in general, in a both nice and efficient manner. d From alan.gauld at btinternet.com Thu Feb 20 14:25:49 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Feb 2014 13:25:49 +0000 Subject: [Tutor] Responding Tweet: A Twitter Bot In-Reply-To: References: Message-ID: On 20/02/14 08:23, Zaki Akhmad wrote: > I am trying to create a twitter bot which respond mentions as soon as > possible. Here's the detail. These have been around for a long time in email circles. One thing to watch is detection of cycles. That's where someone tweets you and you auto-respond, But they also have an auto-responder that responds to your automated message. Will your program then respond to that too? If so you get a cycle with an infinite loop of auto responses. That's not a good thing. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From zakiakhmad at gmail.com Fri Feb 21 04:52:58 2014 From: zakiakhmad at gmail.com (Zaki Akhmad) Date: Fri, 21 Feb 2014 10:52:58 +0700 Subject: [Tutor] Responding Tweet: A Twitter Bot In-Reply-To: <5305F794.9040902@jls-radio.com> References: <5305F794.9040902@jls-radio.com> Message-ID: On Thu, Feb 20, 2014 at 7:39 PM, James Scholes wrote: > Most decent Python libraries for accessing Twitter support the streaming > API. This lets you keep a connection to the Twitter API alive and > process new data as it is received. There is a simple (but out-of-date) > example on using streaming with the twitter package you linked to: > https://pypi.python.org/pypi/twitter/1.13.1 My question is: how to execute this streaming API? My current approach is using cron to execute python script which has "check the streaming API" function: def check_mention: if (mention): tweet If I want to check every minute, then I should configure cron to execute this script every minute. Are there any other approach besides using cron? -- Zaki Akhmad From davea at davea.name Fri Feb 21 05:47:37 2014 From: davea at davea.name (Dave Angel) Date: Thu, 20 Feb 2014 23:47:37 -0500 (EST) Subject: [Tutor] Responding Tweet: A Twitter Bot References: <5305F794.9040902@jls-radio.com> Message-ID: Zaki Akhmad Wrote in message: > On Thu, Feb 20, 2014 at 7:39 PM, James Scholes wrote: > >> Most decent Python libraries for accessing Twitter support the streaming >> API. This lets you keep a connection to the Twitter API alive and >> process new data as it is received. There is a simple (but out-of-date) >> example on using streaming with the twitter package you linked to: >> https://pypi.python.org/pypi/twitter/1.13.1 > > My question is: how to execute this streaming API? > > My current approach is using cron to execute python script which has > "check the streaming API" function: > > def check_mention: > if (mention): > tweet > > If I want to check every minute, then I should configure cron to > execute this script every minute. Are there any other approach besides > using cron? > > > > import time while True: do|something time.sleep (60) Note that sleep () doesn't hog the processor; very nearly 100% of the processor is given to the other processes. Further, you don't have the startup time you'd have with cron. There are tradeoffs, but sleep is usually what you want. -- DaveA From wprins at gmail.com Fri Feb 21 10:05:13 2014 From: wprins at gmail.com (Walter Prins) Date: Fri, 21 Feb 2014 09:05:13 +0000 Subject: [Tutor] Responding Tweet: A Twitter Bot In-Reply-To: References: <5305F794.9040902@jls-radio.com> Message-ID: Hi, On 21 February 2014 03:52, Zaki Akhmad wrote: > On Thu, Feb 20, 2014 at 7:39 PM, James Scholes wrote: > >> Most decent Python libraries for accessing Twitter support the streaming >> API. This lets you keep a connection to the Twitter API alive and >> process new data as it is received. There is a simple (but out-of-date) >> example on using streaming with the twitter package you linked to: >> https://pypi.python.org/pypi/twitter/1.13.1 > > My question is: how to execute this streaming API? > > My current approach is using cron to execute python script which has > "check the streaming API" function: > > def check_mention: > if (mention): > tweet > > If I want to check every minute, then I should configure cron to > execute this script every minute. Are there any other approach besides > using cron? With the caveat that I'm not familiar with the Twitter streaming API's and that I literally only spend 3 minutes googling this, it seems to me to be the case that the Twitter streaming API's is intended to be a push style notification service. This means you should not in principle ideally be polling the service for updates yourself (e.g. using sleep/crong etc). Instead, the docs say that the streaming API can return an iterator that yields objects as they're decoded from the stream. Quote: "The TwitterStream object is an interface to the Twitter Stream API (stream.twitter.com). This can be used pretty much the same as the Twitter class except the result of calling a method will be an iterator that yields objects decoded from the stream. For example::" It's highly preferable to not poll something if it will generate/notify you of new objects, so you should be able to do something like in their example. Quote: twitter_stream = TwitterStream(auth=UserPassAuth('joe', 'joespassword')) iterator = twitter_stream.statuses.sample() for tweet in iterator: # ...do something with this tweet... (e.g. check if you want to retweet or something) So the for loop should just block by itself until a new tweet/message comes in at which point it will spring to life and hand it to your code to process. I hope that helps, and apologies if I misunderstood something or have missed something that makes my comment irrelevant to your problem. Walter From gb.gabrielebrambilla at gmail.com Fri Feb 21 15:20:15 2014 From: gb.gabrielebrambilla at gmail.com (Gabriele Brambilla) Date: Fri, 21 Feb 2014 09:20:15 -0500 Subject: [Tutor] from command prompt use interactive python and running script together Message-ID: Hi, Is possible on python to running scripts from the command prompt (I'm using python on windows) and in the end saving all the variables and continue the analysis in the interactive mode? (the one that you activate typing python in the command prompt?) Or to use python in the interactive mode and in some moments to run scripts, without quit() the interactive mode, and use for the script variables the one you have defined in the interactive mode? thanks Gabriele -------------- next part -------------- An HTML attachment was scrubbed... URL: From dpalao.python at gmail.com Fri Feb 21 15:40:08 2014 From: dpalao.python at gmail.com (David Palao) Date: Fri, 21 Feb 2014 15:40:08 +0100 Subject: [Tutor] from command prompt use interactive python and running script together In-Reply-To: References: Message-ID: 2014-02-21 15:20 GMT+01:00 Gabriele Brambilla : > Hi, > > Is possible on python to running scripts from the command prompt (I'm using > python on windows) and in the end saving all the variables and continue the > analysis in the interactive mode? (the one that you activate typing python > in the command prompt?) I guess you could define a function that does something like this by using pickle or similar technology. > Or to use python in the interactive mode and in some moments to run scripts, > without quit() the interactive mode, and use for the script variables the > one you have defined in the interactive mode? > You could import some objects from modules and use them in the interactive session. > > thanks > > Gabriele > Best > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From kwpolska at gmail.com Fri Feb 21 15:43:14 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Fri, 21 Feb 2014 15:43:14 +0100 Subject: [Tutor] from command prompt use interactive python and running script together In-Reply-To: References: Message-ID: On Fri, Feb 21, 2014 at 3:20 PM, Gabriele Brambilla wrote: > Hi, > > Is possible on python to running scripts from the command prompt (I'm using > python on windows) and in the end saving all the variables and continue the > analysis in the interactive mode? (the one that you activate typing python > in the command prompt?) Run this: python -i file.py > Or to use python in the interactive mode and in some moments to run scripts, > without quit() the interactive mode, and use for the script variables the > one you have defined in the interactive mode? > > > thanks > > Gabriele > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From eryksun at gmail.com Fri Feb 21 16:08:41 2014 From: eryksun at gmail.com (eryksun) Date: Fri, 21 Feb 2014 10:08:41 -0500 Subject: [Tutor] from command prompt use interactive python and running script together In-Reply-To: References: Message-ID: On Fri, Feb 21, 2014 at 9:20 AM, Gabriele Brambilla wrote: > > Is possible on python to running scripts from the command prompt (I'm using > python on windows) and in the end saving all the variables and continue the > analysis in the interactive mode? (the one that you activate typing python > in the command prompt?) The -i option will inspect interactively after running a command, module, or script: python -i [-c cmd | -m mod | file] Or using the new launcher that comes with 3.3: py [-2 | -3 | -X.Y | -X.Y-32] -i [-c cmd | -m mod | file] The 3.3 installer associates the new launcher with .py files. This introduces Unix-style shebang support, e.g.: #!python2 -i A shebang lets you run the script directly in the console, or from the Windows GUI shell. In other words, instead of running "python -i script.py" you'd simply run "script.py", or just double-click on the file icon in Explorer. Normally the console window that opens when you run a .py file will automatically close when the script exits. But with -i in the above shebang, the console stays open, with the interpreter running in interactive mode. > Or to use python in the interactive mode and in some moments to run scripts, > without quit() the interactive mode, and use for the script variables the > one you have defined in the interactive mode? You can use runpy.run_path, which was added in 2.7/3.2. It returns a dict namespace, and if you want you can simply update globals() with it. test.py: def main(): print('spam') if __name__ == '__main__': main() Demo: >>> import runpy >>> ns = runpy.run_path('test.py', run_name='__main__') spam >>> globals().update(ns) >>> main() spam From wescpy at gmail.com Fri Feb 21 18:48:40 2014 From: wescpy at gmail.com (wesley chun) Date: Fri, 21 Feb 2014 09:48:40 -0800 Subject: [Tutor] Regarding Exceptions In-Reply-To: References: Message-ID: On Mon, Feb 17, 2014 at 3:29 AM, Khalid Al-Ghamdi wrote: Hi, in the following snippet, why is it I don't need to create an Exception object and I can use the class directly in raise my custom exception? here's a new one... i'm going to try to answer this question without working code since everyone has pointed out it won't compile. the OP is simply asking why Exception didn't need to be defined before using, as with all Python variables... IOW, why doesn't it give a NameError exception here? the reason is because Exception is a built-in, meaning that it's C code that's been made available for you before your Python code executes. look: >>> Exception in reality, built-ins are part of a magical module called __builtins__ that's "automagically" imported for you so that you never have to do it yourself. check this out: >>> __builtins__.Exception you can also find out what all the other built-ins are using dir(): >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError',...] hope this helps! --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Fri Feb 21 19:27:55 2014 From: eryksun at gmail.com (eryksun) Date: Fri, 21 Feb 2014 13:27:55 -0500 Subject: [Tutor] Regarding Exceptions In-Reply-To: References: Message-ID: On Fri, Feb 21, 2014 at 12:48 PM, wesley chun wrote: > in reality, built-ins are part of a magical module called __builtins__ > that's "automagically" imported for you so that you never have to do it > yourself. check this out: > >>>> __builtins__.Exception > > > you can also find out what all the other built-ins are using dir(): >>>> dir(__builtins__) > ['ArithmeticError', 'AssertionError', 'AttributeError',...] In __main__, __builtins__ is the __builtin__ module (no "s"): >>> __builtins__ I have no idea why. I guess someone thinks this is convenient? In every other pure-Python (not built-in) module, it defaults to the dict of the __builtin__ module: >>> import __builtin__, os >>> os.__builtins__ is vars(__builtin__) True That's the default when a module is executed. However, it's possible to exec and eval code with a custom __builtins__: >>> ns = {'__builtins__': {'msg': 'spam'}} >>> exec 'print msg' in ns spam >>> eval('msg', ns) 'spam' Just don't be deluded into thinking it's possible to sandbox Python like this. From steve at pearwood.info Sat Feb 22 02:34:39 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Feb 2014 12:34:39 +1100 Subject: [Tutor] from command prompt use interactive python and running script together In-Reply-To: References: Message-ID: <20140222013438.GB3684@ando> On Fri, Feb 21, 2014 at 09:20:15AM -0500, Gabriele Brambilla wrote: > Hi, > > Is possible on python to running scripts from the command prompt (I'm using > python on windows) and in the end saving all the variables and continue the > analysis in the interactive mode? (the one that you activate typing python > in the command prompt?) The best way to do this is to use a Python shell that supports it. ipython is an advanced, powerful shell that supports saving and restoring the shell state when you leave, as well as many more features. http://ipython.org/ The feature I think you want is this: http://ipython.org/ipython-doc/stable/interactive/reference.html#session-logging-and-restoring bpython is a more light-weight alternative. It doesn't have all the features of ipython, but it is closer to the standard interactive shell: http://bpython-interpreter.org/ DreamPie is another alternate Python shell that might be worth investigating. http://www.dreampie.org/ > Or to use python in the interactive mode and in some moments to run > scripts, without quit() the interactive mode, and use for the script > variables the one you have defined in the interactive mode? Again, I expect that ipython will do something very like that. -- Steven From steve at pearwood.info Sat Feb 22 02:50:20 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Feb 2014 12:50:20 +1100 Subject: [Tutor] Regarding Exceptions In-Reply-To: References: Message-ID: <20140222015020.GC3684@ando> On Fri, Feb 21, 2014 at 01:27:55PM -0500, eryksun wrote: > On Fri, Feb 21, 2014 at 12:48 PM, wesley chun wrote: > > in reality, built-ins are part of a magical module called __builtins__ > > that's "automagically" imported for you so that you never have to do it > > yourself. check this out: > > > >>>> __builtins__.Exception > > > > > > you can also find out what all the other built-ins are using dir(): > >>>> dir(__builtins__) > > ['ArithmeticError', 'AssertionError', 'AttributeError',...] > > In __main__, __builtins__ is the __builtin__ module (no "s"): > > >>> __builtins__ > Built-ins is confusing. __builtins__ with an S is a special, implementation-specific hack for CPython only, it is *not* part of the language and you should not rely on it. Never use __builtins__, it is considered for internal use only. In Python 2, the built-in objects live inside a module called __builtin__ (with no S). Like all modules, you have to import it before you can access the module. Unlike other modules, it's automatically used to look up names, even if you haven't imported it. So when you refer to a name like "foo", or "len", or "Exception", Python searches the local variables, the global variables, and the built-ins, before raising NameError if it is not found at all. The difference between private __builtins__ and public __builtin__ is confusing and subtle and easy to get wrong, so in Python 3 the built-in module was renamed to "builtins". # Don't do this, this is bad. __builtins__.len # Instead, do this in Python 2. import __builtin__ __builtin__.len # Or in Python 3. import builtins builtins.len The history of __builtins__ with an S is quite old. It's used for performance reasons, and originally it was supposed to be used for sandboxing Python, but that turned out to not work. So although it still exists even in Python 3, it's a performance hack for the CPython interpreter, and does not exist in Jython, IronPython or other interpreters. -- Steven From eryksun at gmail.com Sat Feb 22 04:31:01 2014 From: eryksun at gmail.com (eryksun) Date: Fri, 21 Feb 2014 22:31:01 -0500 Subject: [Tutor] Regarding Exceptions In-Reply-To: <20140222015020.GC3684@ando> References: <20140222015020.GC3684@ando> Message-ID: On Fri, Feb 21, 2014 at 8:50 PM, Steven D'Aprano wrote: > The history of __builtins__ with an S is quite old. It's used for > performance reasons, and originally it was supposed to be used for > sandboxing Python, but that turned out to not work. So although it still > exists even in Python 3, it's a performance hack for the CPython > interpreter, and does not exist in Jython, IronPython or other > interpreters. I can see how it's a small memory optimization to store __builtins__ in globals. Otherwise a function would need another slot for func_builtins, just as a frame has f_globals and f_builtins. That's assuming CPython retains the ability to use a custom builtins namespace. As you say, that isn't even possible in other Python implementations such as Jython. As to this being a "performance hack", I can't see how using __builtins__ improves performance, since the interpreter keeps a reference to the dict of the __builtin__ module. The attempt at sandboxing runs deeper than just customizing __builtins__. Search the CPython 2.x source for PyEval_GetRestricted. The latter returns true when a frame's f_builtins isn't the interpreter's builtins. Restricted code can't directly create file objects, unmarshal code objects (from .pyc), set old-style class attributes, or read/write restricted members of built-in objects such as a function's __doc__, among other restrictions. But trying to lock Python down in an otherwise uncontrolled environment is harder than playing Whac-A-Mole. Almost all of the restricted API was removed from Python 3, except for a few legacy flags. From piyushjoshi999 at gmail.com Sat Feb 22 13:26:45 2014 From: piyushjoshi999 at gmail.com (piyush joshi) Date: Sat, 22 Feb 2014 17:56:45 +0530 Subject: [Tutor] i dont understand this code Message-ID: <001201cf2fc9$7b24e060$716ea120$@com> Can anyone help me out in understanding this code # import os rotationMatrix1 = [7, 1, 5, 3, 0, 6, 2, 5, 2, 3, 0, 6, 1, 7, 6, 1, 5, 2, 7, 1, 0, 3, 7, 6, 1, 0, 5, 2, 1, 5, 7, 3, 2, 0, 6] rotationMatrix2 = [1, 6, 2, 5, 7, 3, 0, 7, 1, 6, 2, 5, 0, 3, 0, 6, 5, 1, 1, 7, 2, 5, 2, 3, 7, 6, 2, 1, 3, 7, 6, 5, 0, 1, 7] keyboardDict = { 2: '1', 3: '2', 4: '3', 5: '4', 6: '5', 7: '6', 8: '7', 9: '8', 10: '9', 11: '0', 16: 'q', 17: 'w', 18: 'e', 19: 'r', 20: 't', 21: 'y', 22: 'u', 23: 'i', 24: 'o', 25: 'p', 30: 'a', 31: 's', 32: 'd', 33: 'f', 34: 'g', 35: 'h', 36: 'j', 37: 'k', 38: 'l', 44: 'z', 45: 'x', 46: 'c', 47: 'v', 48: 'b', 49: 'n', 50: 'm' } def keyboardEncToAscii(inKey): out = "" for c in inKey: if c == 0: return out if c in keyboardDict: out += keyboardDict[c] else: return "" return out def decryptHash(hash, key, rotationMatrix): outhash = [] for i in range(0, len(hash)): outhash.append(((hash[i] << (rotationMatrix[7*key+i])) & 0xFF) | (hash[i] >> (8-rotationMatrix[7*key+i]))) return outhash print("") print("hexa decimal code") print("hexadecimal code from which the password can be calculated,") print("07088120410C0000") print("") print("Please enter the code: ") code = raw_input() hash = [] for i in range(1, len(code) // 2): hash.append(int(code[2*i]+code[2*i+1],16)) key = int(code[0:2], 16) % 5 password = keyboardEncToAscii(decryptHash(hash, key, rotationMatrix1)) if password == "": password = keyboardEncToAscii(decryptHash(hash, key, rotationMatrix2)) if password == "": print("The password could not be calculated. Bummer.") else: print("The password is: " + password) if (os.name == 'nt'): print("Press a key to exit...") raw_input() --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Feb 22 19:47:39 2014 From: bgailer at gmail.com (bob gailer) Date: Sat, 22 Feb 2014 13:47:39 -0500 Subject: [Tutor] i dont understand this code In-Reply-To: <001201cf2fc9$7b24e060$716ea120$@com> References: <001201cf2fc9$7b24e060$716ea120$@com> Message-ID: <5308F0CB.3010306@gmail.com> On 2/22/2014 7:26 AM, piyush joshi wrote: > > Can anyone help me out in understanding this code > Your question is kinda vague. Exactly what do you not understand? > # > > import os > > rotationMatrix1 = [7, 1, 5, 3, 0, 6, 2, 5, 2, 3, 0, 6, 1, 7, 6, 1, 5, > 2, 7, 1, 0, 3, 7, 6, 1, 0, 5, 2, 1, 5, 7, 3, 2, 0, 6] > > rotationMatrix2 = [1, 6, 2, 5, 7, 3, 0, 7, 1, 6, 2, 5, 0, 3, 0, 6, 5, > 1, 1, 7, 2, 5, 2, 3, 7, 6, 2, 1, 3, 7, 6, 5, 0, 1, 7] > > keyboardDict = { 2: '1', 3: '2', 4: '3', 5: '4', 6: '5', 7: > '6', 8: '7', 9: '8', 10: '9', 11: '0', > > 16: 'q', 17: 'w', 18: 'e', 19: 'r', 20: 't', 21: 'y', > 22: 'u', 23: 'i', 24: 'o', 25: 'p', > > 30: 'a', 31: 's', 32: 'd', 33: 'f', 34: 'g', 35: 'h', > 36: 'j', 37: 'k', 38: 'l', > > 44: 'z', 45: 'x', 46: 'c', 47: 'v', 48: 'b', 49: 'n', > 50: 'm' } > > def keyboardEncToAscii(inKey): > > out = "" > > for c in inKey: > > if c == 0: return out > > if c in keyboardDict: out += > keyboardDict[c] > > else: return "" > > return out > > def decryptHash(hash, key, rotationMatrix): > > outhash = [] > > for i in range(0, len(hash)): > > outhash.append(((hash[i] << (rotationMatrix[7*key+i])) & 0xFF) | > (hash[i] >> (8-rotationMatrix[7*key+i]))) > > return outhash > > print("") > > print("hexa decimal code") > > print("hexadecimal code from which the password can be calculated,") > > print("07088120410C0000") > > print("") > > print("Please enter the code: ") > > code = raw_input() > > hash = [] > > for i in range(1, len(code) // 2): > > hash.append(int(code[2*i]+code[2*i+1],16)) > > key = int(code[0:2], 16) % 5 > > password = keyboardEncToAscii(decryptHash(hash, key, rotationMatrix1)) > > if password == "": > > password = keyboardEncToAscii(decryptHash(hash, key, > rotationMatrix2)) > > if password == "": > > print("The password could not be calculated. Bummer.") > > else: > > print("The password is: " + password) > > if (os.name == 'nt'): > > print("Press a key to exit...") > > raw_input() > > > > ------------------------------------------------------------------------ > > > This email is free from viruses and malware because avast! Antivirus > protection is active. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Feb 22 20:03:53 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Feb 2014 19:03:53 +0000 Subject: [Tutor] i dont understand this code In-Reply-To: <001201cf2fc9$7b24e060$716ea120$@com> References: <001201cf2fc9$7b24e060$716ea120$@com> Message-ID: On 22/02/14 12:26, piyush joshi wrote: > Can anyone help me out in understanding this code Sure, but it's an quite a lot of code to describe line by line. Is there anything specific you need help with? > import os > > rotationMatrix1 = [7, 1, 5, 3, 0, 6, 2, 5, 2, 3, 0, 6, 1, 7, 6, 1, 5, 2, > 7, 1, 0, 3, 7, 6, 1, 0, 5, 2, 1, 5, 7, 3, 2, 0, 6] > > rotationMatrix2 = [1, 6, 2, 5, 7, 3, 0, 7, 1, 6, 2, 5, 0, 3, 0, 6, 5, 1, > 1, 7, 2, 5, 2, 3, 7, 6, 2, 1, 3, 7, 6, 5, 0, 1, 7] > > keyboardDict = { 2: '1', 3: '2', 4: '3', 5: '4', 6: '5', 7: '6', > 8: '7', 9: '8', 10: '9', 11: '0', > 16: 'q', 17: 'w', 18: 'e', 19: 'r', 20: 't', 21: 'y', > 22: 'u', 23: 'i', 24: 'o', 25: 'p', > 30: 'a', 31: 's', 32: 'd', 33: 'f', 34: 'g', 35: 'h', > 36: 'j', 37: 'k', 38: 'l', > 44: 'z', 45: 'x', 46: 'c', 47: 'v', 48: 'b', 49: 'n', > 50: 'm' } > > def keyboardEncToAscii(inKey): > out = "" > > for c in inKey: > if c == 0: return out > if c in keyboardDict: out += > keyboardDict[c] > else: return "" > return out > > def decryptHash(hash, key, rotationMatrix): > outhash = [] > for i in range(0, len(hash)): > outhash.append(((hash[i] << > (rotationMatrix[7*key+i])) & 0xFF) | (hash[i] >> > (8-rotationMatrix[7*key+i]))) > return outhash > > print("") > print("hexa decimal code") > print("hexadecimal code from which the password can be calculated,") > print("07088120410C0000") > print("") > print("Please enter the code: ") > code = raw_input() > hash = [] > for i in range(1, len(code) // 2): > hash.append(int(code[2*i]+code[2*i+1],16)) > key = int(code[0:2], 16) % 5 > > password = keyboardEncToAscii(decryptHash(hash, key, rotationMatrix1)) > if password == "": > password = keyboardEncToAscii(decryptHash(hash, key, > rotationMatrix2)) > if password == "": > print("The password could not be calculated. Bummer.") > else: > print("The password is: " + password) > if (os.name == 'nt'): > print("Press a key to exit...") > raw_input() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From swdunning at cox.net Sun Feb 23 09:08:21 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 23 Feb 2014 01:08:21 -0700 Subject: [Tutor] Function help Message-ID: I am VERY new to python (programming too). I had a question regarding functions. Is there a way to call a function multiple times without recalling it over and over. Meaning is there a way I can call a function and then add *5 or something like that? I am trying to code an American Flag using turtle for class so I?ll post the code I have so far below. As you can see towards the bottom I recall the functions to draw the stars, fill in color and give it spacing. I was wondering if there was a way to cut down on all that some how? Thanks for any help! Scott From swdunning at cox.net Sun Feb 23 09:17:43 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 23 Feb 2014 01:17:43 -0700 Subject: [Tutor] Function help In-Reply-To: <950D8EBE-7D8A-445C-A3E0-28D592262202@cox.net> References: <950D8EBE-7D8A-445C-A3E0-28D592262202@cox.net> Message-ID: <211315A3-4D6B-4C96-8D69-36825E885478@cox.net> On Feb 23, 2014, at 1:12 AM, Scott W Dunning wrote: > I am VERY new to python (programming too). I had a question regarding functions. Is there a way to call a function multiple times without recalling it over and over. Meaning is there a way I can call a function and then add *5 or something like that? I am trying to code an American Flag using turtle for class so I?ll post the code I have so far below. As you can see towards the bottom I recall the functions to draw the stars, fill in color and give it spacing. I was wondering if there was a way to cut down on all that some how? > > Thanks for any help! > > Scott from turtle import * from math import sin, sqrt, radians def star(width): R = (width)/(2*sin(radians(72))) A = (2*width)/(3+sqrt(5)) penup() left(18) penup() forward(R) pendown() left(162) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) penup() left(162) forward(R) left(162) showturtle() def fillstar(color): fillcolor(color) begin_fill() star(25) end_fill() red = "red" fillstar(red) def space(width): penup() forward(2*width) pendown() space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) def row(width): penup() right(90) forward(width) right(90) forward(11*width) right(180) pendown() row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) row(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) fillstar(red) space(25) From __peter__ at web.de Sun Feb 23 10:26:59 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 Feb 2014 10:26:59 +0100 Subject: [Tutor] Function help References: <950D8EBE-7D8A-445C-A3E0-28D592262202@cox.net> <211315A3-4D6B-4C96-8D69-36825E885478@cox.net> Message-ID: Scott W Dunning wrote: > > On Feb 23, 2014, at 1:12 AM, Scott W Dunning wrote: > >> I am VERY new to python (programming too). I had a question regarding >> functions. Is there a way to call a function multiple times without >> recalling it over and over. Meaning is there a way I can call a function >> and then add *5 or something like that? I am trying to code an American >> Flag using turtle for class so I?ll post the code I have so far below. >> As you can see towards the bottom I recall the functions to draw the >> stars, fill in color and give it spacing. I was wondering if there was a >> way to cut down on all that some how? >> >> Thanks for any help! The example helps a lot! And of course this process of "cutting down", achieving complex tasks by doing simple things repetetively is what programmers do all the time. There is even a principle called "DRY" (don't repeat yourself) meaning that if you have to write something twice in your code you are doing it wrong. Looking at > fillstar(red) > space(25) > fillstar(red) > space(25) > fillstar(red) > space(25) > fillstar(red) > space(25) > fillstar(red) > space(25) a programmer would think "for loop" immediately for i in range(5): fillstar(red) space(25) and as this sequence occurs more than once in your code you should make it a function. For example: def star_row(): for i in range(5): fillstar(red) space(25) If you want to make rows with more or less stars, or stars in other colors you could add parameters: def star_row(numstars, starcolor): for i in range(numstars): fillstar(starcolor) space(25) Your code will then become star_row(6, red) row(25) star_row(5, red) row(25) ... which still shows a repetetive pattern and thus you can simplify it with another loop. You should be able to find a way to write that loop with two star_row() calls on a single iteration, but can you do it with a single call too? From ben+python at benfinney.id.au Sun Feb 23 12:06:03 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 23 Feb 2014 22:06:03 +1100 Subject: [Tutor] Function help References: Message-ID: <85ppmeozqc.fsf@benfinney.id.au> Scott W Dunning writes: > I am VERY new to python (programming too). Welcome! You should establish the fundamentals of Python, by working through the Python tutorial . Begin at the beginning, and execute all the examples, and experiment with them to satisfy yourself that you understand what is being demonstrated; then, move on to the next. Continue until you have a good grasp of all the basics of Python. > I had a question regarding functions. Is there a way to call a > function multiple times without recalling it over and over. When you have worked through the tutorial, you will understand how loops can address problems like this. Enjoy learning the basics of programming! -- \ ?As scarce as truth is, the supply has always been in excess of | `\ the demand.? ?Josh Billings | _o__) | Ben Finney From davea at davea.name Sun Feb 23 13:31:29 2014 From: davea at davea.name (Dave Angel) Date: Sun, 23 Feb 2014 07:31:29 -0500 (EST) Subject: [Tutor] Function help References: Message-ID: Scott W Dunning Wrote in message: > I am VERY new to python (programming too). I had a question regarding functions. Is there a way to call a function multiple times without recalling it over and over. Meaning is there a way I can call a function and then add *5 or something like that? I am trying to code an American Flag using turtle for class so I???ll post the code I have so far below. As you can see towards the bottom I recall the functions to draw the stars, fill in color and give it spacing. I was wondering if there was a way to cut down on all that some how? > Welcome to the tutor forum also, Scott. You'll find it works very similarly to python-list, and has many of the same people on it. I'm not sure how you tried to attach source, but please be aware that this is a text list - anything other than plain text will probably be invisible or inconvenient to someone. Just paste snippets inline when needed. What you're looking for is a loop. for and while are the two keywords for looping. In this case, since you know how many times you want to go round, loop is appropriate. Build a collection or iterator of length 5, and loop over it. range is designed for the purpose: for index in range (5): dosomething moresomething (index) Everything that's indented will happen 5 times. Later you'll want to learn continue and break, which can alter the simple flow. And presumably you already know if. import, for, while, if, elif, else, break, continue Incidentally, your star function could have been much shorter with a loop. -- DaveA From salexandre.bm at gmail.com Sun Feb 23 15:38:33 2014 From: salexandre.bm at gmail.com (Alexandre BM) Date: Sun, 23 Feb 2014 15:38:33 +0100 Subject: [Tutor] Responding Tweet: A Twitter Bot In-Reply-To: References: Message-ID: <530A07E9.8090802@gmail.com> Here is a twitter bot that I created, it evaluates math expression then it reply to the sender You can study how it works it's pretty simple :) [1] [1] https://github.com/rednaks/Twitter-Math-Bot On 20/02/2014 09:23, Zaki Akhmad wrote: > Hello, > > I am trying to create a twitter bot which respond mentions as soon as > possible. Here's the detail. > > If @someone mention my account @example then in t seconds I would > respond @someone tweet. I am hoping to get this t less than 60 > seconds. > > I would utilize the Mike Verdone twitter API python[1]. My question is > how to get the mentions as soon as possible, as @someone mention > @example? Any python library could help me? Hint please. > > Previously, I use cron to search for tweets that mentioned @example account. > > [1]https://pypi.python.org/pypi/twitter > > Thank you, > From vogernewsletters at yahoo.gr Sun Feb 23 22:59:27 2014 From: vogernewsletters at yahoo.gr (voger) Date: Sun, 23 Feb 2014 23:59:27 +0200 Subject: [Tutor] I can't understand where python class methods come from Message-ID: <530A6F3F.8080704@yahoo.gr> I have a really hard time understanding where methods are defined in python classes. My first contact with programming was with C++ and Java and even if I was messing with them in a very amateurish level, I could find where each class was defined and what methods were defined inside them. Everything was clear and comprehensive. With python everything looks like magic. Methods and properties appearing out of nowhere and somehow easing the task at hand. I am not complaining for their existence but I really can't understand how and what is defined so I can use it. Enough ranting and let me give an example of what I mean. Let's have a look at the pygeocoder library located here: http://code.xster.net/pygeocoder/src/8888c863f907f8a706545fa9b27959595f45f8c5/pygeolib.py?at=default and a short tutorial on usage by someone unrelated to the author located here: http://www.pixelite.co.nz/article/validate-and-clean-user-submitted-address-data-pygeocoder?&ei=518KU5mcFeim4ASG34Fo?&usg=AFQjCNFgMx8s7wPP6R6CyLLoSAE-Ohh51Q?&sig2=afBUF9yuxbZYB9fcfK9Lmw?&bvm=bv.61725948,d.bGE The tutorial basicaly says in code that once we obtain the data we can do: print "address.valid_address: ", address.valid_address print "address.street_number: ", address.street_number print "address.route: ", address.route print "address.sublocality: ", address.sublocality print "address.locality: ", address.locality print "address.administrative_area_level_1: ", address.administrative_area_level_1 print "address.country: ", address.country print "address.postal_code: ", address.postal_code print "address.coordinates: ", address.coordinates print "address.formatted_address: ", address.formatted_address Some properties I can see them defined but some others like sublocality or administrative_area_level_1 I don't see them defined anywhere. Also in the comments in the source code the author says #You can also choose a different property to display for each lookup #type. # Example: # result.country__short_name but I can't understand where that __short_name comes from I hope I didn't bore you with this long text but this is really confusing for me and I hope someone can help me understand these things. From ben+python at benfinney.id.au Sun Feb 23 23:44:42 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Feb 2014 09:44:42 +1100 Subject: [Tutor] I can't understand where python class methods come from References: <530A6F3F.8080704@yahoo.gr> Message-ID: <85k3clphyd.fsf@benfinney.id.au> voger writes: > I have a really hard time understanding where methods are defined in > python classes. Reading the rest of your message, I think you're saying that you can't locate *which* class defines a method > [?] With python everything looks like magic. It can seem that way. Fortunately, most of the magic needs to be explicitly declared in the code, so it's a matter of knowing what to look for. In this message, I'll guide you in when you should expect magic, and where to look for it. > Methods and properties appearing out of nowhere and somehow easing the > task at hand. I am not complaining for their existence but I really > can't understand how and what is defined so I can use it. This is a valid complaint, and certainly some libraries can get rather too clever with the ?magic behaviour?, leading to difficulty in understanding what is happening well enough to debug problems. > Enough ranting and let me give an example of what I mean. > > Let's have a look at the pygeocoder library located here: > http://code.xster.net/pygeocoder/src/8888c863f907f8a706545fa9b27959595f45f8c5/pygeolib.py?at=default The important part of that file is the ?GeocoderResult? class definition. It defines a lot of magic behaviour. In general, the magic often happens with ?dunder?-named attributes; that is, attributes named with a leading and traling double-underscore. An attribute named ?__foo__? is a strong indication that it will be treated specially and be invoked by the Python interpreter, *without* the programmer needing to invoke the attribute by name. Here is the class definition showing just the dunder-named attributes:: class GeocoderResult(collections.Iterator): ? def __init__(self, data): ? def __len__(self): ? def __iter__(self): ? def __getitem__(self, key): ? def __unicode__(self): ? if sys.version_info[0] >= 3: # Python 3 def __str__(self): return self.__unicode__() def __next__(self): return self.return_next() else: # Python 2 def __str__(self): return self.__unicode__().encode('utf8') def next(self): return self.return_next() ? def __getattr__(self, name): ? So already you should be on high alert: there is a large amount of ?magic? in this class! Seemlingly-simple uses of this class and its instances will result in invocations of those custom methods, even without seeing the names used explicitly. > Some properties I can see them defined but some others like > sublocality or administrative_area_level_1 I don't see them defined > anywhere. The specific magic happening here is that, when you access an attribute on an object, Python will allow interception of that request by a custom ?__getattr__? method. As you can see, the ?GeocoderResult? class defines that method for its instances, so you will need to look there for custom behaviour when accessing attributes on instances of this class. Similarly, the class defines ?__getitem__? to intercept ?foo[bar]?, it defines ?__len__? to intercept ?len(foo)?, it defines ?__iter__? to intercept attempts to iterate over an instance; and so on. Much magic! Personally, I'm suspicious whether this class really needs to be so awfully clever; it is certainly making the behaviour less intuitive, as demonstrated in your case. It smells of a poor design. > I hope I didn't bore you with this long text but this is really > confusing for me and I hope someone can help me understand these > things. One good decision made by the Python core developers early on was a convention of naming these special, magical-behaviour ?hook? attributes in a way that they are clearly special and signal to the reader that Python will be using them implicitly. So the general advice is to understand that any ?dunder?-named attribute needs to be researched, because it can be invoked *without* you necessarily being aware of that. Hope that helps! -- \ ?Choose mnemonic identifiers. If you can't remember what | `\ mnemonic means, you've got a problem.? ?Larry Wall | _o__) | Ben Finney From alan.gauld at btinternet.com Mon Feb 24 01:26:38 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Feb 2014 00:26:38 +0000 Subject: [Tutor] I can't understand where python class methods come from In-Reply-To: <530A6F3F.8080704@yahoo.gr> References: <530A6F3F.8080704@yahoo.gr> Message-ID: On 23/02/14 21:59, voger wrote: > I have a really hard time understanding where methods are defined in > python classes. My first contact with programming was with C++ and Java Ben has already addressed much of your confusion. I'd just add that if you look at C++ operator overloading it is very similar to Python's except that the C++ operators are more literally like their usage. Thus in C++ to overload the plus sign you write something like (I'm a bit rusty so the detail might be wrong...): class C{ public: C(int n){ this.data = n; }; C* operator+(C c){ return new C(c.data + this.data); }; }; myC1 = C(42); myC2 = C(66); void main(){ cout << myC1 + myC2; } In Python that is very like class C: def __init__(self,n): self.data = n def __add__(self, aCobj): return self.data + aCobj.data c1 = C(42) c2 = C(66) print (c1 + c2) In both languages a bit of magic happens to turn __add__ or operator+ into the infix + operator. > find where each class was defined and what methods were defined inside > them. Are you sure? That has always been one of the big challenges in OOP, finding where operations are defined. Especially in deep inheritance hierarchies. That's where explorer type tools can help. Python provides such help via the help() function. Often it will show you where a published method is defined. > Everything was clear and comprehensive. With python everything > looks like magic. Methods and properties appearing out of nowhere and > somehow easing the task at hand. They are always defined but the location and timing can be different. That's part of the dynamic nature of Python. [ Just be thankful it's not lisp which allows you to change all aspects of the objects, including the method search algorithm, at runtime...] > Let's have a look at the pygeocoder library located here: > http://code.xster.net/pygeocoder/src/8888c863f907f8a706545fa9b27959595f45f8c5/pygeolib.py?at=default There are many "smart" third party modules. Sometimes for good reasons, sometimes because the author found a clever solution and wanted to use it. Python is a broad church and while the standard library is fairly conventional for the most part third party libraries are the sole responsibility of their maintainers and may not be so readily understood. But then again many C libraries are obscure in the extreme, that's not the language's fault, it's just open and flexible. You have the choice to use it without fully understanding, spend time to understand, find an alternative or write your own... hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From james at jls-radio.com Sun Feb 23 23:21:17 2014 From: james at jls-radio.com (James Scholes) Date: Sun, 23 Feb 2014 22:21:17 +0000 Subject: [Tutor] I can't understand where python class methods come from In-Reply-To: <530A6F3F.8080704@yahoo.gr> References: <530A6F3F.8080704@yahoo.gr> Message-ID: <530A745D.4060209@jls-radio.com> voger wrote: > Some properties I can see them defined but some others like > sublocality or administrative_area_level_1 I don't see them defined > anywhere. Also in the comments in the source code the author says > > #You can also choose a different property to display for each lookup > #type. # Example: # result.country__short_name > > but I can't understand where that __short_name comes from The relevant code is in the __getattr__ method. From the Python docs: > If no class attribute is found, and the object?s class has a > __getattr__() method, that is called to satisfy the lookup. > > -- Source: > http://docs.python.org/2/reference/datamodel.html As an aside, your examples are attributes, not methods. Read the code below; this is where the magic happens: def __getattr__(self, name): lookup = name.split('__') attribute = lookup[0] if (attribute in GeocoderResult.attribute_mapping): attribute = GeocoderResult.attribute_mapping[attribute] try: prop = lookup[1] except IndexError: prop = 'long_name' for elem in self.current_data['address_components']: if attribute in elem['types']: return elem[prop] -- James Scholes http://twitter.com/JamesScholes From swdunning at cox.net Mon Feb 24 02:47:09 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 23 Feb 2014 18:47:09 -0700 Subject: [Tutor] Function help In-Reply-To: References: Message-ID: On Feb 23, 2014, at 5:31 AM, Dave Angel wrote: > > Welcome to the tutor forum also, Scott. You'll find it works very > similarly to python-list, and has many of the same people on it. > I'm not sure how you tried to attach source, but please be aware > that this is a text list - anything other than plain text will > probably be invisible or inconvenient to someone. Just paste > snippets inline when needed. I actually forgot to paste the code before I sent the email. > > What you're looking for is a loop. for and while are the two > keywords for looping. In this case, since you know how many > times you want to go round, loop is appropriate. Build a > collection or iterator of length 5, and loop over it. range is > designed for the purpose: > > for index in range (5): > dosomething > moresomething (index) Thank you for this help. I believe I understand. At least enough to do a simple loop for what I need. I?ll check back and paste my code after and maybe you can tell me if there is anything I could be doing better/easier. Thanks again!! Scott From swdunning at cox.net Mon Feb 24 03:15:05 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 23 Feb 2014 19:15:05 -0700 Subject: [Tutor] Function help In-Reply-To: References: <950D8EBE-7D8A-445C-A3E0-28D592262202@cox.net> <211315A3-4D6B-4C96-8D69-36825E885478@cox.net> Message-ID: On Feb 23, 2014, at 2:26 AM, Peter Otten <__peter__ at web.de> wrote: > If you want to make rows with more or less stars, or stars in other colors > you could add parameters: > > def star_row(numstars, starcolor): > for i in range(numstars): > fillstar(starcolor) > space(25) > > Your code will then become > > star_row(6, red) > row(25) > star_row(5, red) > row(25) > I have a question with the above loop function. Why couldn?t row(25) be added into the function so that wouldn?t have to placed in between every star_row()? > > which still shows a repetetive pattern and thus you can simplify it with > another loop. You should be able to find a way to write that loop with two > star_row() calls on a single iteration, but can you do it with a single call > too? Not sure I understand what you mean in the above paragraph? From swdunning at cox.net Mon Feb 24 03:04:56 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 23 Feb 2014 19:04:56 -0700 Subject: [Tutor] Function help In-Reply-To: References: <950D8EBE-7D8A-445C-A3E0-28D592262202@cox.net> <211315A3-4D6B-4C96-8D69-36825E885478@cox.net> Message-ID: <63FB7F51-89B5-4C00-853C-7A5F1E143FAA@cox.net> On Feb 23, 2014, at 2:26 AM, Peter Otten <__peter__ at web.de> wrote > a programmer would think "for loop? immediately That?s what I thought. It just seemed like way to much to keep repeating everything over and over. I knew there had to be a better way we just haven?t learned loops in school yet. > > for i in range(5): > fillstar(red) > space(25) Awesome, I was able to cut everything down quite a bit but, now like you say below I?m still repeating the loop. I?m gonna see if I can make a function with the loop to cut it down even further. Here is what I was able to cut it down to so far with your help. I?ll paste the new code when I make a function with the loop and maybe you guys can help me see if it look any better/easier. Also, does anyone know anything about turtle where I can try and move the starting point to the upper left hand corner? Thanks again! Scott from turtle import * from math import sin, sqrt, radians def star(width): R = (width)/(2*sin(radians(72))) A = (2*width)/(3+sqrt(5)) penup() left(18) penup() forward(R) pendown() left(162) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) penup() left(162) forward(R) left(162) showturtle() def fillstar(color): fillcolor(color) begin_fill() star(25) end_fill() red = "red" fillstar(red) def space(width): penup() forward(2*width) pendown() space(25) for i in range (5): fillstar(red) space(25) def row(width): penup() right(90) forward(width) right(90) forward(11*width) right(180) pendown() row(25) for i in range (5): fillstar(red) space(25) row(25) for i in range (6): fillstar(red) space(25) row(25) for i in range (5): fillstar(red) space(25) row(25) for i in range (6): fillstar(red) space(25) -------------- next part -------------- An HTML attachment was scrubbed... URL: From swdunning at cox.net Mon Feb 24 03:31:42 2014 From: swdunning at cox.net (Scott W Dunning) Date: Sun, 23 Feb 2014 19:31:42 -0700 Subject: [Tutor] Function help In-Reply-To: References: <950D8EBE-7D8A-445C-A3E0-28D592262202@cox.net> <211315A3-4D6B-4C96-8D69-36825E885478@cox.net> Message-ID: On Feb 23, 2014, at 2:26 AM, Peter Otten <__peter__ at web.de> wrote: > which still shows a repetetive pattern and thus you can simplify it with > another loop. You should be able to find a way to write that loop with two > star_row() calls on a single iteration, but can you do it with a single call > too? So, I was able to cut it down a bit but I?m having a hard time trying to cut it down with another loop and a single call. Wouldn?t what you?re saying in the above paragraph have to be another function with a loop inside? Or are you saying just another loop will suffice? Any hints? Here is what I got so far, I?ll put the loop in question in bold. from turtle import * from math import sin, sqrt, radians def star(width): R = (width)/(2*sin(radians(72))) A = (2*width)/(3+sqrt(5)) penup() left(18) penup() forward(R) pendown() left(162) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) left(144) forward(A) right(72) forward(A) penup() left(162) forward(R) left(162) showturtle() def fillstar(color): fillcolor(color) begin_fill() star(25) end_fill() red = "red" fillstar(red) def space(width): penup() forward(2*width) pendown() space(25) def row(width): penup() right(90) forward(width) right(90) forward(11*width) right(180) pendown() def star_row(numberstars): for i in range (numberstars): fillstar(red) space(25) star_row(5) row(25) star_row(5) row(25) star_row(6) row(25) star_row(5) row(25) star_row(6) row(25) star_row(5) row(25) star_row(6) row(25) star_row(5) row(25) star_row(6) This is what I?m thinking? for I in range(4) star_row(5) row(25) star_row(6) row(25) ???? Am I at all close? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 24 09:47:29 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Feb 2014 08:47:29 +0000 Subject: [Tutor] Function help In-Reply-To: <63FB7F51-89B5-4C00-853C-7A5F1E143FAA@cox.net> References: <950D8EBE-7D8A-445C-A3E0-28D592262202@cox.net> <211315A3-4D6B-4C96-8D69-36825E885478@cox.net> <63FB7F51-89B5-4C00-853C-7A5F1E143FAA@cox.net> Message-ID: On 24/02/14 02:04, Scott W Dunning wrote: > *Also, does anyone know anything about turtle where I can try and move > the starting point to the upper left hand corner? * dir() and help() are your friends. After doing dir(turtle) I spooted this likely looking candidate and ran help on it: -------------- setposition(x, y=None) Move turtle to an absolute position. Aliases: setpos | setposition | goto: Arguments: x -- a number or a pair/vector of numbers y -- a number None call: goto(x, y) # two coordinates --or: goto((x, y)) # a pair (tuple) of coordinates --or: goto(vec) # e.g. as returned by pos() Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle's orientation does not change. etc -------------- Similarly, I found the window_width() and window_height() methods. So, to get to the top left corner you'd goto( -window_width/2, window_height/2 ) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Mon Feb 24 10:41:33 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Feb 2014 10:41:33 +0100 Subject: [Tutor] Function help References: <950D8EBE-7D8A-445C-A3E0-28D592262202@cox.net> <211315A3-4D6B-4C96-8D69-36825E885478@cox.net> Message-ID: Scott W Dunning wrote: > > On Feb 23, 2014, at 2:26 AM, Peter Otten <__peter__ at web.de> wrote: >> If you want to make rows with more or less stars, or stars in other >> colors you could add parameters: >> >> def star_row(numstars, starcolor): >> for i in range(numstars): >> fillstar(starcolor) >> space(25) >> >> Your code will then become >> >> star_row(6, red) >> row(25) >> star_row(5, red) >> row(25) >> > I have a question with the above loop function. Why couldn?t row(25) be > added into the function so that wouldn?t have to placed in between every > star_row()? That's of course possible. >> which still shows a repetetive pattern and thus you can simplify it with >> another loop. You should be able to find a way to write that loop with >> two star_row() calls on a single iteration, but can you do it with a >> single call too? > Not sure I understand what you mean in the above paragraph? What you found out later and put in you next post: This repetetive pattern > star_row(5) # oops, typo > row(25) > star_row(5) > row(25) > star_row(6) > row(25) > star_row(5) > row(25) > star_row(6) > row(25) > star_row(5) > row(25) > star_row(6) > row(25) > star_row(5) > row(25) > star_row(6) can be turned into this for loop: > This is what I?m thinking? > > for I in range(4) > star_row(5) > row(25) > star_row(6) > row(25) > > Am I at all close? You hit the jackpot :) Now on to the next challenge: for row_index in range(9): row_width = ... star_row(row_width) row(25) Can you replace the ... with a calculation to get row_width=6 for even and row_width=5 for odd rows? Hint: look at the % ("modulo") operator. From denis.spir at gmail.com Mon Feb 24 11:15:18 2014 From: denis.spir at gmail.com (spir) Date: Mon, 24 Feb 2014 11:15:18 +0100 Subject: [Tutor] I can't understand where python class methods come from In-Reply-To: <530A6F3F.8080704@yahoo.gr> References: <530A6F3F.8080704@yahoo.gr> Message-ID: <530B1BB6.90808@gmail.com> On 02/23/2014 10:59 PM, voger wrote: > I have a really hard time understanding where methods are defined in python > classes. My first contact with programming was with C++ and Java > and even if I was messing with them in a very amateurish level, I could find > where each class was defined and what methods were defined inside them. > Everything was clear and comprehensive. With python everything looks like magic. > Methods and properties appearing out of nowhere and somehow easing the task at > hand. I am not complaining for their existence but I really can't understand how > and what is defined so I can use it. In general, python classes look like: class Point: def __init__ (self, x, y): self.x = x self.y = y self.d = x + y # square distance def move (self, dx, dy): self.x += dx self.y == dy def __str__ (self): return "{%s %s}" % (self.x, self.y) (Try using it if needed.) A valid complaint --which I share-- is that python classes do not obviously show data attributes. Maybe from other languages you'd rather expect something like: class Point: data = x , y, d # data attr (no static typing) def __init__ (self, x, y): self.d = x + y # square distance def move (self, dx, dy): self.x += dx self.y == dy def __str__ (self): return "{%s %s}" % (self.x, self.y) In python, you have to look inside __init__ (and sometimes also other methods just to know what are the actual data defining a given class's instances. > Enough ranting and let me give an example of what I mean. > > Let's have a look at the pygeocoder library located here: > http://code.xster.net/pygeocoder/src/8888c863f907f8a706545fa9b27959595f45f8c5/pygeolib.py?at=default This code is very unusual and indeed pretty magic. The big schema is that instead of computing and setting all data attributes at init time, it only does it *on demand*. To do so, it intercepts your requests (eg "x = addr.attr") in the "magic metamethod" called __getattr__. This method is called, as name suggests, when you request to read one of an object's attributes. You can even to similar magic with methods (since they are looked up as well), but it even more rare. Anyway, such metamagic is indeed advanced python programing and maybe you shouldn't bother with it now. d From 201302659 at tati.ub.bw Mon Feb 24 14:54:51 2014 From: 201302659 at tati.ub.bw (MS K MAGUNGA) Date: Mon, 24 Feb 2014 15:54:51 +0200 Subject: [Tutor] Tutor Digest, Vol 120, Issue 20 In-Reply-To: References: Message-ID: hey guys your tutorials really have me a lot and i managed to pass python and i would like you to continue sending me those tutorials so i can do more practice as far as the future is concerned.. I would also like to enroll on the java tutorials that's if you provide them... THANKS IN ADVANCE Regards Daisy Kebadiretse Magunga -------------- next part -------------- An HTML attachment was scrubbed... URL: From xenai_hatsotep at yahoo.com Mon Feb 24 09:37:36 2014 From: xenai_hatsotep at yahoo.com (Xenai Hatsotep) Date: Mon, 24 Feb 2014 16:37:36 +0800 (SGT) Subject: [Tutor] How to perform a google advanced search using python Message-ID: <1393231056.21872.YahooMailNeo@web190001.mail.sg3.yahoo.com> I have a python program which performs a simple google search. What i really want to do is perform an advanced search such that i can search for pdf files and ppt files in google. Any help on this subject would be very helpful. I have attached the search.py program i'm using with this mail. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: search.py Type: text/x-python Size: 1631 bytes Desc: not available URL: From steve at pearwood.info Mon Feb 24 16:40:48 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 25 Feb 2014 02:40:48 +1100 Subject: [Tutor] How to perform a google advanced search using python In-Reply-To: <1393231056.21872.YahooMailNeo@web190001.mail.sg3.yahoo.com> References: <1393231056.21872.YahooMailNeo@web190001.mail.sg3.yahoo.com> Message-ID: <20140224154048.GQ3684@ando> On Mon, Feb 24, 2014 at 04:37:36PM +0800, Xenai Hatsotep wrote: > I have a python program which performs a simple google search. What i > really want to do is perform an advanced search such that i can search > for pdf files and ppt files in google. Any help on this subject would > be very helpful. Sorry, I don't have an answer for you, but I have a warning. I am pretty sure that what you are doing is against Google's terms of service, and if they spot what you are doing they might ban you. I believe that they have an official API for doing searches programmatically. Ah yes, here you go: https://developers.google.com/custom-search/?csw=1 You might also consider Duck Duck Go: https://duckduckgo.com/api -- Steven From linux at barrowhillfarm.org.uk Mon Feb 24 17:07:55 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Mon, 24 Feb 2014 16:07:55 +0000 Subject: [Tutor] os.symlink can't find target Message-ID: <530B6E5B.6060304@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 My operating system is Linux (openSUSE 13.1). I'm trying to create symlinks. The following code: if pathList[j][-3:] == "mp3": linkName1 = pathList[j][0:-3] + "mp3" linkName2 = destPath + linkName1[len(sourcePath):] print 'Creating link %s -> %s' % (linkName2, pathList[j]) os.symlink(pathList[j], linkName2) fails with this error: Creating link /pollux/music/portable/testing/artists/Death in June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 -> /home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 Traceback (most recent call last): File "/home/bob/Documents/scripts/python/flac2mp3.py", line 101, in os.symlink(pathList[j], linkName2) OSError: [Errno 2] No such file or directory The same thing happens in ipython, when I type the paths in manually. I have tried escaping the spaces with '\', but the same error is generated. The file "/home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3" definitely exists. Thanks, Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 12:00pm up 11 days 20:00, 5 users, load average: 0.14, 0.17, 0.22 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMLblkACgkQ0Sr7eZJrmU4qfACdGc7/U8dN6I/NcyJsHA7ILzcV Ea4AoIHSbWLkg5eQ1Lo5rN7z0FTse+YM =+wrZ -----END PGP SIGNATURE----- From __peter__ at web.de Mon Feb 24 17:36:16 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Feb 2014 17:36:16 +0100 Subject: [Tutor] os.symlink can't find target References: <530B6E5B.6060304@barrowhillfarm.org.uk> Message-ID: Bob Williams wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > My operating system is Linux (openSUSE 13.1). > > I'm trying to create symlinks. The following code: > > if pathList[j][-3:] == "mp3": > linkName1 = pathList[j][0:-3] + "mp3" > linkName2 = destPath + linkName1[len(sourcePath):] > print 'Creating link %s -> %s' % (linkName2, pathList[j]) > os.symlink(pathList[j], linkName2) > > fails with this error: > > > Creating link /pollux/music/portable/testing/artists/Death in > June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 -> > /home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10 > Lifebooks.mp3 > Traceback (most recent call last): > File "/home/bob/Documents/scripts/python/flac2mp3.py", line 101, in > > os.symlink(pathList[j], linkName2) > OSError: [Errno 2] No such file or directory > > The same thing happens in ipython, when I type the paths in manually. > I have tried escaping the spaces with '\', but the same error is > generated. > > The file "/home/bob/music/artists/Death in June/1995 Rose Clouds Of > Holocaust/10 Lifebooks.mp3" definitely exists. > > Thanks, os.symlink(existing_file, symlink_to_create) fails with that error if the directory that shall contain the new symlink does not exist. You can create it before making the symlink with try: os.makedirs(os.path.dirname(symlink_to_create)) except OSError as err: # Assume the directory exists. # A thorough coder would check the errno here pass From sangeeth.saravanaraj at gmail.com Mon Feb 24 17:52:52 2014 From: sangeeth.saravanaraj at gmail.com (Sangeeth Saravanaraj) Date: Mon, 24 Feb 2014 22:22:52 +0530 Subject: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError Message-ID: I am trying to capture an object initiation and deletion events using the __call__() and __del__() methods with the following approach. class A(object): def __init__(self, klass): print "A::__init__()" self._klass = klass def __call__(self): print "A::__call__()" return self._klass() def __del__(self): print "A::__del__()" class Parent1(object): def __init__(self): print "Parent1:: __init__()" super(Parent1, self).__init__() class Parent2(object): def __init__(self): print "Parent2:: __init__()" super(Parent2, self).__init__() @A class B(Parent1, Parent2): def __init__(self): print "B::__init__()" super(B, self).__init__() def main(): b = B() if __name__ == "__main__": main() I decorate a class, say class B (whose object initiation and deletion I wanted to capture) with a decorator class A. Please note that the class B is derived from two classes - Parent1 & Parent2 and I want to use super() method to initialise the parent classes. When I executed the above code snippet, I ran into the following issue: A::__init__() A::__call__() B::__init__() Traceback (most recent call last): File "so.py", line 40, in main() File "so.py", line 36, in main b = B() File "so.py", line 10, in __call__ return self._klass() File "so.py", line 32, in __init__ super(B, self).__init__() TypeError: must be type, not A A::__del__() When I commented "super(B, self).__init__()" in the class B :: __init__() method, it returned an object of type B and I was able to see the prints in the __call__ and __del__ methods but the __init__() methods of the base classes (Parent1 & Parent2) are not called! >From the error message, what I could understand is - the object returned by A::__call__() is not of type B but of type A. But when I put a print in the A::__call__() I could see it returns an object of type B and not A. Now the question is - With this approach to capture the initiation and deletion events of an object, how do I initialise the base classes using super()? Or, is there any other better way to capture the __call__ and __del__ events for an object of a certain class - if so, how?! Thank you, Sangeeth PS: http://stackoverflow.com/questions/21826854/typeerror-when-using-super-method-with-class-decorator-for-a-derived-class -------------- next part -------------- An HTML attachment was scrubbed... URL: From vogernewsletters at yahoo.gr Mon Feb 24 17:54:04 2014 From: vogernewsletters at yahoo.gr (voger) Date: Mon, 24 Feb 2014 18:54:04 +0200 Subject: [Tutor] I can't understand where python class methods come from In-Reply-To: <530A6F3F.8080704@yahoo.gr> References: <530A6F3F.8080704@yahoo.gr> Message-ID: <530B792C.4040009@yahoo.gr> Thank you all for your responses. My first post on the list an I already got more than I asked for. :) From breamoreboy at yahoo.co.uk Mon Feb 24 17:56:46 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Feb 2014 16:56:46 +0000 Subject: [Tutor] os.symlink can't find target In-Reply-To: References: <530B6E5B.6060304@barrowhillfarm.org.uk> Message-ID: On 24/02/2014 16:36, Peter Otten wrote: > Bob Williams wrote: > >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> My operating system is Linux (openSUSE 13.1). >> >> I'm trying to create symlinks. The following code: >> >> if pathList[j][-3:] == "mp3": >> linkName1 = pathList[j][0:-3] + "mp3" >> linkName2 = destPath + linkName1[len(sourcePath):] >> print 'Creating link %s -> %s' % (linkName2, pathList[j]) >> os.symlink(pathList[j], linkName2) >> >> fails with this error: >> >> >> Creating link /pollux/music/portable/testing/artists/Death in >> June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 -> >> /home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10 >> Lifebooks.mp3 >> Traceback (most recent call last): >> File "/home/bob/Documents/scripts/python/flac2mp3.py", line 101, in >> >> os.symlink(pathList[j], linkName2) >> OSError: [Errno 2] No such file or directory >> >> The same thing happens in ipython, when I type the paths in manually. >> I have tried escaping the spaces with '\', but the same error is >> generated. >> >> The file "/home/bob/music/artists/Death in June/1995 Rose Clouds Of >> Holocaust/10 Lifebooks.mp3" definitely exists. >> >> Thanks, > > os.symlink(existing_file, symlink_to_create) > > fails with that error if the directory that shall contain the new symlink > does not exist. You can create it before making the symlink with > > try: > os.makedirs(os.path.dirname(symlink_to_create)) > except OSError as err: > # Assume the directory exists. > # A thorough coder would check the errno here > pass > Python 3.3+ allows finer grained error handling than that shown above, so you could catch FileExistsError, see http://legacy.python.org/dev/peps/pep-3151/ for the details. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From linux at barrowhillfarm.org.uk Mon Feb 24 18:03:51 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Mon, 24 Feb 2014 17:03:51 +0000 Subject: [Tutor] os.symlink can't find target In-Reply-To: References: <530B6E5B.6060304@barrowhillfarm.org.uk> Message-ID: <530B7B77.5000200@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 24/02/14 16:36, Peter Otten wrote: > os.symlink(existing_file, symlink_to_create) > > fails with that error if the directory that shall contain the new > symlink does not exist. You can create it before making the symlink > with > Peter, Many thanks. I was fixating on the existing_file, not realising I had to create a home for the symlink first. > try: os.makedirs(os.path.dirname(symlink_to_create)) except OSError > as err: # Assume the directory exists. # A thorough coder would > check the errno here pass Regards Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 12:00pm up 11 days 20:00, 5 users, load average: 0.14, 0.17, 0.22 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMLe3QACgkQ0Sr7eZJrmU6QmQCeLUSIh0l97T017KrIHXT92Xhd YuQAn2To2AOXNpbA4fZ+4i6Swt4RdsMg =NgLw -----END PGP SIGNATURE----- From linux at barrowhillfarm.org.uk Mon Feb 24 18:09:57 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Mon, 24 Feb 2014 17:09:57 +0000 Subject: [Tutor] os.symlink can't find target In-Reply-To: References: <530B6E5B.6060304@barrowhillfarm.org.uk> Message-ID: <530B7CE5.9000706@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 24/02/14 16:56, Mark Lawrence wrote: > On 24/02/2014 16:36, Peter Otten wrote: >> Bob Williams wrote: >> [...] >>> Thanks, >> >> os.symlink(existing_file, symlink_to_create) >> >> fails with that error if the directory that shall contain the new >> symlink does not exist. You can create it before making the >> symlink with >> >> try: os.makedirs(os.path.dirname(symlink_to_create)) except >> OSError as err: # Assume the directory exists. # A thorough coder >> would check the errno here pass >> > > Python 3.3+ allows finer grained error handling than that shown > above, so you could catch FileExistsError, see > http://legacy.python.org/dev/peps/pep-3151/ for the details. > I'm using a module (mutagen) elsewhere in this script, which only works in Python 2 (so far). Also, I'm fairly new to this, so getting things working takes precedence over 'good practice' like error trapping. But I'm also aware that it's best to establish good habits early on. Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 12:00pm up 11 days 20:00, 5 users, load average: 0.14, 0.17, 0.22 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMLfOMACgkQ0Sr7eZJrmU4IgQCgn5MeqNsCOgiS3QY8g2jjMooR 65oAnjcWZaHrfe78C2WvHjMNlqZqjgo1 =CnnC -----END PGP SIGNATURE----- From __peter__ at web.de Mon Feb 24 18:23:26 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Feb 2014 18:23:26 +0100 Subject: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError References: Message-ID: Sangeeth Saravanaraj wrote: > I am trying to capture an object initiation and deletion events using the > __call__() and __del__() methods with the following approach. Note that there is no guarantee that __dell__ will ever be called. Usually it is better to introduce a weakref with callback. > class A(object): > def __init__(self, klass): > print "A::__init__()" > self._klass = klass > > def __call__(self): > print "A::__call__()" > return self._klass() > > def __del__(self): > print "A::__del__()" > > class Parent1(object): > def __init__(self): > print "Parent1:: __init__()" > super(Parent1, self).__init__() > > class Parent2(object): > def __init__(self): > print "Parent2:: __init__()" > super(Parent2, self).__init__() > > @A > class B(Parent1, Parent2): > def __init__(self): > print "B::__init__()" > super(B, self).__init__() > > def main(): > b = B() > > if __name__ == "__main__": > main() > > > I decorate a class, say class B (whose object initiation and deletion I > wanted to capture) with a decorator class A. Please note that the class B > is derived from two classes - Parent1 & Parent2 and I want to use super() > method to initialise the parent classes. > > When I executed the above code snippet, I ran into the following issue: > > > A::__init__() > A::__call__() > B::__init__() > Traceback (most recent call last): > File "so.py", line 40, in > main() > File "so.py", line 36, in main > b = B() > File "so.py", line 10, in __call__ > return self._klass() > File "so.py", line 32, in __init__ > super(B, self).__init__() > TypeError: must be type, not A > A::__del__() > > > When I commented "super(B, self).__init__()" in the class B :: __init__() > method, it returned an object of type B and I was able to see the prints > in the __call__ and __del__ methods but the __init__() methods of the base > classes (Parent1 & Parent2) are not called! > > From the error message, what I could understand is - the object returned > by A::__call__() is not of type B but of type A. But when I put a print in > the A::__call__() I could see it returns an object of type B and not A. > > Now the question is - With this approach to capture the initiation and > deletion events of an object, how do I initialise the base classes using > super()? You'd have to introduce a naming convention or rewrite your class to be aware of the wrapping in some way: @A class B(Parent1, Parent2): def __init__(self): print "B::__init__()" super(B._klass, self).__init__() Not pretty. > Or, is there any other better way to capture the __call__ and __del__ > events for an object of a certain class - if so, how?! Most certainly, but you have to give some details about what you are up to first. > PS: > http://stackoverflow.com/questions/21826854/typeerror-when-using-super- method-with-class-decorator-for-a-derived-class From dyoo at hashcollision.org Mon Feb 24 19:55:58 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 24 Feb 2014 10:55:58 -0800 Subject: [Tutor] How to perform a google advanced search using python In-Reply-To: <20140224154048.GQ3684@ando> References: <1393231056.21872.YahooMailNeo@web190001.mail.sg3.yahoo.com> <20140224154048.GQ3684@ando> Message-ID: > Ah yes, here you go: > > https://developers.google.com/custom-search/?csw=1 Also see the "Indexable file types" help topic: https://support.google.com/webmasters/answer/35287?hl=en From dyoo at hashcollision.org Mon Feb 24 20:18:13 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 24 Feb 2014 11:18:13 -0800 Subject: [Tutor] i dont understand this code In-Reply-To: References: <001201cf2fc9$7b24e060$716ea120$@com> Message-ID: It's also a bit unreasonable to ask us to reverse-engineer code that is orginally CRC-16 code. Whoever you got this code from is violating the GPL by stripping out the comments or the COPYRIGHT license from the original sources. This is perhaps unintentional. Please ask them to correct the problem. The original sources appear to have come from: http://dogber1.blogspot.com/2009/05/table-of-reverse-engineered-bios.html From sangeeth.saravanaraj at gmail.com Mon Feb 24 20:19:34 2014 From: sangeeth.saravanaraj at gmail.com (Sangeeth Saravanaraj) Date: Tue, 25 Feb 2014 00:49:34 +0530 Subject: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError In-Reply-To: References: Message-ID: On Mon, Feb 24, 2014 at 10:53 PM, Peter Otten <__peter__ at web.de> wrote: > Sangeeth Saravanaraj wrote: > > > I am trying to capture an object initiation and deletion events using the > > __call__() and __del__() methods with the following approach. > > Note that there is no guarantee that __dell__ will ever be called. Usually > it is better to introduce a weakref with callback. > > > class A(object): > > def __init__(self, klass): > > print "A::__init__()" > > self._klass = klass > > > > def __call__(self): > > print "A::__call__()" > > return self._klass() > > > > def __del__(self): > > print "A::__del__()" > > > > class Parent1(object): > > def __init__(self): > > print "Parent1:: __init__()" > > super(Parent1, self).__init__() > > > > class Parent2(object): > > def __init__(self): > > print "Parent2:: __init__()" > > super(Parent2, self).__init__() > > > > @A > > class B(Parent1, Parent2): > > def __init__(self): > > print "B::__init__()" > > super(B, self).__init__() > > > > def main(): > > b = B() > > > > if __name__ == "__main__": > > main() > > > > > > I decorate a class, say class B (whose object initiation and deletion I > > wanted to capture) with a decorator class A. Please note that the class B > > is derived from two classes - Parent1 & Parent2 and I want to use super() > > method to initialise the parent classes. > > > > When I executed the above code snippet, I ran into the following issue: > > > > > > A::__init__() > > A::__call__() > > B::__init__() > > Traceback (most recent call last): > > File "so.py", line 40, in > > main() > > File "so.py", line 36, in main > > b = B() > > File "so.py", line 10, in __call__ > > return self._klass() > > File "so.py", line 32, in __init__ > > super(B, self).__init__() > > TypeError: must be type, not A > > A::__del__() > > > > > > When I commented "super(B, self).__init__()" in the class B :: __init__() > > method, it returned an object of type B and I was able to see the prints > > in the __call__ and __del__ methods but the __init__() methods of the > base > > classes (Parent1 & Parent2) are not called! > > > > From the error message, what I could understand is - the object returned > > by A::__call__() is not of type B but of type A. But when I put a print > in > > the A::__call__() I could see it returns an object of type B and not A. > > > > Now the question is - With this approach to capture the initiation and > > deletion events of an object, how do I initialise the base classes using > > super()? > > You'd have to introduce a naming convention or rewrite your class to be > aware of the wrapping in some way: > > @A > class B(Parent1, Parent2): > def __init__(self): > print "B::__init__()" > super(B._klass, self).__init__() > > Not pretty. > > > Or, is there any other better way to capture the __call__ and __del__ > > events for an object of a certain class - if so, how?! > > Most certainly, but you have to give some details about what you are up to > first. > Sorry, I should have described what I was trying! I want to create a decorator which should do the following things: - When an object of the decorated class is created, the objects name (say the value of the incoming "id" argument) should be stored as a record in a table in a database. - When an object of the decorated class is deleted, the record with this deleted objects name (i.e. object.id) should be removed from the table. You can safely assume that all the database operations are working fine! Now, for example - consider the following snippet: @saveme class A(object): def __init__(self, id): self.id = id @saveme class B(object): def __init__(self, id): self.id = id "saveme" should do what I have explained earlier. a1 = A("A1") a2 = A("A2") a3 = A("A3") b1 = B("B1") b2 = B("B2") At this point if I query and print all the records in a table, I should get the following: output: ["A1", "A2", "A3", "B1", "B2"] del a1 del a2 del a3 del b1 del b2 At this point, all entries in the table should be deleted; query should return an empty list! And, I want to highlight that the classes that are being decorated with "saveme" can de derived classes too! What is the best way to do this?! Thank you, Sangeeth > > > PS: > > http://stackoverflow.com/questions/21826854/typeerror-when-using-super- > method-with-class-decorator-for-a-derived-class > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Feb 24 21:09:06 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Feb 2014 21:09:06 +0100 Subject: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError References: Message-ID: Sangeeth Saravanaraj wrote: > On Mon, Feb 24, 2014 at 10:53 PM, Peter Otten <__peter__ at web.de> wrote: > >> Sangeeth Saravanaraj wrote: >> >> > I am trying to capture an object initiation and deletion events using >> > the __call__() and __del__() methods with the following approach. >> >> Note that there is no guarantee that __dell__ will ever be called. >> Usually it is better to introduce a weakref with callback. >> >> > class A(object): >> > def __init__(self, klass): >> > print "A::__init__()" >> > self._klass = klass >> > >> > def __call__(self): >> > print "A::__call__()" >> > return self._klass() >> > >> > def __del__(self): >> > print "A::__del__()" >> > >> > class Parent1(object): >> > def __init__(self): >> > print "Parent1:: __init__()" >> > super(Parent1, self).__init__() >> > >> > class Parent2(object): >> > def __init__(self): >> > print "Parent2:: __init__()" >> > super(Parent2, self).__init__() >> > >> > @A >> > class B(Parent1, Parent2): >> > def __init__(self): >> > print "B::__init__()" >> > super(B, self).__init__() >> > >> > def main(): >> > b = B() >> > >> > if __name__ == "__main__": >> > main() >> > >> > >> > I decorate a class, say class B (whose object initiation and deletion I >> > wanted to capture) with a decorator class A. Please note that the class >> > B is derived from two classes - Parent1 & Parent2 and I want to use >> > super() method to initialise the parent classes. >> > >> > When I executed the above code snippet, I ran into the following issue: >> > >> > >> > A::__init__() >> > A::__call__() >> > B::__init__() >> > Traceback (most recent call last): >> > File "so.py", line 40, in >> > main() >> > File "so.py", line 36, in main >> > b = B() >> > File "so.py", line 10, in __call__ >> > return self._klass() >> > File "so.py", line 32, in __init__ >> > super(B, self).__init__() >> > TypeError: must be type, not A >> > A::__del__() >> > >> > >> > When I commented "super(B, self).__init__()" in the class B :: >> > __init__() method, it returned an object of type B and I was able to >> > see the prints in the __call__ and __del__ methods but the __init__() >> > methods of the >> base >> > classes (Parent1 & Parent2) are not called! >> > >> > From the error message, what I could understand is - the object >> > returned by A::__call__() is not of type B but of type A. But when I >> > put a print >> in >> > the A::__call__() I could see it returns an object of type B and not A. >> > >> > Now the question is - With this approach to capture the initiation and >> > deletion events of an object, how do I initialise the base classes >> > using super()? >> >> You'd have to introduce a naming convention or rewrite your class to be >> aware of the wrapping in some way: >> >> @A >> class B(Parent1, Parent2): >> def __init__(self): >> print "B::__init__()" >> super(B._klass, self).__init__() >> >> Not pretty. >> >> > Or, is there any other better way to capture the __call__ and __del__ >> > events for an object of a certain class - if so, how?! >> >> Most certainly, but you have to give some details about what you are up >> to first. >> > > Sorry, I should have described what I was trying! > > I want to create a decorator which should do the following things: > > - When an object of the decorated class is created, the objects name > (say the value of the incoming "id" argument) should be stored as a > record in a table in a database. > - When an object of the decorated class is deleted, the record with > this deleted objects name (i.e. object.id) should be removed from the > table. > > You can safely assume that all the database operations are working fine! > > Now, for example - consider the following snippet: > > @saveme > class A(object): > def __init__(self, id): > self.id = id > > @saveme > class B(object): > def __init__(self, id): > self.id = id > > "saveme" should do what I have explained earlier. > > a1 = A("A1") > a2 = A("A2") > a3 = A("A3") > b1 = B("B1") > b2 = B("B2") > > At this point if I query and print all the records in a table, I should > get the following: > output: ["A1", "A2", "A3", "B1", "B2"] > > del a1 > del a2 > del a3 > del b1 > del b2 > > At this point, all entries in the table should be deleted; query should > return an empty list! > > And, I want to highlight that the classes that are being decorated with > "saveme" can de derived classes too! > > What is the best way to do this?! I'm sorry, after a bit of try-and-error I could not come up with a good way to write such a decorator. My best effort so far uses inheritance: import itertools import weakref _registry = weakref.WeakValueDictionary() _next_id = lambda count=itertools.count(): next(count) def show(): print(list(_registry.values())) class Registered(object): def __init__(self, id=None): if id is None: id = _next_id() self.id = id _registry[id] = self def __repr__(self): return "{}(id={!r})".format(self.__class__.__name__, self.id) class A(Registered): pass class B(Registered): pass class C(B): pass a1 = A() b1 = B() c1 = C() show() del a1 show() b2 = B() show() del b1 del c1 del b2 show() From fomcl at yahoo.com Mon Feb 24 21:29:35 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 24 Feb 2014 12:29:35 -0800 (PST) Subject: [Tutor] subprocess.call list vs. str argument Message-ID: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> Hi, In the code below, cmd1 and cmd2 are equivalent, as in: " ".join(cmd1) == cmd2. But the first example returns a code 2, whereas the second runs successfully. What is the difference? I prefer using a list as it looks a little cleaner. Btw, shell=True is needed here. # Python 2.7.3 (default, Jan? 2 2013, 13:56:14) [GCC 4.7.2] on linux2 import subprocess #1# returns retcode 2 (whatever error that maybe) title, author, version = "title", "author", "1.0.0" output_dir, input_dir = '/tmp/input', '/tmp/output' cmd1 = [r'sphinx-apidoc', ?????? r'-f -F', ?????? r'-H', '"%s"' % title, ?????? r'-A', '"%s"' % author, ?????? r'-V', '"%s"' % version, ?????? r'-o', output_dir, input_dir] retcode = subprocess.call(cmd1, shell=True) assert not retcode, retcode #2# returns retcode 0 (succes) cmd2 = (r'sphinx-apidoc ' ?????? r'-f -F ' ?????? r'-H "%(title)s" ' ?????? r'-A "%(author)s" ' ?????? r'-V "%(version)s" ' ?????? r'-o %(output_dir)s %(input_dir)s') % locals() retcode = subprocess.call(cmd2, shell=True) assert not retcode, retcode # no AssertionError assert " ".join(cmd1) == cmd2 Thanks in advance! ? Regards, 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 dyoo at hashcollision.org Mon Feb 24 21:50:24 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 24 Feb 2014 12:50:24 -0800 Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: > cmd1 = [r'sphinx-apidoc', > r'-f -F', This part looks suspicious. Are you sure you don't mean: '-f', '-F' here? They need to be separate arguments. Also, you mention: > Btw, shell=True is needed here. Why do you need shell expansion on the arguments? This can be dangerous unless you know what you're doing. See all the red-backgrounded warnings the subprocess documentation. For example: http://docs.python.org/2/library/subprocess.html#frequently-used-arguments From __peter__ at web.de Mon Feb 24 21:54:08 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Feb 2014 21:54:08 +0100 Subject: [Tutor] subprocess.call list vs. str argument References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > Hi, > > In the code below, cmd1 and cmd2 are equivalent, as in: " ".join(cmd1) == > cmd2. But the first example returns a code 2, whereas the second runs > successfully. What is the difference? I prefer using a list as it looks a > little cleaner. Btw, shell=True is needed here. > > > # Python 2.7.3 (default, Jan 2 2013, 13:56:14) [GCC 4.7.2] on linux2 > > import subprocess > > #1# returns retcode 2 (whatever error that maybe) > title, author, version = "title", "author", "1.0.0" > output_dir, input_dir = '/tmp/input', '/tmp/output' > cmd1 = [r'sphinx-apidoc', > r'-f -F', > r'-H', '"%s"' % title, "title" becomes \"title\", i. e. Python puts in an extra effort to have the quotes survive the subsequent parsing process of the shell: >>> print subprocess.list2cmdline(['"title"']) \"title\" > r'-A', '"%s"' % author, > r'-V', '"%s"' % version, > r'-o', output_dir, input_dir] > retcode = subprocess.call(cmd1, shell=True) > assert not retcode, retcode > > #2# returns retcode 0 (succes) > cmd2 = (r'sphinx-apidoc ' > r'-f -F ' > r'-H "%(title)s" ' > r'-A "%(author)s" ' > r'-V "%(version)s" ' > r'-o %(output_dir)s %(input_dir)s') % locals() > > retcode = subprocess.call(cmd2, shell=True) > assert not retcode, retcode > > # no AssertionError > assert " ".join(cmd1) == cmd2 > > > > Thanks in advance! > > Regards, > > 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? > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Mon Feb 24 21:59:04 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Feb 2014 21:59:04 +0100 Subject: [Tutor] subprocess.call list vs. str argument References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: Peter Otten wrote: >> r'-f -F', >> r'-H', '"%s"' % title, > > "title" becomes \"title\", i. e. Python puts in an extra effort to have > the quotes survive the subsequent parsing process of the shell: > >>>> print subprocess.list2cmdline(['"title"']) > \"title\" Forget that :( Danny spotted the real problem. From dyoo at hashcollision.org Mon Feb 24 22:48:49 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 24 Feb 2014 13:48:49 -0800 Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: There are a few issues there. I'd also recommend not trying to shell-quote these manually, # in the argument list of os.subprocess: r'-H', '"%s"' % title, r'-A', '"%s"' % author, r'-V', '"%s"' % version, Rather, just do the simpler thing: r'-H', title, r'-A', author, r'-V', version, in conjunction with passing the "shell=False" keyword argument. Don't escape. Just pass the arguments as is. As far as I can tell, trying to do shell escaping is not only unnecessary here, but doing without it makes the code cleaner safer. Maybe there's another reason why Albert-Jan's situation is different enough that "shell=True" is necessary, but the default situation should be to avoid it. From dyoo at hashcollision.org Mon Feb 24 23:01:02 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 24 Feb 2014 14:01:02 -0800 Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: Last comment (apologies for being so fragmented!). I don't know why the literal strings there are raw there. Altogether, I'd expect: ############################################# cmd1 = ['sphinx-apidoc', '-f', '-F', '-H', title, '-A', author, '-V', version, '-o', output_dir, input_dir] retcode = subprocess.call(cmd1, shell=False) ############################################# From denis.spir at gmail.com Tue Feb 25 00:52:16 2014 From: denis.spir at gmail.com (spir) Date: Tue, 25 Feb 2014 00:52:16 +0100 Subject: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError In-Reply-To: References: Message-ID: <530BDB30.3020902@gmail.com> On 02/24/2014 08:19 PM, Sangeeth Saravanaraj wrote: > Sorry, I should have described what I was trying! > > I want to create a decorator which should do the following things: > > - When an object of the decorated class is created, the objects name > (say the value of the incoming "id" argument) should be stored as a record > in a table in a database. > - When an object of the decorated class is deleted, the record with this > deleted objects name (i.e. object.id) should be removed from the table. > > You can safely assume that all the database operations are working fine! > > Now, for example - consider the following snippet: > > @saveme > class A(object): > def __init__(self, id): > self.id = id > > @saveme > class B(object): > def __init__(self, id): > self.id = id > > "saveme" should do what I have explained earlier. > > a1 = A("A1") > a2 = A("A2") > a3 = A("A3") > b1 = B("B1") > b2 = B("B2") > > At this point if I query and print all the records in a table, I should get > the following: > output: ["A1", "A2", "A3", "B1", "B2"] > > del a1 > del a2 > del a3 > del b1 > del b2 > > At this point, all entries in the table should be deleted; query should > return an empty list! > > And, I want to highlight that the classes that are being decorated with > "saveme" can de derived classes too! > > What is the best way to do this?! > > Thank you, > > Sangeeth Your problem looks like a typical "crosscutting" (transversal) concern addressed by AOP (Aspect Oriented Programming). Their usual example is in fact logging. Look at the wikipedia page: https://en.wikipedia.org/wiki/Aspect-oriented_programming Not that it would help you solve it _in python_, but this may serve at least to better understand what kind of problem you are actually facing; and why it is annoying in programming (with common languages); what may be your options. [I have no better approach than yours, using magic metamethods, and a decorator to wrap it all.] d From sangeeth.saravanaraj at gmail.com Tue Feb 25 01:49:37 2014 From: sangeeth.saravanaraj at gmail.com (Sangeeth Saravanaraj) Date: Tue, 25 Feb 2014 06:19:37 +0530 Subject: [Tutor] Class decorator on a derived class not initialising the base classes using super - TypeError In-Reply-To: <530BDB30.3020902@gmail.com> References: <530BDB30.3020902@gmail.com> Message-ID: Peter, Spir - thanks for your time and effort! I am posting this query to few more Python mailers. Thank you, Sangeeth On Tue, Feb 25, 2014 at 5:22 AM, spir wrote: > On 02/24/2014 08:19 PM, Sangeeth Saravanaraj wrote: > >> Sorry, I should have described what I was trying! >> >> I want to create a decorator which should do the following things: >> >> - When an object of the decorated class is created, the objects name >> >> (say the value of the incoming "id" argument) should be stored as a >> record >> in a table in a database. >> - When an object of the decorated class is deleted, the record with >> this >> >> deleted objects name (i.e. object.id) should be removed from the >> table. >> >> You can safely assume that all the database operations are working fine! >> >> Now, for example - consider the following snippet: >> >> @saveme >> class A(object): >> def __init__(self, id): >> self.id = id >> >> @saveme >> class B(object): >> def __init__(self, id): >> self.id = id >> >> "saveme" should do what I have explained earlier. >> >> a1 = A("A1") >> a2 = A("A2") >> a3 = A("A3") >> b1 = B("B1") >> b2 = B("B2") >> >> At this point if I query and print all the records in a table, I should >> get >> the following: >> output: ["A1", "A2", "A3", "B1", "B2"] >> >> del a1 >> del a2 >> del a3 >> del b1 >> del b2 >> >> At this point, all entries in the table should be deleted; query should >> return an empty list! >> >> And, I want to highlight that the classes that are being decorated with >> "saveme" can de derived classes too! >> >> What is the best way to do this?! >> >> Thank you, >> >> Sangeeth >> > > Your problem looks like a typical "crosscutting" (transversal) concern > addressed by AOP (Aspect Oriented Programming). Their usual example is in > fact logging. Look at the wikipedia page: > https://en.wikipedia.org/wiki/Aspect-oriented_programming > > Not that it would help you solve it _in python_, but this may serve at > least to better understand what kind of problem you are actually facing; > and why it is annoying in programming (with common languages); what may be > your options. > > [I have no better approach than yours, using magic metamethods, and a > decorator to wrap it all.] > > > d > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregg.martinson at gmail.com Tue Feb 25 01:59:24 2014 From: gregg.martinson at gmail.com (Gregg Martinson) Date: Mon, 24 Feb 2014 18:59:24 -0600 Subject: [Tutor] Why does the last loop not work? Message-ID: I am trying to generate a list of teams using objects that I collect into a list that I can cycle through. But when I run the last loop there is nothing produced. I am pretty sure it has to do with my syntax for the list and the substitution of a a local variable but I can't figure out how to make it work. Any help would be appreciated. I am working my way though *Learning Python*, but its a long slog. #!/usr/bin/env python def printit (aff,neg): print (aff, "\t",neg,"\tTBD\tTBD") def header (r): print ("##############################") print ("### Round: ",r," ####") print ("##############################") print ("Aff\tNeg\tJudge\tRoom") class Team(object): code = "" # The class "constructor" - It's actually an initializer def __init__(self,code): self.code = code print ("code is: ",code) self.competitors=[] def print_team(self): print("team code is: ",self.code) print("debated:",end=" ") for x in self.competitors: print (x) def debated(self,otherTeam): print (x) self.competitors.append(x) def giveCode(self): return self.code def make_team(code): team = Team(code) return team #MAIN Program# myTeamCodes=["a","aa","b","bb","c","cc","d"] # Make teams myTeams=[]#list of teams for x in myTeamCodes: myteam=make_team(x) myTeams.append(myteam) # problem is that myTeams has no value outside of the loop for x in myTeams: x.print_team -- http://about.me/greggmartinson -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Tue Feb 25 11:26:35 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Tue, 25 Feb 2014 11:26:35 +0100 Subject: [Tutor] Why does the last loop not work? In-Reply-To: References: Message-ID: On Tue, Feb 25, 2014 at 1:59 AM, Gregg Martinson wrote: > # problem is that myTeams has no value outside of the loop > for x in myTeams: > x.print_team No, that is not the problem. The problem is, you?re missing parentheses there and are not executing the print_team method, just referring to it. Do this: for x in myTeams: x.print_team() This causes this output: [kwpolska at kw-cassandra /tmp]% python foo.py code is: a code is: aa code is: b code is: bb code is: c code is: cc code is: d team code is: a debated: team code is: aa debated: team code is: b debated: team code is: bb debated: team code is: c debated: team code is: cc debated: team code is: d debated: [kwpolska at kw-cassandra /tmp]% Which is kinda wrong. But that?s the fault of your print_team() and lack of competitors. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From alan.gauld at btinternet.com Tue Feb 25 11:44:15 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Feb 2014 10:44:15 +0000 Subject: [Tutor] Why does the last loop not work? In-Reply-To: References: Message-ID: On 25/02/14 00:59, Gregg Martinson wrote: > there is nothing produced. I am pretty sure it has to do with my syntax > for the list and the substitution of a a local variable Chris has answered your question but there are a couple of general points on your code below... > def header (r): > print ("##############################") > print ("### Round: ",r," ####") > print ("##############################") > print ("Aff\tNeg\tJudge\tRoom") Rather than having multiple calls to print you could do the same thing with a single call using a triple quoted string. Its largely a matter of taste. > class Team(object): > code = "" This makes code a class level attribute. I don't think that's what you want. And you don't seem to use it anywhere. > # The class "constructor" - It's actually an initializer > def __init__(self,code): > self.code = code This creates an instance attribute which is distinct to your class variable above. > print ("code is: ",code) > self.competitors=[] > def print_team(self): > print("team code is: ",self.code) > print("debated:",end=" ") > for x in self.competitors: > print (x) > > def debated(self,otherTeam): > print (x) > self.competitors.append(x) > def giveCode(self): > return self.code In Python its idiomatic to not use getter methods like this. Unless you need to use a method you can just access code directly. > def make_team(code): > team = Team(code) > return team Unless you u=inrtend to do more magic here this is pretty much redundant. Calling spam = make_team(code) is no better than calling spam = Team(code) And it takes more typing, more reading to understand and is slower. > #MAIN Program# > myTeamCodes=["a","aa","b","bb","c","cc","d"] > # Make teams > myTeams=[]#list of teams > for x in myTeamCodes: > myteam=make_team(x) > myTeams.append(myteam) I don't know if you've discovered list comprehensions yet but this pattern is exactly what they do somelist = [] for item in anotherList: somelist.append(somefunc(item) So when you see that pattern consider replacing it with: someList = [someFunc(item) for item in anotherList] Or in your case: myTeams = [Team(code) for code in myTeamCodes] HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From denis.spir at gmail.com Tue Feb 25 11:49:11 2014 From: denis.spir at gmail.com (spir) Date: Tue, 25 Feb 2014 11:49:11 +0100 Subject: [Tutor] Why does the last loop not work? In-Reply-To: References: Message-ID: <530C7527.3070107@gmail.com> On 02/25/2014 01:59 AM, Gregg Martinson wrote: > I am trying to generate a list of teams using objects that I collect into a > list that I can cycle through. But when I run the last loop there is > nothing produced. Look at your last line of code: x.print_team This is just the _name_ of the method print_team, for x. To call it, must add () even it take takes no parameter. A few notes below. > I am pretty sure it has to do with my syntax for the > list and the substitution of a a local variable but I can't figure out how > to make it work. Any help would be appreciated. I am working my way > though *Learning Python*, but its a long slog. > > #!/usr/bin/env python > def printit (aff,neg): > print (aff, "\t",neg,"\tTBD\tTBD") You don't seem to use this func. > def header (r): > print ("##############################") > print ("### Round: ",r," ####") > print ("##############################") > print ("Aff\tNeg\tJudge\tRoom") May be called 'write-header'? > class Team(object): > code = "" > > > > Why so much vertical space? > # The class "constructor" - It's actually an initializer > def __init__(self,code): > self.code = code > print ("code is: ",code) > self.competitors=[] Here one blank line may help readability. > def print_team(self): > print("team code is: ",self.code) > print("debated:",end=" ") > for x in self.competitors: > print (x) > Instead of print_team, you should use Python's builtin tools for this purpose. [1] > def debated(self,otherTeam): > print (x) > self.competitors.append(x) some space here, again? > def giveCode(self): > return self.code > > > def make_team(code): > team = Team(code) > return team This function (a "factory", that creates new objects) is not needed in Python. Classes act as factories for their instances, also in syntax. Just as you do above: team = Team(code) > #MAIN Program# > myTeamCodes=["a","aa","b","bb","c","cc","d"] > # Make teams > myTeams=[]#list of teams > for x in myTeamCodes: > myteam=make_team(x) myteam = Team(code) > myTeams.append(myteam) > # problem is that myTeams has no value outside of the loop You assert this, but did you try? Did you add a debug print like: print(myTeams) ? > for x in myTeams: > x.print_team d [1] There are two "magic methods" intended for object written output: * __repr__ is for programmer feedback, when you control, debug, diagnose... (on the terminal in general) The best thing in general is to reproduce the original notation, as in program source. So, in your case, __repr__ would produce "Team(code)". * __str__ is for user information on the user interface (terminal, GUI, game screen...) The difference with your print_team is that they produce the strings, they don't write directly; python magically uses such strings when you ask for an object to be written out. Then you can freely use that in print statement directly, or in in composite strings. # instead of: team.print_team print(team) # eg "Team('c') print("team #%d --> %r" %(i, team)) # eg "team #3 --> Team('c')" __repr__ corresponds to to the code %r, __str__ to %s; whenever they differ, use %r for your own feedback in general. From james at uplinkzero.com Tue Feb 25 11:52:19 2014 From: james at uplinkzero.com (James Chapman) Date: Tue, 25 Feb 2014 10:52:19 +0000 Subject: [Tutor] When to use multiprocessing Managers? Message-ID: Hello tutors I'm curious about managers and when to use them. For example, I see they offer a Queue() for sharing a Q between processes, but if I create a Q in the parent process and pass it down to child processes, then they can put messages into that Q just fine, and I presume the same thing for other objects available under the managers package. So unless the other process is on a different machine, is there a reason to use a manager? Does anyone have any use case examples or snippets I could look at even? Thanks in advance James From fomcl at yahoo.com Tue Feb 25 20:52:55 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 25 Feb 2014 11:52:55 -0800 (PST) Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <1393357975.56883.YahooMailNeo@web163806.mail.gq1.yahoo.com> ----- Original Message ----- > From: Danny Yoo > To: Peter Otten <__peter__ at web.de> > Cc: Python Tutor Mailing List > Sent: Monday, February 24, 2014 11:01 PM > Subject: Re: [Tutor] subprocess.call list vs. str argument > > Last comment (apologies for being so fragmented!).? I don't know why > the literal strings there are raw there.? Altogether, I'd expect: > > ############################################# > cmd1 = ['sphinx-apidoc', > ? ? ? '-f', > ? ? ? '-F', > ? ? ? '-H', title, > ? ? ? '-A', author, > ? ? ? '-V', version, > ? ? ? '-o', output_dir, > ? ? ? input_dir] > retcode = subprocess.call(cmd1, shell=False) > > ############################################# Hi Danny, Peter, Thanks for helping me. Danny, your example works indeed and it is also very readable. And now I do not need to use shell=True anymore. The raw strings were a leftover from earlier attempts that contained the entire path (not even relevant under Linux, but I still did it). Here is why I used "shell=True" before. Is it related to the file paths? ??? cmd = (r'sphinx-apidoc ' ?????????? r'-f -F ' ?????????? r'-H "%(title)s" ' ?????????? r'-A "%(author)s" ' ?????????? r'-V "%(version)s" ' ?????????? r'-o %(output_dir)s %(input_dir)s') % locals() ??? retcode = subprocess.call(cmd) Traceback (most recent call last): ? File "/home/albertjan/Downloads/documenter.py", line 188, in ??? rst_to_html(input_dir, output_dir, title="Test", author=getpass.getuser(), version="1.0.0") ? File "/home/albertjan/Downloads/documenter.py", line 118, in rst_to_html ??? retcode = subprocess.call(cmd) ? File "/usr/lib/python2.7/subprocess.py", line 493, in call ??? return Popen(*popenargs, **kwargs).wait() ? File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ ??? errread, errwrite) ? File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child ??? raise child_exception OSError: [Errno 2] No such file or directory regards, Albert-Jan From davea at davea.name Tue Feb 25 21:41:44 2014 From: davea at davea.name (Dave Angel) Date: Tue, 25 Feb 2014 15:41:44 -0500 (EST) Subject: [Tutor] subprocess.call list vs. str argument References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1393357975.56883.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam Wrote in message: > > > ----- Original Message ----- > >> From: Danny Yoo >> To: Peter Otten <__peter__ at web.de> >> Cc: Python Tutor Mailing List >> Sent: Monday, February 24, 2014 11:01 PM >> Subject: Re: [Tutor] subprocess.call list vs. str argument >> >> Last comment (apologies for being so fragmented!). I don't know why >> the literal strings there are raw there. Altogether, I'd expect: >> >> ############################################# >> cmd1 = ['sphinx-apidoc', >> '-f', >> '-F', >> '-H', title, >> '-A', author, >> '-V', version, >> '-o', output_dir, >> input_dir] >> retcode = subprocess.call(cmd1, shell=False) >> >> ############################################# > > > Hi Danny, Peter, > > Thanks for helping me. Danny, your example works indeed and it is also very readable. And now I do not need to use shell=True anymore. The raw strings were a leftover from earlier attempts that contained the entire path (not even relevant under Linux, but I still did it). Here is why I used "shell=True" before. Is it related to the file paths? > > cmd = (r'sphinx-apidoc ' > r'-f -F ' > r'-H "%(title)s" ' > r'-A "%(author)s" ' > r'-V "%(version)s" ' > r'-o %(output_dir)s %(input_dir)s') % locals() > retcode = subprocess.call(cmd) > Traceback (most recent call last): > File "/home/albertjan/Downloads/documenter.py", line 188, in > rst_to_html(input_dir, output_dir, title="Test", author=getpass.getuser(), version="1.0.0") > File "/home/albertjan/Downloads/documenter.py", line 118, in rst_to_html > retcode = subprocess.call(cmd) > File "/usr/lib/python2.7/subprocess.py", line 493, in call > return Popen(*popenargs, **kwargs).wait() > File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ > errread, errwrite) > File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > Here you are feeding a string to the call function, while Danny was using a list. With a string, you must use shell=True, so the shell can turn it into a list. Usually much easier to use a list in the first place. -- DaveA From eryksun at gmail.com Tue Feb 25 21:37:31 2014 From: eryksun at gmail.com (eryksun) Date: Tue, 25 Feb 2014 15:37:31 -0500 Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: <1393357975.56883.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1393357975.56883.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Tue, Feb 25, 2014 at 2:52 PM, Albert-Jan Roskam wrote: > Here is why I used "shell=True" before. Is it related to the > file paths? > > cmd = (r'sphinx-apidoc ' > r'-f -F ' > r'-H "%(title)s" ' > r'-A "%(author)s" ' > r'-V "%(version)s" ' > r'-o %(output_dir)s %(input_dir)s') % locals() > retcode = subprocess.call(cmd) Take a look at the code in subprocess._execute_child for POSIX platforms: if isinstance(args, types.StringTypes): args = [args] else: args = list(args) if shell: args = ["/bin/sh", "-c"] + args if executable: args[0] = executable if executable is None: executable = args[0] It calls os.execvp in the child process, for which you want the executable file argument to be 'sphinx-apidoc'. But without shell=True, you can see that Popen uses your entire cmd string as the executable. FYI, in Windows the situation is different. CreateProcess takes a string argument, so the setup code changes to the following: if not isinstance(args, types.StringTypes): args = list2cmdline(args) # Process startup details if startupinfo is None: startupinfo = STARTUPINFO() if None not in (p2cread, c2pwrite, errwrite): startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES startupinfo.hStdInput = p2cread startupinfo.hStdOutput = c2pwrite startupinfo.hStdError = errwrite if shell: startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW startupinfo.wShowWindow = _subprocess.SW_HIDE comspec = os.environ.get("COMSPEC", "cmd.exe") args = '{} /c "{}"'.format (comspec, args) It's fine to use a string for args in Windows, and you may need to if the program parses the command line differently than list2cmdline, which escapes the arguments according to the rules used by Microsoft's CRT. From dyoo at hashcollision.org Tue Feb 25 21:47:48 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 25 Feb 2014 12:47:48 -0800 Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1393357975.56883.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: See the comment about 'args' in: http://docs.python.org/2/library/subprocess.html#frequently-used-arguments which says: """args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.""" This is an unfortunate pain-point in the subprocess API. Personally, I think that having subprocess.call optionally accept a single string is a wrong API decision because it causes so much confusion. You can tell there's a schizophrenia in that part of the documentation: it says something to the effect of, "If you want to use a single string, you have to use shell=True". And a few paragraphs later, it says, "But don't use shell=True!" I would strongly suggest not trying to use the single string interface to subprocess: it's too easy to get wrong. From davea at davea.name Tue Feb 25 22:54:42 2014 From: davea at davea.name (Dave Angel) Date: Tue, 25 Feb 2014 16:54:42 -0500 (EST) Subject: [Tutor] subprocess.call list vs. str argument References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1393357975.56883.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: eryksun Wrote in message: > > > FYI, in Windows the situation is different. CreateProcess takes a > string argument, so the setup code changes to the following: > > > It's fine to use a string for args in Windows, and you may need to if > the program parses the command line differently than list2cmdline, > which escapes the arguments according to the rules used by Microsoft's > CRT. CreateProcess has its own design bobbles as well. For example, if you forget to put quotes around the program name, it will happily try to add ".exe" to *multiple* places in the hopes that one of them will work. Adding a file c:\program.exe to a system will blow up lots of programs that were working by mistake for years. -- DaveA From eryksun at gmail.com Tue Feb 25 23:30:28 2014 From: eryksun at gmail.com (eryksun) Date: Tue, 25 Feb 2014 17:30:28 -0500 Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: References: <1393273775.79028.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1393357975.56883.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Tue, Feb 25, 2014 at 4:54 PM, Dave Angel wrote: > CreateProcess has its own design bobbles as well. For example, if > you forget to put quotes around the program name, it will > happily try to add ".exe" to *multiple* places in the hopes that > one of them will work. > > Adding a file c:\program.exe to a system will blow up lots of > programs that were working by mistake for years. Yes, using a string requires quoting the path for the executable if you aren't using lpApplicationName (i.e. Popen's "executable"). I noticed for shell=True they aren't using list2cmdline for COMPSPEC; they just trust it. So I wrote the following test to exemplify the problem you're talking about: >>> import os, subprocess >>> open('temp.c', 'w').write(r''' ... #include ... int main(int argc, char *argv[]) { ... printf("\n\n*** spam! ***\n\n"); ... return 0; ... }''') 107 >>> os.system('cl temp.c /FeC:\\Program.exe 1>nul 2>&1') 0 >>> os.environ['COMSPEC'] = r'C:\Program Files\doesnt\matter' >>> p = subprocess.Popen('dir', shell=True) >>> *** spam! *** From steve at pearwood.info Tue Feb 25 23:45:33 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Feb 2014 09:45:33 +1100 Subject: [Tutor] When to use multiprocessing Managers? In-Reply-To: References: Message-ID: <20140225224533.GT3684@ando> On Tue, Feb 25, 2014 at 10:52:19AM +0000, James Chapman wrote: > Hello tutors > > I'm curious about managers and when to use them. [...] I have absolutely no idea about multiprocessing managers, sorry, but a few seconds googling found these: http://stackoverflow.com/questions/740848/python-good-place-to-learn-about-multiprocessing-manager which lead me to these: http://broadcast.oreilly.com/2009/04/pymotw-multiprocessing-part-2.html http://www.ibm.com/developerworks/aix/library/au-multiprocessing/ And of course there is also the documentation. You don't say whether you are using Python 2 or 3, so here's both: http://docs.python.org/3/library/multiprocessing.html http://docs.python.org/2/library/multiprocessing.html Do any of these help? -- Steven From dyoo at hashcollision.org Tue Feb 25 23:55:31 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 25 Feb 2014 14:55:31 -0800 Subject: [Tutor] When to use multiprocessing Managers? In-Reply-To: <20140225224533.GT3684@ando> References: <20140225224533.GT3684@ando> Message-ID: I believe James is referring to: http://docs.python.org/2/library/queue.html but I am not sure yet. Let's hear back from him to clarify what he's looking at. From steve at pearwood.info Wed Feb 26 00:05:00 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Feb 2014 10:05:00 +1100 Subject: [Tutor] When to use multiprocessing Managers? In-Reply-To: References: <20140225224533.GT3684@ando> Message-ID: <20140225230500.GU3684@ando> On Tue, Feb 25, 2014 at 02:55:31PM -0800, Danny Yoo wrote: > I believe James is referring to: > > http://docs.python.org/2/library/queue.html > > but I am not sure yet. Let's hear back from him to clarify what he's > looking at. I think both the subject line and the description is fairly clear he's talking about Manager from multiprocessing :-) py> from multiprocessing import Manager py> Manager py> help(Manager) Help on function Manager in module multiprocessing: Manager() Returns a manager associated with a running server process The managers methods such as `Lock()`, `Condition()` and `Queue()` can be used to create shared objects. -- Steven From rhce.san at gmail.com Wed Feb 26 08:04:18 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Wed, 26 Feb 2014 12:34:18 +0530 Subject: [Tutor] viewkeys,viewvalues,viewitems : Use Cases Message-ID: All, I defined a dictionary a below. In [14]: a = {'a':1,'b':2,'c':3} In [15]: type(a) Out[15]: dict Funtion associated with dictionaries. In [11]: print a.viewkeys() dict_keys(['a', 'c', 'b']) In [12]: print a.viewvalues() dict_values([1, 3, 2]) In [13]: print a.viewitems() dict_items([('a', 1), ('c', 3), ('b', 2)]) Where do i use these , can i get any user cases. Thanks, santosh -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhce.san at gmail.com Wed Feb 26 08:12:00 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Wed, 26 Feb 2014 12:42:00 +0530 Subject: [Tutor] calling global in funtions. Message-ID: All, Requirement : i want to call a variable assigned outside a function scope anytime within the function. I read "global" is a way. a) Case I looks fine. b) Case II is bombing out. Is this how it works or please correct me if i am wrong. case I: In [17]: a = 10 In [19]: def fun_local(): ....: global a ....: print "the value of a is %d" %(a) ....: a = 5 ....: print "the value of a is %d" %(a) ....: In [20]: fun_local() the value of a is 10 the value of a is 5 CASE II: In [21]: a = 10 In [22]: def fun_local(): ....: a = 5 ....: print "the value of a is %d" %(a) ....: global a :4: SyntaxWarning: name 'a' is assigned to before global declaration :4: SyntaxWarning: name 'a' is assigned to before global declaration :4: SyntaxWarning: name 'a' is assigned to before global declaration Thanks, santosh -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Wed Feb 26 06:31:14 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 26 Feb 2014 16:31:14 +1100 Subject: [Tutor] os.symlink can't find target In-Reply-To: <530B6E5B.6060304@barrowhillfarm.org.uk> References: <530B6E5B.6060304@barrowhillfarm.org.uk> Message-ID: <20140226053114.GA16365@cskk.homeip.net> Hi Bob, I notice your problem is solved, but I've got a few remarks about your script and also how you might have investigated your problem. First: the os.foo calls are usually very thin wrappers for the corresponding OS call. So if you get an errno type error for os.symlink, it is worth running: man 2 symlink to read the man page for the symlink OS call. Amongst other things it says, under ERRORS: ENOENT A directory component in newpath does not exist or is a dangling symbolic link, or oldpath is the empty string. You need to know that ENOENT is errno 2 "No such file or directory", but it helps. The other things are just script remarks, not directly related to your problem: On 24Feb2014 16:07, Bob Williams wrote: > if pathList[j][-3:] == "mp3": This is often written (I've inserted a dot, assuming you don't want "foomp3", only "foo.mp3"): if pathList[j].endswith(".mp3"): More readable, and also more reliable because it doesn't rely on you getting the "3" correct. > linkName1 = pathList[j][0:-3] + "mp3" Isn't this exactly the same as pathList[j] ? > linkName2 = destPath + linkName1[len(sourcePath):] You might want to spell this: linkName2 = os.path.join(destPath, linkName1[len(sourcePath):]) This means you don't need to have trailing slashes on sourcePath and destPath. And, to a degree, it might work on non-UNIX systems where the path separator is not a slash. Ireelevant for you now, but it is often a good habit to use portable ways of working on things if it is not inconvenient. [...snip...] > I have tried escaping the spaces with '\', but the same error is > generated. This is usually never the right thing to do. If you find yourself doing this, chances are you're trying to fix the wrong thing. You only need to escape strings when passing them to something that will be interpreting a line of text. Such as a piece of shell script. You should not need it to pass strings to something that expects strings. Cheers, -- Cameron Simpson We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. - Donald Knuth From fomcl at yahoo.com Wed Feb 26 09:50:52 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 26 Feb 2014 00:50:52 -0800 (PST) Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: Message-ID: <1393404652.81128.YahooMailBasic@web163801.mail.gq1.yahoo.com> Regards, 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? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------------------------------------- On Tue, 2/25/14, eryksun wrote: Subject: Re: [Tutor] subprocess.call list vs. str argument To: "Dave Angel" Cc: tutor at python.org Date: Tuesday, February 25, 2014, 11:30 PM On Tue, Feb 25, 2014 at 4:54 PM, Dave Angel wrote: > CreateProcess has its own design bobbles as well. For example,? if > you forget to put quotes around the program name,? it will > happily try to add ".exe" to *multiple* places in the hopes that > one of them will work. > > Adding a file c:\program.exe to a system will blow up lots of > programs that were working by mistake for years. Yesterday evening (it was *late* so forgive me if I wrong) I realized that part of my confusion was also caused by the fact that I ran my code in Idle. If I called subprocess.call with a list argument, it returned code 0 (success) but the generated sphinx code was not the same as when I ran the program from the terminal. I concluded that this is some weird interaction between Idle (which may also run in a subprocess??) and my own program. I also had no problems when I ran (in the terminal): python -c "import subprocess; subprocess.call(['sphinx-apidoc'...(etc)])" I was surprised that the list elements of the argument for subprocess.call *have to be* separate tokens, e.g. (earlier in one of Danny's replies): a token (list element) '-f -F' won't work, it has to be two separate elements/tokens: '-f', '-F'. Apparently, subprocess.call is more than just a convenience function that " ".joins the list and escapes the resulting string. regards, Albert-Jan From zakiakhmad at gmail.com Wed Feb 26 10:34:59 2014 From: zakiakhmad at gmail.com (Zaki Akhmad) Date: Wed, 26 Feb 2014 16:34:59 +0700 Subject: [Tutor] Responding Tweet: A Twitter Bot In-Reply-To: References: <5305F794.9040902@jls-radio.com> Message-ID: On Fri, Feb 21, 2014 at 4:05 PM, Walter Prins wrote: > > With the caveat that I'm not familiar with the Twitter streaming API's > and that I literally only spend 3 minutes googling this, it seems to > me to be the case that the Twitter streaming API's is intended to be a > push style notification service. > > This means you should not in principle ideally be polling the service > for updates yourself (e.g. using sleep/crong etc). Instead, the docs > say that the streaming API can return an iterator that yields objects > as they're decoded from the stream. Quote: > > "The TwitterStream object is an interface to the Twitter Stream API > (stream.twitter.com). This can be used pretty much the same as the > Twitter class except the result of calling a method will be an > iterator that yields objects decoded from the stream. For example::" > > It's highly preferable to not poll something if it will > generate/notify you of new objects, so you should be able to do > something like in their example. Quote: > > twitter_stream = TwitterStream(auth=UserPassAuth('joe', 'joespassword')) > iterator = twitter_stream.statuses.sample() > > for tweet in iterator: > # ...do something with this tweet... (e.g. check if you want to > retweet or something) > > So the for loop should just block by itself until a new tweet/message > comes in at which point it will spring to life and hand it to your > code to process. > > I hope that helps, and apologies if I misunderstood something or have > missed something that makes my comment irrelevant to your problem. Hi Lists, Finally, I could monitor in real time by accessing Twitter API Stream[1]. I add the track variable to string which I'd like to monitor. Such as @mention. for tweet in twitter_stream.statuses.filter(track='example'): print tweet I use Mike Verdone's Twitter python library[2] [1]https://dev.twitter.com/docs/api/1.1/post/statuses/filter [2]https://pypi.python.org/pypi/twitter/1.13.1 Thank you all, From matbioinfo at gmail.com Wed Feb 26 10:35:31 2014 From: matbioinfo at gmail.com (rahmad akbar) Date: Wed, 26 Feb 2014 10:35:31 +0100 Subject: [Tutor] next element in list Message-ID: hey guys i have this file i wish to parse, the file looks something like bellow. there are only four entry here (AaaI, AacLI, AaeI, AagI). the complete file contains thousands of entries =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= REBASE, The Restriction Enzyme Database http://rebase.neb.com Copyright (c) Dr. Richard J. Roberts, 2014. All rights reserved. =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Rich Roberts Jan 30 2014 AaaI (XmaIII) C^GGCCG AacLI (BamHI) GGATCC AaeI (BamHI) GGATCC AagI (ClaI) AT^CGAT the strategy was to mark the string 'Rich Roberts' as the start. i wrote the following function. but then i realized i couldn't do something like .next() to the var in_file which is a list. so i added a flag start = False in which will be turned to True upon 'Rich Roberts' found. is the any simpler way to move to the next element in the list. like built in method or something like that. def read_bionet(bionetfile): res_enzime_dict = {} in_file = open(bionetfile, 'r').readlines() start = False for line in in_file: if line.startswith('Rich Roberts'): start = True if start and len(line) >= 10: line = line.split() res_enzime_dict[line[0]] = line[-1] return res_enzime_dict -- many thanks mat -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Wed Feb 26 12:21:13 2014 From: davea at davea.name (Dave Angel) Date: Wed, 26 Feb 2014 06:21:13 -0500 (EST) Subject: [Tutor] next element in list References: Message-ID: rahmad akbar Wrote in message: > > then i realized i couldn't do something like .next() to the var in_file which is a list. so i added a flag start = False in which will be turned to True upon 'Rich Roberts' found. is the any simpler way to move to the next element in the list. like built in method or something like that.?? def read_bionet(bionetfile): ?? res_enzime_dict = {} ?? in_file = open(bionetfile, 'r').readlines() ?? start = False ?? for line in in_file: ?? ?? if line.startswith('Rich Roberts'): ........ If you omit the call to readlines, then in_file is a file object instead of a list. A file object is its own iterator, and has a next () method. You could also change readlines to xreadlines but I don't see the advantage. Another plus is saving all that memory that a list would take. -- DaveA From davea at davea.name Wed Feb 26 12:28:18 2014 From: davea at davea.name (Dave Angel) Date: Wed, 26 Feb 2014 06:28:18 -0500 (EST) Subject: [Tutor] calling global in funtions. References: Message-ID: Santosh Kumar Wrote in message: > Requirement : i want to call a variable assigned outside a function scope anytime > within the function. I read "global" is a way. > Your sample code doesn't do any calling. But if your design requires you to assign to a global from inside a function, then the global declaration is the correct way. And the global statement should be at the beginning of the function. -- DaveA From bouncingcats at gmail.com Wed Feb 26 13:13:39 2014 From: bouncingcats at gmail.com (David) Date: Wed, 26 Feb 2014 23:13:39 +1100 Subject: [Tutor] os.symlink can't find target In-Reply-To: <20140226053114.GA16365@cskk.homeip.net> References: <530B6E5B.6060304@barrowhillfarm.org.uk> <20140226053114.GA16365@cskk.homeip.net> Message-ID: On 26 February 2014 16:31, Cameron Simpson wrote: > > You need to know that ENOENT is errno 2 "No such file or directory", > but it helps. In case it helps anyone, there is information in the python documentation of the errno module that associates system error numbers with their corresponding messages. Same as in 'man 3 errno' . From __peter__ at web.de Wed Feb 26 13:29:04 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Feb 2014 13:29:04 +0100 Subject: [Tutor] next element in list References: Message-ID: rahmad akbar wrote: > hey guys > > i have this file i wish to parse, the file looks something like bellow. > there are only four entry here (AaaI, AacLI, AaeI, AagI). the complete > file contains thousands of entries > > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > REBASE, The Restriction Enzyme Database http://rebase.neb.com > Copyright (c) Dr. Richard J. Roberts, 2014. All rights reserved. > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > > Rich Roberts Jan 30 > 2014 > > AaaI (XmaIII) C^GGCCG > AacLI (BamHI) GGATCC > AaeI (BamHI) GGATCC > AagI (ClaI) AT^CGAT > > > the strategy was to mark the string 'Rich Roberts' as the start. i wrote > the following function. but then i realized i couldn't do something like > .next() to the var in_file which is a list. so i added a flag start = > False in which will be turned to True upon 'Rich Roberts' found. is the > any simpler way to move to the next element in the list. like built in > method or something like that. > > def read_bionet(bionetfile): > res_enzime_dict = {} > in_file = open(bionetfile, 'r').readlines() > start = False > for line in in_file: > if line.startswith('Rich Roberts'): > start = True > if start and len(line) >= 10: > line = line.split() > res_enzime_dict[line[0]] = line[-1] > return res_enzime_dict As David says, don't call readlines() which reads the lines of the file into a list, iterate over the file directly: def read_bionet(bionetfile): with open(bionetfile) as in_file: # skip header for line in in_file: if line.startswith("Rich Roberts"): break # populate dict res_enzimes = {} for line in in_file: # continues after the line with R. R. if len(line) >= 10: parts = line.split() res_enzimes[parts[0]] = parts[-1] # file will be closed now rather than at # the garbage collector's discretion return res_enzimes From matbioinfo at gmail.com Wed Feb 26 14:11:53 2014 From: matbioinfo at gmail.com (rahmad akbar) Date: Wed, 26 Feb 2014 14:11:53 +0100 Subject: [Tutor] next element in list In-Reply-To: References: Message-ID: David, Peter roger that and thanks so much!! On Wed, Feb 26, 2014 at 1:29 PM, Peter Otten <__peter__ at web.de> wrote: > rahmad akbar wrote: > > > hey guys > > > > i have this file i wish to parse, the file looks something like bellow. > > there are only four entry here (AaaI, AacLI, AaeI, AagI). the complete > > file contains thousands of entries > > > > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > > REBASE, The Restriction Enzyme Database http://rebase.neb.com > > Copyright (c) Dr. Richard J. Roberts, 2014. All rights reserved. > > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > > > > Rich Roberts Jan 30 > > 2014 > > > > AaaI (XmaIII) C^GGCCG > > AacLI (BamHI) GGATCC > > AaeI (BamHI) GGATCC > > AagI (ClaI) AT^CGAT > > > > > > the strategy was to mark the string 'Rich Roberts' as the start. i wrote > > the following function. but then i realized i couldn't do something like > > .next() to the var in_file which is a list. so i added a flag start = > > False in which will be turned to True upon 'Rich Roberts' found. is the > > any simpler way to move to the next element in the list. like built in > > method or something like that. > > > > def read_bionet(bionetfile): > > res_enzime_dict = {} > > in_file = open(bionetfile, 'r').readlines() > > start = False > > for line in in_file: > > if line.startswith('Rich Roberts'): > > start = True > > if start and len(line) >= 10: > > line = line.split() > > res_enzime_dict[line[0]] = line[-1] > > return res_enzime_dict > > As David says, don't call readlines() which reads the lines of the file > into > a list, iterate over the file directly: > > def read_bionet(bionetfile): > with open(bionetfile) as in_file: > # skip header > for line in in_file: > if line.startswith("Rich Roberts"): > break > > # populate dict > res_enzimes = {} > for line in in_file: # continues after the line with R. R. > if len(line) >= 10: > parts = line.split() > res_enzimes[parts[0]] = parts[-1] > > # file will be closed now rather than at > # the garbage collector's discretion > > return res_enzimes > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- many thanks mat -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Wed Feb 26 14:14:50 2014 From: eryksun at gmail.com (eryksun) Date: Wed, 26 Feb 2014 08:14:50 -0500 Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: <1393404652.81128.YahooMailBasic@web163801.mail.gq1.yahoo.com> References: <1393404652.81128.YahooMailBasic@web163801.mail.gq1.yahoo.com> Message-ID: On Wed, Feb 26, 2014 at 3:50 AM, Albert-Jan Roskam wrote: > On Tue, Feb 25, 2014 at 4:54 PM, Dave Angel wrote: >> CreateProcess has its own design bobbles as well. For >> example, if you forget to put quotes around the program >> name, it will happily try to add ".exe" to *multiple* >> places in the hopes that one of them will work. >> Adding a file c:\program.exe to a system will blow up >> lots of programs that were working by mistake for years. > > Yesterday evening (it was *late* so forgive me if I wrong) I > realized that part of my confusion was also caused by the fact > that I ran my code in Idle. If I called subprocess.call with a > list argument, it returned code 0 (success) but the generated > sphinx code was not the same as when I ran the program from > the terminal. I concluded that this is some weird interaction > between Idle (which may also run in a subprocess??) and my own > program. I also had no problems when I ran (in the terminal): > python -c "import subprocess; > subprocess.call(['sphinx-apidoc'...(etc)])" Run IDLE from the terminal to have sphinx-apidoc inherit the terminal for standard I/O. Then you can see the TTY output. I assume you're using a POSIX system. I tacked on the bit about Windows CreateProcess just so you'd be aware of the differences. I'd flip the quoting around in a POSIX shell: python -c 'import subprocess; subprocess.call(["sphinx-apidoc", "..."])'. The shell expands $ and `cmd` in a double-quoted string: $ msg=spam $ echo "$msg" spam $ echo "`uname -o`" GNU/Linux But not in a single-quoted string: $ echo '$msg' $msg $ echo '`uname -o`' `uname -o` > I was surprised that the list elements of the argument for > subprocess.call *have to be* separate tokens, e.g. (earlier in > one of Danny's replies): a token (list element) '-f -F' won't > work, it has to be two separate elements/tokens: '-f', '-F'. > Apparently, subprocess.call is more than just a convenience > function that " ".joins the list and escapes the resulting > string. subprocess.call doesn't join the arguments: def call(*popenargs, **kwargs): return Popen(*popenargs, **kwargs).wait() On a POSIX system, Popen._execute_child doesn't join the arguments, either. It sets executable=args[0] and calls os.execvp(executable, args) in the forked child process. If executable is a relative path, os.execvp uses a loop over the paths in the PATH environment variable to create an absolute path. In CPython, os.execvp calls posix.execv(path, args), which is written in C to call the system function execv(const char *path, char *const argv[]). This replaces the current process image with the executable file located at the absolute `path`. To set up the system call, posix.execv transforms the tuple/list of args into an array of char * pointers of length len(args) + 1. The final item of the array is the NULL terminator. Any unicode strings are encoded with the file-system encoding (probably UTF-8). If the new process image isn't successfully executed (replacing Python in the process), then OSError is raised. This is in the forked child, so Popen._execute_child has to pickle the exception and write it back to the parent process via os.write(errpipe_write, pickle.dumps(exc_value)). It reads the `data` from the other end of the pipe in the parent, and if it's non-empty it'll `raise pickle.loads(data)`. That's the source of the OSError from calling subprocess.call(cmd), where cmd was the entire command line as a string. As to what a program does if you mash two options into a single item of its argv array, such as '-f -F', assuming it isn't trying to be clever and expects the command-line to be parsed by a standard POSIX shell, then '-f -F' won't match any of its known options. From alan.gauld at btinternet.com Wed Feb 26 14:29:04 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Feb 2014 13:29:04 +0000 Subject: [Tutor] viewkeys,viewvalues,viewitems : Use Cases In-Reply-To: References: Message-ID: On 26/02/14 07:04, Santosh Kumar wrote: > I defined a dictionary a below. > > In [14]: a = {'a':1,'b':2,'c':3} >... > Funtion associated with dictionaries. > > In [11]: print a.viewkeys() > dict_keys(['a', 'c', 'b']) > > In [12]: print a.viewvalues() > dict_values([1, 3, 2]) > > In [13]: print a.viewitems() > dict_items([('a', 1), ('c', 3), ('b', 2)]) > > Where do i use these , can i get any user cases. What is 'these'? Do you mean: 1) where do I use a dictionary? 2) where do I use viewXXX()? 3) How do viewXXX differ from XXX (eg a.viewkeys v a.keys)? I'm not sure which aspect you want help with? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Feb 26 14:37:40 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Feb 2014 13:37:40 +0000 Subject: [Tutor] calling global in funtions. In-Reply-To: References: Message-ID: On 26/02/14 07:12, Santosh Kumar wrote: > All, > > Requirement : i want to call a variable assigned outside a function > scope anytime within the function. call in Python means something very specific, namey that you put parens after the name and that hopefully results in some code being executed. You call dir by writing dir(). I assume you just mean you want to access a global variable (which is usually a bad idea and its better to pass it in/out of your function) > I read "global" is a way. Yes, you specify that the variable is global using the global keyword global a > a) Case I looks fine. Yes, that's the correct usage. > b) Case II is bombing out. > CASE II: > > In [21]: a = 10 > > In [22]: def fun_local(): > ....: a = 5 This creates a new local variable 'a' in your function. > ....: print "the value of a is %d" %(a) > ....: global a > :4: SyntaxWarning: name 'a' is assigned to before global declaration This tries to tell the function that 'a' is global but it already has a local 'a' so if this worked you would lose that local variable. So Python issues a warning to tell you so. You must specify global before Python tries to create a local variable of the same name. And if you are just reading the value then you don't need to specify global at all, you can just read it and Python will find it. But it's still better practice to pass the value in as an argument than to use globals. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Wed Feb 26 14:45:42 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 27 Feb 2014 00:45:42 +1100 Subject: [Tutor] calling global in funtions. In-Reply-To: References: Message-ID: <20140226134541.GX3684@ando> On Wed, Feb 26, 2014 at 12:42:00PM +0530, Santosh Kumar wrote: > All, > > Requirement : i want to call a variable assigned outside a function scope > anytime within the function. I read "global" is a way. You can *read* the value of a global from inside a function without needing to declare it at any time. In fact, this is how you can call other functions -- they are just globals that you read. So this will work: a = 10 def func(): print("a equals %s" % a) func() => prints "a equals 10" But if you want to re-assign a global, you need to declare it global first. By default, if you say "x = ..." inside a function, Python will treat that variable x as a local variable. So here's an example: a = 10 def func(): global a print("Before, a equals %s" % a) a = 23 print("After, a equals %s" % a) func() => prints "Before, a equals 10" and "After, a equals 23") > a) Case I looks fine. > b) Case II is bombing out. Actually no it isn't. You're just getting a warning, not an error. See below. > Is this how it works or please correct me if i am wrong. > > case I: > > In [17]: a = 10 > > In [19]: def fun_local(): > ....: global a > ....: print "the value of a is %d" %(a) > ....: a = 5 > ....: print "the value of a is %d" %(a) > ....: > > In [20]: fun_local() > the value of a is 10 > the value of a is 5 This is completely fine. > CASE II: > > In [21]: a = 10 > > In [22]: def fun_local(): > ....: a = 5 > ....: print "the value of a is %d" %(a) > ....: global a > :4: SyntaxWarning: name 'a' is assigned to before global declaration > :4: SyntaxWarning: name 'a' is assigned to before global declaration > :4: SyntaxWarning: name 'a' is assigned to before global declaration This is just a warning. It is STRONGLY RECOMMENDED that you put the global declaration at the top of the function, but it is not compulsary. If you put it somewhere else, you will get a warning, but the function will still work. For now. Some day Python may change that behaviour, so it is safest if you move the global to the top of the function. -- Steven From dpalao.python at gmail.com Wed Feb 26 15:19:22 2014 From: dpalao.python at gmail.com (David Palao) Date: Wed, 26 Feb 2014 15:19:22 +0100 Subject: [Tutor] When to use multiprocessing Managers? In-Reply-To: References: Message-ID: 2014-02-25 11:52 GMT+01:00 James Chapman : > Hello tutors > > I'm curious about managers and when to use them. > For example, I see they offer a Queue() for sharing a Q between > processes, but if I create a Q in the parent process and pass it down > to child processes, then they can put messages into that Q just fine, > and I presume the same thing for other objects available under the > managers package. > > So unless the other process is on a different machine, is there a > reason to use a manager? > > Does anyone have any use case examples or snippets I could look at even? > > Thanks in advance > James > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Hello, I asked myself the same question when I started using multiprocessing time ago. So I was very happy when I saw the question by James. >From my limited knowledge, I would say that a Manager can be useful when processes are distributed across different hosts, or if the exchange of information between processes is more complex than just a couple of synchronization primitives. Best From oscar.j.benjamin at gmail.com Wed Feb 26 15:38:43 2014 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 26 Feb 2014 14:38:43 +0000 Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: <1393404652.81128.YahooMailBasic@web163801.mail.gq1.yahoo.com> References: <1393404652.81128.YahooMailBasic@web163801.mail.gq1.yahoo.com> Message-ID: On 26 February 2014 08:50, Albert-Jan Roskam wrote: > > Yesterday evening (it was *late* so forgive me if I wrong) I realized that part of my confusion was also caused by the fact that I ran my code in Idle. > If I called subprocess.call with a list argument, it returned code 0 (success) but the generated sphinx code was not the same as when I ran the program from the terminal. I concluded that this is some weird interaction between Idle (which may also run in a subprocess??) and my own program. I also had no problems when I ran (in the terminal): python -c "import subprocess; subprocess.call(['sphinx-apidoc'...(etc)])" > > I was surprised that the list elements of the argument for subprocess.call *have to be* separate tokens, e.g. (earlier in one of Danny's replies): a token (list element) '-f -F' won't work, it has to be two separate elements/tokens: '-f', '-F'. Apparently, subprocess.call is more than just a convenience function that " ".joins the list and escapes the resulting string. At the operating system level there is no "command line" as such on posix (Linux, Mac etc.). The command to run a program is a string giving the name of the program and you can also pass a list of strings to the program as "arguments". The command line is something that happens in the shell (e.g. bash). Whereas Python would use quotes and commas to separate strings in a list of strings the shell just assumes that whitespace separates strings. So in Python you would write ['qwe', 'asd', 'zxc zxc'] and it's clear that you have a list of three strings. In the shell (e.g. bash) you would type qwe asd "zxc zxc" and the shell understands that as three separate strings. The quotes are needed to distinguish it from 4 strings because shell syntax assumes that spaces separate strings. So the idea of the "command line" as a single string that must be split on whitespace is just something that happens in the shell. It is supposed to be a convenient way of typing commands in the interactive shell i.e. it would slow me down if I has to put in square brackets quotes and commas every time I wanted to type a command in the shell like ['ls', '-l', '~/mystuff']. But this convenience comes at a price in that it becomes hard to handle strings that have spaces in them. I've never really figured out how to write a non-trivial shell script that can properly handle whitespace (it's easier to just avoid putting spaces in filenames - or write the script in Python). So really I think it's a good thing that Python lets you clearly delineate each string in the argument list: subprocess.call(['ls', '-l', foldername]) without needing to worry about whether or not foldername contains spaces. Oscar From eryksun at gmail.com Wed Feb 26 15:12:17 2014 From: eryksun at gmail.com (eryksun) Date: Wed, 26 Feb 2014 09:12:17 -0500 Subject: [Tutor] calling global in funtions. In-Reply-To: <20140226134541.GX3684@ando> References: <20140226134541.GX3684@ando> Message-ID: On Wed, Feb 26, 2014 at 8:45 AM, Steven D'Aprano wrote: >> :4: SyntaxWarning: name 'a' is assigned to before global declaration > > This is just a warning. It is STRONGLY RECOMMENDED that you put the > global declaration at the top of the function, but it is not compulsary. > If you put it somewhere else, you will get a warning, but the function > will still work. The declaration doesn't have to go at the top to avoid the warning. A variable has to be declared global before it's used or assigned. However, it's a good practice to put it at the top of the function definition. This is for your own good, in case you accidentally try to use a name as both local and global in the same function. All usage will be global, which will probably be a bug. From linux at barrowhillfarm.org.uk Wed Feb 26 16:41:57 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Wed, 26 Feb 2014 15:41:57 +0000 Subject: [Tutor] os.symlink can't find target In-Reply-To: <20140226053114.GA16365@cskk.homeip.net> References: <530B6E5B.6060304@barrowhillfarm.org.uk> <20140226053114.GA16365@cskk.homeip.net> Message-ID: <530E0B45.4010605@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Cameron, Many thanks for your helpful comments. I do still have some problems with my script, but it's probably better to start a new thread with an appropriate subject. I'm a bit new to Python, so it still seems like magic sometimes (someone else said the same in a different thread). A lot of my coding is 'trial & error', and I'll admit that at the moment my main goal is getting things to work; after that I can explore making my code more efficient/readable etc. But I appreciate your suggestions. On 26/02/14 05:31, Cameron Simpson wrote: > Hi Bob, > [...] > > The other things are just script remarks, not directly related to > your problem: > > On 24Feb2014 16:07, Bob Williams > wrote: >> if pathList[j][-3:] == "mp3": > > This is often written (I've inserted a dot, assuming you don't > want "foomp3", only "foo.mp3"): > > if pathList[j].endswith(".mp3"): > > More readable, and also more reliable because it doesn't rely on > you getting the "3" correct. > Yes, and reduces the need for explanatory comments. >> linkName1 = pathList[j][0:-3] + "mp3" > > Isn't this exactly the same as pathList[j] ? > Actually, no. pathList[j] can contain either .mp3 files or .flac files. In fact the main function of the script is to run all the flacs through lame to convert them into mp3s. If they are already mp3s, then a symlink will suffice. >> linkName2 = destPath + linkName1[len(sourcePath):] > > You might want to spell this: > > linkName2 = os.path.join(destPath, linkName1[len(sourcePath):]) > More good stuff. :-) Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMOC0UACgkQ0Sr7eZJrmU77fwCeIAgFpOKEdt5C6Q/qzHPQglnm 91gAnRLHLs5u/369RNsBOMOFeZVhTiN5 =w7La -----END PGP SIGNATURE----- From linux at barrowhillfarm.org.uk Wed Feb 26 18:09:49 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Wed, 26 Feb 2014 17:09:49 +0000 Subject: [Tutor] Editing values from a dictionary Message-ID: <530E1FDD.1050207@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi List, I have two problems, but it's possible that one solution will suffice. I am using a module called mutagen to extract audio metadata from .flac files. The output of mutagen is in the form of a dictionary, so In [1]: import mutagen.flac In [2]: metadata = mutagen.flac.Open("/home/bob/music/artists/The Incredible String Band/1967 The 5000 Spirits Or The Layers Of The Onion/08 The Hedgehog's Song.flac") In [3]: print metadata["artist"] [u'The Incredible String Band'] I now want to pass that string to another program, but I want to strip off the leading [u' and the trailing ']. However, this doesn't work: In [4]: artistName = metadata["artist"][3:-2] In [5]: print artistName [] I was expecting The Incredible String Band, not [] What am I doing wrong? Or what have I misunderstood? The other problem concerns the program that receives these arguments - it complains (and stops with an error) if one the arguments is empty. For example, the flac file may not have the date information: Traceback (most recent call last): File "/home/bob/Documents/scripts/python/flac2mp3v2.py", line 81, in subprocess.call(['lame', '--add-id3v2', '--ignore-tag-errors', '--tt', str(metadata['title']), '--ta', str(metadata['artist']), '--tl', str(metadata['album']), '--ty', str(metadata['date']), '--tn', str(metadata['tracknumber']), '--tg', str(metadata['genre']), tempName1, tempName3]) File "/usr/lib/python2.7/site-packages/mutagen/__init__.py", line 85, in __getitem__ else: return self.tags[key] File "/usr/lib/python2.7/site-packages/mutagen/_vorbis.py", line 184, in __getitem__ if not values: raise KeyError, key KeyError: 'date' If it's possible to edit the string value that gets passed to subprocess.call('lame'...) - see problem #1 above, would it also be possible to define a default value if the original field is empty? Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMOH9sACgkQ0Sr7eZJrmU5ufACeILRlmiXt4CgDa6ZpdTI3Npm5 FToAn2+AcjNKGxJKU+9nE9IdsoEqlQdd =JpdC -----END PGP SIGNATURE----- From ben+python at benfinney.id.au Wed Feb 26 18:29:28 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 27 Feb 2014 04:29:28 +1100 Subject: [Tutor] Editing values from a dictionary References: <530E1FDD.1050207@barrowhillfarm.org.uk> Message-ID: <854n3lpytj.fsf@benfinney.id.au> Bob Williams writes: > In [3]: print metadata["artist"] > [u'The Incredible String Band'] > > I now want to pass that string to another program, but I want to strip > off the leading [u' and the trailing ']. You may be assuming that ?metadata["artist"]? is a text string; I suspect it is not. Try ?type(metadata["artist"])?, to get Python to tell you what the type of that object is. -- \ ?Those who write software only for pay should go hurt some | `\ other field.? ?Erik Naggum, in _gnu.misc.discuss_ | _o__) | Ben Finney From i.am.songoku at gmail.com Wed Feb 26 18:33:53 2014 From: i.am.songoku at gmail.com (Krishnan Shankar) Date: Wed, 26 Feb 2014 23:03:53 +0530 Subject: [Tutor] Editing values from a dictionary In-Reply-To: <530E1FDD.1050207@barrowhillfarm.org.uk> References: <530E1FDD.1050207@barrowhillfarm.org.uk> Message-ID: Hi Bob, >>> In [3]: print metadata["artist"] [u'The Incredible String Band'] <<< Here u' and ' is not something you can strip off as it is part of python datatype called UNICODE. Python prints a word or sentence in double or singles quotes when it is a STRING or UNICODE in interpreter. These are python datatypes. And even if there are any whitespaces in your data, For example: a = [u' The Incredible String Band '] Here there are leading and trailing spaces in the string which is inside the LIST. Do a a[0].strip() Another thing above is that your string in inside a LIST so to access the string to strip it, you need to specify the place value as i have done above. If you do the above you can get the string as you need it. And if you dont need a 'u' in front of your string simply convert it to a string with str() method like below. >>> s = u'spam' >>> >>> >>> s u'spam' >>> type(s) >>> str(s) 'spam' >>> type(str(s)) >>> Regards, Krishnan On Wed, Feb 26, 2014 at 10:39 PM, Bob Williams wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi List, > > I have two problems, but it's possible that one solution will suffice. > I am using a module called mutagen to extract audio metadata from > .flac files. The output of mutagen is in the form of a dictionary, so > > In [1]: import mutagen.flac > > In [2]: metadata = mutagen.flac.Open("/home/bob/music/artists/The > Incredible String Band/1967 The 5000 Spirits Or The Layers Of The > Onion/08 The Hedgehog's Song.flac") > > In [3]: print metadata["artist"] > [u'The Incredible String Band'] > > I now want to pass that string to another program, but I want to strip > off the leading [u' and the trailing ']. However, this doesn't work: > > In [4]: artistName = metadata["artist"][3:-2] > > In [5]: print artistName > [] > > I was expecting The Incredible String Band, not [] > > What am I doing wrong? Or what have I misunderstood? > > The other problem concerns the program that receives these arguments - > it complains (and stops with an error) if one the arguments is empty. > For example, the flac file may not have the date information: > > Traceback (most recent call last): > File "/home/bob/Documents/scripts/python/flac2mp3v2.py", line 81, in > subprocess.call(['lame', '--add-id3v2', > '--ignore-tag-errors', '--tt', str(metadata['title']), '--ta', > str(metadata['artist']), '--tl', str(metadata['album']), '--ty', > str(metadata['date']), '--tn', str(metadata['tracknumber']), '--tg', > str(metadata['genre']), tempName1, tempName3]) > File "/usr/lib/python2.7/site-packages/mutagen/__init__.py", line > 85, in __getitem__ > else: return self.tags[key] > File "/usr/lib/python2.7/site-packages/mutagen/_vorbis.py", line > 184, in __getitem__ > if not values: raise KeyError, key > KeyError: 'date' > > If it's possible to edit the string value that gets passed to > subprocess.call('lame'...) - see problem #1 above, would it also be > possible to define a default value if the original field is empty? > > Bob > - -- > Bob Williams > System: Linux 3.11.10-7-desktop > Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 > Uptime: 12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26 > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v2.0.22 (GNU/Linux) > Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ > > iEYEARECAAYFAlMOH9sACgkQ0Sr7eZJrmU5ufACeILRlmiXt4CgDa6ZpdTI3Npm5 > FToAn2+AcjNKGxJKU+9nE9IdsoEqlQdd > =JpdC > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From linux at barrowhillfarm.org.uk Wed Feb 26 18:48:49 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Wed, 26 Feb 2014 17:48:49 +0000 Subject: [Tutor] Editing values from a dictionary In-Reply-To: <854n3lpytj.fsf@benfinney.id.au> References: <530E1FDD.1050207@barrowhillfarm.org.uk> <854n3lpytj.fsf@benfinney.id.au> Message-ID: <530E2901.7080802@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 26/02/14 17:29, Ben Finney wrote: > Bob Williams writes: > >> In [3]: print metadata["artist"] [u'The Incredible String Band'] >> >> I now want to pass that string to another program, but I want to >> strip off the leading [u' and the trailing ']. > > You may be assuming that ?metadata["artist"]? is a text string; I > suspect it is not. > > Try ?type(metadata["artist"])?, to get Python to tell you what the > type of that object is. > Aha! Sounds of pennies dropping ;-) In [7]: type(metadata["artist"]) Out[7]: list In [12]: print metadata["artist"][0] The Incredible String Band Gets me what I want. Thank you. Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMOKP8ACgkQ0Sr7eZJrmU5a0ACdEH9kJPtHmbQ9w8YXrUc3NJT1 /t8AnitS+J4+kcM2z+Ai6Ak7cbe7Qnmk =Sv8P -----END PGP SIGNATURE----- From rhce.san at gmail.com Wed Feb 26 19:12:24 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Wed, 26 Feb 2014 23:42:24 +0530 Subject: [Tutor] calling global in funtions. In-Reply-To: References: <20140226134541.GX3684@ando> Message-ID: Thank you all. I understood the global function now. On Wed, Feb 26, 2014 at 7:42 PM, eryksun wrote: > On Wed, Feb 26, 2014 at 8:45 AM, Steven D'Aprano > wrote: > >> :4: SyntaxWarning: name 'a' is assigned to before global > declaration > > > > This is just a warning. It is STRONGLY RECOMMENDED that you put the > > global declaration at the top of the function, but it is not compulsary. > > If you put it somewhere else, you will get a warning, but the function > > will still work. > > The declaration doesn't have to go at the top to avoid the warning. A > variable has to be declared global before it's used or assigned. > However, it's a good practice to put it at the top of the function > definition. This is for your own good, in case you accidentally try to > use a name as both local and global in the same function. All usage > will be global, which will probably be a bug. > -- D. Santosh Kumar RHCE | SCSA +91-9703206361 Every task has a unpleasant side .. But you must focus on the end result you are producing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhce.san at gmail.com Wed Feb 26 19:11:19 2014 From: rhce.san at gmail.com (Santosh Kumar) Date: Wed, 26 Feb 2014 23:41:19 +0530 Subject: [Tutor] viewkeys,viewvalues,viewitems : Use Cases In-Reply-To: References: Message-ID: I want to understand about where to use , viewkeys() viewvalues() viewitems() Thanks, santosh On Wed, Feb 26, 2014 at 6:59 PM, Alan Gauld wrote: > On 26/02/14 07:04, Santosh Kumar wrote: > > I defined a dictionary a below. >> >> In [14]: a = {'a':1,'b':2,'c':3} >> ... >> >> Funtion associated with dictionaries. >> >> In [11]: print a.viewkeys() >> dict_keys(['a', 'c', 'b']) >> >> In [12]: print a.viewvalues() >> dict_values([1, 3, 2]) >> >> In [13]: print a.viewitems() >> dict_items([('a', 1), ('c', 3), ('b', 2)]) >> >> Where do i use these , can i get any user cases. >> > > What is 'these'? > Do you mean: > > 1) where do I use a dictionary? > 2) where do I use viewXXX()? > 3) How do viewXXX differ from XXX (eg a.viewkeys v a.keys)? > > I'm not sure which aspect you want help with? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- D. Santosh Kumar RHCE | SCSA +91-9703206361 Every task has a unpleasant side .. But you must focus on the end result you are producing. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Wed Feb 26 19:55:53 2014 From: davea at davea.name (Dave Angel) Date: Wed, 26 Feb 2014 13:55:53 -0500 (EST) Subject: [Tutor] viewkeys,viewvalues,viewitems : Use Cases References: Message-ID: Santosh Kumar Wrote in message: > want to understand about where to use , viewkeys() viewvalues() viewitems() .............. Sometimes you want to loop through a dict, doing something with each of the items. For example you want to generate a report. Suppose you have a dict where the keys are names and the values are grades. Perhaps you want to calculate the average grade. You don't care about names, so you loop through values. Or you want to check how many names begin with J. Loop through the keys. -- DaveA From davea at davea.name Wed Feb 26 20:03:07 2014 From: davea at davea.name (Dave Angel) Date: Wed, 26 Feb 2014 14:03:07 -0500 (EST) Subject: [Tutor] os.symlink can't find target References: <530B6E5B.6060304@barrowhillfarm.org.uk> <20140226053114.GA16365@cskk.homeip.net> <530E0B45.4010605@barrowhillfarm.org.uk> Message-ID: Bob Williams Wrote in message: > >>> linkName1 = pathList[j][0:-3] + "mp3" >> >> Isn't this exactly the same as pathList[j] ? >> > Actually, no. pathList[j] can contain either .mp3 files or .flac > files. In fact the main function of the script is to run all the flacs > through lame to convert them into mp3s. If they are already mp3s, then > a symlink will suffice. > >>> If you're dealing with more than one extension, and especially if they're different lengths, consider using splitext -- DaveA From linux at barrowhillfarm.org.uk Wed Feb 26 23:40:17 2014 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Wed, 26 Feb 2014 22:40:17 +0000 Subject: [Tutor] os.symlink can't find target In-Reply-To: <530E0B45.4010605@barrowhillfarm.org.uk> References: <530B6E5B.6060304@barrowhillfarm.org.uk> <20140226053114.GA16365@cskk.homeip.net> <530E0B45.4010605@barrowhillfarm.org.uk> Message-ID: <530E6D51.703@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 26/02/14 15:41, Bob Williams wrote: On 26/02/14 05:31, Cameron Simpson wrote: >>> linkName1 = pathList[j][0:-3] + "mp3" >>> >>> Isn't this exactly the same as pathList[j] ? >>> > Actually, no. Actually, you are right. I've trimmed down that block now, thank you. Bob - -- Bob Williams System: Linux 3.11.10-7-desktop Distro: openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2 Uptime: 18:00pm up 3:41, 5 users, load average: 2.73, 2.45, 1.92 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.22 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/ iEYEARECAAYFAlMObU0ACgkQ0Sr7eZJrmU5AhgCgpolM3vDLEDzEy8t1o4O+5zCA B58AoJJC3IeyXqt3onBNnoaUaW833Lj3 =BhVn -----END PGP SIGNATURE----- From cs at zip.com.au Wed Feb 26 23:04:16 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 27 Feb 2014 09:04:16 +1100 Subject: [Tutor] os.symlink can't find target In-Reply-To: <530E0B45.4010605@barrowhillfarm.org.uk> References: <530E0B45.4010605@barrowhillfarm.org.uk> Message-ID: <20140226220416.GA84510@cskk.homeip.net> On 26Feb2014 15:41, Bob Williams wrote: > Many thanks for your helpful comments. I do still have some problems > with my script, but it's probably better to start a new thread with an > appropriate subject. Very true. > I'm a bit new to Python, so it still seems like magic sometimes > (someone else said the same in a different thread). A lot of my coding > is 'trial & error', and I'll admit that at the moment my main goal is > getting things to work; after that I can explore making my code more > efficient/readable etc. But I appreciate your suggestions. Readable helps. Even for the author (when you come back later, not to mention when trying to explain the code to others). > >> linkName1 = pathList[j][0:-3] + "mp3" > > > > Isn't this exactly the same as pathList[j] ? > > > Actually, no. pathList[j] can contain either .mp3 files or .flac > files. Except that I thought this was inside the if-statement, so you know that this time it is an mp3. Cheers, -- Cameron Simpson Trust the computer industry to shorten Year 2000 to Y2K. It was this thinking that caused the problem in the first place. - Mark Ovens From steve at pearwood.info Wed Feb 26 23:58:52 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 27 Feb 2014 09:58:52 +1100 Subject: [Tutor] Editing values from a dictionary In-Reply-To: <530E1FDD.1050207@barrowhillfarm.org.uk> References: <530E1FDD.1050207@barrowhillfarm.org.uk> Message-ID: <20140226225852.GB28804@ando> On Wed, Feb 26, 2014 at 05:09:49PM +0000, Bob Williams wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi List, > > I have two problems, but it's possible that one solution will suffice. > I am using a module called mutagen to extract audio metadata from > .flac files. The output of mutagen is in the form of a dictionary, so > > In [1]: import mutagen.flac > > In [2]: metadata = mutagen.flac.Open("/home/bob/music/artists/The > Incredible String Band/1967 The 5000 Spirits Or The Layers Of The > Onion/08 The Hedgehog's Song.flac") > > In [3]: print metadata["artist"] > [u'The Incredible String Band'] Get rid of the print, which automatically converts whatever you pass it to strings and then displays those strings. If you inspect the item directly, you will see that the value you have is not a string: "[u'The Incredible String Band']" but a list [ ... ] containing one item, which is a string. Since you are using an interactive shell, in this case ipython, you can drop the call to print, and just enter metadata["artist"] on its own, and you'll see *exactly the same output*, without quotation marks on the outside. That tells you that what you have is not a string. (If it were a string, you would see quote marks surrounding it.) If you're still not convinced, call: type(metadata['artist']) and take note of what it says. Once you have convinced yourself that it is in fact a list of one item, you can extract that item like this: item = metadata['artist'][0] but beware! The fact that mutagen returns a list rather than the string directly warns you that sometimes there might be two or more pieces of metadata with the same key, e.g.: # some imaginary metadata from a hypothetical FLAC file [u'The Beatles', u'The Rolling Stones', u'ABBA'] So you need to be prepared to deal with multiple metadata items. One last thing: you *do not* want to get rid of the leading u, trust me on this. The u is not actually part of the string itself, it is just a delimiter. What you are seeing is the difference between a Unicode text string and a byte-string. A regular string with "" or '' delimiters consists of a sequence of bytes. Bytes, as you probably are aware, are numbers between 0 and 255 inclusive. But you don't enter them using their numeric value, but by their character value. Python gives you two functions for converting between the numeric and character values: chr(n) # returns the character of ordinal n ord(c) # returns the ordinal of character c and uses ASCII for the first 127 ordinal values, and some arbitary and likely unpredicatable scheme for the rest. Byte strings have their uses, but for text, it's not 1960 any longer, and there is an entire world filled with people for whom ASCII is not enough. (In truth, *even in America*, the ASCII character set was never sufficient for all common uses, since it lacks symbols such as ?.) In the 1980s and 90s the world proliferated a confusing mess of dozens of alternative character sets, often called "extended ASCII" as if there were only one, but fortunately it is now 2014 and the right solution is to use Unicode. Unlike byte-strings, which only contain 256 possible characters, Unicode strings can contain over a million distinct characters, numbered between U+0000 and U+10FFFF (the number after the U+ is in hexadecimal). It contains a dedicated character (technically called a "code point") for each and every character included in all of those dozens of legacy so-called "extended ASCIIs", plus many more that they never included. Unicode strings use delimiters u"" and u'', so as you can see the u is *outside* the quote marks, it is part of the delimiter, not part of the string. Unicode strings allow metadata to include artist's who have non-ASCII characters in their names, like Sin?ad O'Connor and Bj?rk, as well as stylistic "heavy metal umlauts" as used by artists like William ?rbit and Blue ?yster Cult. And even totally pretentious wankfests like ???????, and no I have no idea how that's pronounced. (Alas, the Love Symbol in The Artist Formerly Known As Love Symbol is not available in Unicode, so he'll have to be known as The Artist Formerly Known As The Artist Formerly Known As Prince.) So you should prefer Unicode strings over byte-strings. Apart from the leading u prefix, there is practically no difference in how you use them. All the usual string methods are available: py> print(u'Bj?rk'.upper()) BJ?RK Just be careful about mixing regular '' byte strings and proper u'' Unicode text strings. Python 2 tries to do the "smart" thing when you combine them, and while that works 9 times out of 10, the tenth time you end up even more confused than ever. (Python 3 is far more strict about keeping them separate.) -- Steven From wescpy at gmail.com Thu Feb 27 01:30:07 2014 From: wescpy at gmail.com (wesley chun) Date: Wed, 26 Feb 2014 16:30:07 -0800 Subject: [Tutor] OT: supporting Python & the PSF with a half/quarter-page ad? Message-ID: Hey everyone, This is somewhat off-topic for this list, but if you've gotten a lot out of Python and want to contribute, the Python Software Foundation is advocating for the language by creating and distributing a brochurethat talks all about the goodness of Python. For the first run, they're making "10,000 copies which the PSF will then distribute to user groups, Python conferences and educational institutions on request and free of charge." If your company is interested in supporting the project and want to advertise in it but find the half-page ad cost prohibitive at EURO 2650 (~$3636) or the 3-line reference ad listing at EURO 500 (~$686) too small, let me know. I'm willing to split the cost of the ad (creating 2 quarter-page ads).. the PSF organizer of the brochure suggested this as an alternative, so now I want to see if any of you or your companies want to participate. The full details can be found here . The deadline is this Fri, Feb 28, so please get back to me by tomorrow privately... thanks! -- Wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From pierre.dagenais at ncf.ca Thu Feb 27 22:18:16 2014 From: pierre.dagenais at ncf.ca (Pierre Dagenais) Date: Thu, 27 Feb 2014 16:18:16 -0500 Subject: [Tutor] Installing numpy on Ubuntu Message-ID: <530FAB98.5080208@ncf.ca> I've installed numpy on Ubuntu 12.04 with sudo apt-get install python3-numpy. Everything seems to go OK, yet when I try to use it I get this error: Python 3.3.3 (default, Dec 9 2013, 08:33:48) [GCC 4.6.3] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import numpy Traceback (most recent call last): File "", line 1, in ImportError: No module named 'numpy' >>> What am I doing wrong, Your help is appreciated, PierreD. From eryksun at gmail.com Thu Feb 27 23:07:03 2014 From: eryksun at gmail.com (eryksun) Date: Thu, 27 Feb 2014 17:07:03 -0500 Subject: [Tutor] Installing numpy on Ubuntu In-Reply-To: <530FAB98.5080208@ncf.ca> References: <530FAB98.5080208@ncf.ca> Message-ID: On Thu, Feb 27, 2014 at 4:18 PM, Pierre Dagenais wrote: > I've installed numpy on Ubuntu 12.04 with > sudo apt-get install python3-numpy. > Everything seems to go OK Probably you installed NumPy for python3.2: http://packages.ubuntu.com/precise/python3-numpy > Python 3.3.3 (default, Dec 9 2013, 08:33:48) > [GCC 4.6.3] on linux > Type "help", "copyright", "credits" or "license" for more information. >>>> import numpy > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named 'numpy' >>>> > > What am I doing wrong, Probably you built 3.3 from source or installed from the deadsnakes PPA. Install the NumPy build dependencies and then build/install via pip: $ sudo apt-get build-dep python3-numpy You might want to `pip install numpy` in a virtual environment (pyvenv-3.3 or virtualenv) for testing before pip-3.3 installing to /usr/local. Or you could always use virtual environments and build a wheel package for subsequent re-installations. From dyoo at hashcollision.org Thu Feb 27 23:11:22 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 27 Feb 2014 14:11:22 -0800 Subject: [Tutor] Installing numpy on Ubuntu In-Reply-To: <530FAB98.5080208@ncf.ca> References: <530FAB98.5080208@ncf.ca> Message-ID: I believe this is more an Ubuntu question than a Python one. You mentioned you're using Ubuntu 12.04. But the version of Python 3 in that Ubuntu is Python 3.1: http://packages.ubuntu.com/lucid/python/python3 And your console shows that you're running 3.3.3. So it's likely that you are running a Python that did not come bundled with your Linux distribution. Therefore, you will probably want to switch back to using the standard one that came with your distribution. Alternatively, you can build numpy from source and install it that way. From eryksun at gmail.com Thu Feb 27 23:40:38 2014 From: eryksun at gmail.com (eryksun) Date: Thu, 27 Feb 2014 17:40:38 -0500 Subject: [Tutor] Installing numpy on Ubuntu In-Reply-To: References: <530FAB98.5080208@ncf.ca> Message-ID: On Thu, Feb 27, 2014 at 5:11 PM, Danny Yoo wrote: > You mentioned you're using Ubuntu 12.04. But the version of Python 3 > in that Ubuntu is Python 3.1: > > http://packages.ubuntu.com/lucid/python/python3 12.04 (precise), not 10.04 (lucid). So the python3-numpy package targets Python 3.2, but it's the same problem. From pierre.dagenais at ncf.ca Fri Feb 28 05:08:02 2014 From: pierre.dagenais at ncf.ca (Pierre Dagenais) Date: Thu, 27 Feb 2014 23:08:02 -0500 Subject: [Tutor] Installing numpy on Ubuntu In-Reply-To: References: <530FAB98.5080208@ncf.ca> Message-ID: <53100BA2.2020209@ncf.ca> On 14-02-27 05:40 PM, eryksun wrote: > On Thu, Feb 27, 2014 at 5:11 PM, Danny Yoo wrote: >> You mentioned you're using Ubuntu 12.04. But the version of Python 3 >> in that Ubuntu is Python 3.1: >> >> http://packages.ubuntu.com/lucid/python/python3 > > 12.04 (precise), not 10.04 (lucid). So the python3-numpy package > targets Python 3.2, but it's the same problem. > Thank you all, You were right on, I was running a mix of 3.3 and 3.2. I've made the corrections and now it works PierreD. From tonelitebeats at gmail.com Thu Feb 27 23:35:18 2014 From: tonelitebeats at gmail.com (Tone Lite) Date: Thu, 27 Feb 2014 17:35:18 -0500 Subject: [Tutor] Python help Message-ID: Hello, I am having trouble coming up with a solution to this exercise and any help would be appreciated, thanks! I have attached the code below. '''exercise to complete and test this function''' def joinStrings(stringList): '''Join all the strings in stringList into one string, and return the result, NOT printing it. For example: >>> s = joinStrings(['very', 'hot', 'day']) # returns string >>> print(s) veryhotday ''' # finish the code for this function def main(): print(joinStrings(['very', 'hot', 'day'])) print(joinStrings(['this', 'is', 'it'])) print(joinStrings(['1', '2', '3', '4', '5'])) main() -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: joinAllStub.py Type: text/x-python-script Size: 516 bytes Desc: not available URL: From ben+python at benfinney.id.au Fri Feb 28 09:15:22 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Feb 2014 19:15:22 +1100 Subject: [Tutor] Python help References: Message-ID: <85d2i7odph.fsf@benfinney.id.au> Tone Lite writes: > I am having trouble coming up with a solution to this exercise and any > help would be appreciated, thanks! I have attached the code below. The code you present appears to be the exercise. Are you asking for someone to write the solution for you? That isn't what we do here. We'll help you, but that doesn't mean we'll do your work for you. Please show us what you've tried, describe what it should be doing, and what is happening instead. If there is an error, please also show the complete error output. -- \ ?He who allows oppression, shares the crime.? ?Erasmus Darwin, | `\ grandfather of Charles Darwin | _o__) | Ben Finney From fomcl at yahoo.com Fri Feb 28 10:02:10 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 28 Feb 2014 01:02:10 -0800 (PST) Subject: [Tutor] subprocess.call list vs. str argument In-Reply-To: References: <1393404652.81128.YahooMailBasic@web163801.mail.gq1.yahoo.com> Message-ID: <1393578130.99192.YahooMailNeo@web163802.mail.gq1.yahoo.com> >________________________________ > From: Oscar Benjamin >To: Albert-Jan Roskam >Cc: Dave Angel ; eryksun ; "Tutor at python.org" >Sent: Wednesday, February 26, 2014 3:38 PM >Subject: Re: [Tutor] subprocess.call list vs. str argument > > >On 26 February 2014 08:50, Albert-Jan Roskam wrote: > >> >> Yesterday evening (it was *late* so forgive me if I wrong) I realized that part of my confusion was also caused by the fact that I ran my code in Idle. >> If I called subprocess.call with a list argument, it? returned code 0 (success) but the generated sphinx code was not the same as when I ran the program from the terminal. I concluded that this is some weird interaction between Idle (which may also run in a subprocess??) and my own program. I also had no problems when I ran (in the terminal): python -c "import subprocess; subprocess.call(['sphinx-apidoc'...(etc)])" >> >> I was surprised that the list elements of the argument for subprocess.call *have to be* separate tokens, e.g. (earlier in one of Danny's replies): a token (list element) '-f -F' won't work, it has to be two separate elements/tokens: '-f', '-F'. Apparently, subprocess.call is more than just a convenience function that " ".joins the list and escapes the resulting string. > >At the operating system level there is no "command line" as such on >posix (Linux, Mac etc.). The command to run a program is a string >giving the name of the program and you can also pass a list of strings >to the program as "arguments". The command line is something that >happens in the shell (e.g. bash). Whereas Python would use quotes and >commas to separate strings in a list of strings the shell just assumes >that whitespace separates strings. > >So in Python you would write >? ? ['qwe', 'asd', 'zxc zxc'] >and it's clear that you have a list of three strings. In the shell >(e.g. bash) you would type >? ? qwe asd "zxc zxc" >and the shell understands that as three separate strings. The quotes >are needed to distinguish it from 4 strings because shell syntax >assumes that spaces separate strings. > >So the idea of the "command line" as a single string that must be >split on whitespace is just something that happens in the shell. It is >supposed to be a convenient way of typing commands in the interactive >shell i.e. it would slow me down if I has to put in square brackets >quotes and commas every time I wanted to type a command in the shell >like ['ls', '-l', '~/mystuff']. But this convenience comes at a price >in that it becomes hard to handle strings that have spaces in them. >I've never really figured out how to write a non-trivial shell script >that can properly handle whitespace (it's easier to just avoid putting >spaces in filenames - or write the script in Python). > >So really I think it's a good thing that Python lets you clearly >delineate each string in the argument list: >? ? subprocess.call(['ls', '-l', foldername]) >without needing to worry about whether or not foldername contains spaces. Thank you everybody for all your replies! I will use a list from now on. Also good to know that this works a little differently under Windows. Albert-Jan From fomcl at yahoo.com Fri Feb 28 10:14:35 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 28 Feb 2014 01:14:35 -0800 (PST) Subject: [Tutor] running unittests on multiple OS, including non-Posix Message-ID: <1393578875.93755.YahooMailNeo@web163801.mail.gq1.yahoo.com> Hi, I would like to run my unittests (--> nose) on multiple platforms. I also would like to test different python versions and implementations on each platform (--> tox [2]). These platforms also include Windows, so Travis CI or Docker is not an option. I was thinking about using Vagrant [3] to fire up VirtualBox [4] VMs for each platform-to-be-tested, then either (a) fire up nose or tox through SSH or (b) (the easy way) prepare each VM such that nose/tox is fire up right when the OS starts (ie., edit .bashrc, autoexit.bat or whatever it is called for the OS at hand. But this all feels like reinventing the wheel. Can you recommend a package or strategy to use? [1] https://pypi.python.org/pypi/nose/ [2] https://pypi.python.org/pypi/tox [3] http://www.vagrantbox.es/ [4] https://www.virtualbox.org/ ? Regards, 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 ben+python at benfinney.id.au Fri Feb 28 10:33:44 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Feb 2014 20:33:44 +1100 Subject: [Tutor] running unittests on multiple OS, including non-Posix References: <1393578875.93755.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <851tynoa2v.fsf@benfinney.id.au> Albert-Jan Roskam writes: > I would like to run my unittests (--> nose) on multiple platforms. I > also would like to test different python versions and implementations > on each platform (--> tox [2]). > [?] But this all feels like reinventing the wheel. Can you recommend a > package or strategy to use? I'd recommend you describe your requirements in the ?testing-in-python? forum , specifically for discussing tools and techniques for testing in Python. -- \ ?Always do right. This will gratify some people, and astonish | `\ the rest.? ?Mark Twain | _o__) | Ben Finney From fomcl at yahoo.com Fri Feb 28 11:49:02 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 28 Feb 2014 02:49:02 -0800 (PST) Subject: [Tutor] running unittests on multiple OS, including non-Posix In-Reply-To: <851tynoa2v.fsf@benfinney.id.au> References: <1393578875.93755.YahooMailNeo@web163801.mail.gq1.yahoo.com> <851tynoa2v.fsf@benfinney.id.au> Message-ID: <1393584542.19128.YahooMailNeo@web163806.mail.gq1.yahoo.com> ----- Original Message ----- > From: Ben Finney > To: tutor at python.org > Cc: > Sent: Friday, February 28, 2014 10:33 AM > Subject: Re: [Tutor] running unittests on multiple OS, including non-Posix > > Albert-Jan Roskam writes: > >> I would like to run my unittests (--> nose) on multiple platforms. I >> also would like to test different python versions and implementations >> on each platform (--> tox [2]). > >> [?] But this all feels like reinventing the wheel. Can you recommend a >> package or strategy to use? > > I'd recommend you describe your requirements in the ?testing-in-python? > forum , > specifically for discussing tools and techniques for testing in Python. Cool, thanks. I just subscribed to that list --> "Your subscription request has been received, and will soon be acted upon." From james at uplinkzero.com Fri Feb 28 12:31:40 2014 From: james at uplinkzero.com (James Chapman) Date: Fri, 28 Feb 2014 11:31:40 +0000 Subject: [Tutor] When to use multiprocessing Managers? In-Reply-To: References: Message-ID: Thanks for the replies so far... As per the subject line, yes I'm talking about managers and any object a manager is capable of spawning. This is not version specific or code specific, it's more a discussion on when to use a manager and when it's not needed. >From the OReilly link sent by Steven...(http://broadcast.oreilly.com/2009/04/pymotw-multiprocessing-part-2.html) "The Manager is responsible for coordinating shared information state between all of its users. By creating the list through the manager, the list is updated in all processes when anyone modifies it. In addition to lists, dictionaries are also supported." In my case I have multiple threaded processing sending log messages to a Queue that was created by the parent process. The parent process then has a read thread to take messages out of the queue and write them to file. Whether I create the queue object like this: log_Q = multiprocessing.Queue() or whether I create it like this: multimanager = multiprocessing.Manager() log_Q = multimanager.Queue() seems to make no difference. I always get all the messages from all the threads in all the processes. Perhaps the manager would be important if I was writing to a Queue and expecting all threads to see that message? Although if I needed to command a thread to do something I'd probably have a separate class and separate thread for that purpose. James -- James On 26 February 2014 14:19, David Palao wrote: > 2014-02-25 11:52 GMT+01:00 James Chapman : >> Hello tutors >> >> I'm curious about managers and when to use them. >> For example, I see they offer a Queue() for sharing a Q between >> processes, but if I create a Q in the parent process and pass it down >> to child processes, then they can put messages into that Q just fine, >> and I presume the same thing for other objects available under the >> managers package. >> >> So unless the other process is on a different machine, is there a >> reason to use a manager? >> >> Does anyone have any use case examples or snippets I could look at even? >> >> Thanks in advance >> James >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > > Hello, > I asked myself the same question when I started using multiprocessing > time ago. So I was very happy when I saw the question by James. > > From my limited knowledge, I would say that a Manager can be useful > when processes are distributed across different hosts, or if the > exchange of information between processes is more complex than just a > couple of synchronization primitives. > > Best From james at uplinkzero.com Fri Feb 28 12:45:28 2014 From: james at uplinkzero.com (James Chapman) Date: Fri, 28 Feb 2014 11:45:28 +0000 Subject: [Tutor] Python help In-Reply-To: References: <85d2i7odph.fsf@benfinney.id.au> Message-ID: The answer lies in this page: http://docs.python.org/3.3/library/stdtypes.html#string-methods -- James On 28 February 2014 11:44, James Chapman wrote: > The answer lies in this page: > http://docs.python.org/3.3/library/stdtypes.html#string-methods > > > -- > James > > > On 28 February 2014 08:15, Ben Finney wrote: >> Tone Lite writes: >> >>> I am having trouble coming up with a solution to this exercise and any >>> help would be appreciated, thanks! I have attached the code below. >> >> The code you present appears to be the exercise. Are you asking for >> someone to write the solution for you? That isn't what we do here. We'll >> help you, but that doesn't mean we'll do your work for you. >> >> Please show us what you've tried, describe what it should be doing, and >> what is happening instead. If there is an error, please also show the >> complete error output. >> >> -- >> \ ?He who allows oppression, shares the crime.? ?Erasmus Darwin, | >> `\ grandfather of Charles Darwin | >> _o__) | >> Ben Finney >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor From k-shweta at hcl.com Fri Feb 28 12:41:07 2014 From: k-shweta at hcl.com (Shweta Kaushik) Date: Fri, 28 Feb 2014 11:41:07 +0000 Subject: [Tutor] Reg: How to read string from a static text box from a GUI made in VC++ Message-ID: <7955538EC35A414B9B0A5DDD7DA0404716BA9919@chn-hclt-mbs04.HCLT.CORP.HCL.IN> Hi, I am writing a script to automate GUI which is designed in VC++. How to read strings from a static box using python(pywinauton). Can you provide function details? Thanks & Regards, Shweta Kaushik HCL Technologies Ltd. Mob: +91 9500042351 Extn: 51904 ::DISCLAIMER:: ---------------------------------------------------------------------------------------------------------------------------------------------------- The contents of this e-mail and any attachment(s) are confidential and intended for the named recipient(s) only. E-mail transmission is not guaranteed to be secure or error-free as information could be intercepted, corrupted, lost, destroyed, arrive late or incomplete, or may contain viruses in transmission. The e mail and its contents (with or without referred errors) shall therefore not attach any liability on the originator or HCL or its affiliates. Views or opinions, if any, presented in this email are solely those of the author and may not necessarily reflect the views or opinions of HCL or its affiliates. Any form of reproduction, dissemination, copying, disclosure, modification, distribution and / or publication of this message without the prior written consent of authorized representative of HCL is strictly prohibited. If you have received this email in error please delete it and notify the sender immediately. Before opening any email and/or attachments, please check them for viruses and other defects. ---------------------------------------------------------------------------------------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 7023 bytes Desc: image001.jpg URL: From alan.gauld at btinternet.com Fri Feb 28 14:28:30 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Feb 2014 13:28:30 +0000 Subject: [Tutor] Reg: How to read string from a static text box from a GUI made in VC++ In-Reply-To: <7955538EC35A414B9B0A5DDD7DA0404716BA9919@chn-hclt-mbs04.HCLT.CORP.HCL.IN> References: <7955538EC35A414B9B0A5DDD7DA0404716BA9919@chn-hclt-mbs04.HCLT.CORP.HCL.IN> Message-ID: On 28/02/14 11:41, Shweta Kaushik wrote: > Hi, > > I am writing a script to automate GUI which is designed in VC++. How to > read strings from a static box using python(pywinauton). That's a bit off topic for this list, we focus on core Python language and standard library issues. You could try using the ctypes library module to access the Win32API directly or even pythonwin if you have a COM Object to access. However, the Python Windows mailing list might be a more pertinent list to ask. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Fri Feb 28 17:22:28 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Feb 2014 16:22:28 +0000 Subject: [Tutor] running unittests on multiple OS, including non-Posix In-Reply-To: <1393578875.93755.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1393578875.93755.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On 28/02/2014 09:14, Albert-Jan Roskam wrote: > Hi, > > I would like to run my unittests (--> nose) on multiple platforms. I also would like to test different python versions and implementations on each platform (--> tox [2]). These platforms also include Windows, so Travis CI or Docker is not an option. > I was thinking about using Vagrant [3] to fire up VirtualBox [4] VMs for each platform-to-be-tested, then either (a) fire up nose or tox through SSH or (b) (the easy way) prepare each VM such that nose/tox is fire up right when the OS starts (ie., edit .bashrc, autoexit.bat or whatever it is called for the OS at hand. But this all feels like reinventing the wheel. Can you recommend a package or strategy to use? > > > [1] https://pypi.python.org/pypi/nose/ > > [2] https://pypi.python.org/pypi/tox > [3] http://www.vagrantbox.es/ > [4] https://www.virtualbox.org/ > > Do you really believe that this question is suited to a tutor mailing list? Strangely enough I don't but I'm pleased to see that you've taken Ben Finney's advice and gone to the testing mailing list. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com From jammer10000 at ka3nam.com Fri Feb 28 18:22:15 2014 From: jammer10000 at ka3nam.com (Joe Bennett) Date: Fri, 28 Feb 2014 11:22:15 -0600 Subject: [Tutor] win32api & win32gui help Message-ID: Looking for a good simple remedial course on getting my python script to talk to a Windows program. The author of the windows program has documented the api here: http://www.logger32.net/help/Logger32/Using%20the%20Logger32%20External%20Interface.htm I'm struggling to understand how to implement the messages with win32api/ gui... I've taken a stab at it here with my goal being that I just want to 'register' with the program and receive the response from it. So far I'm still scratching my head over this... I get a response for 'hwnd' but have not been able to get any confirmation that RegisterMessage, PostMessage and GetMessage are working, configured properly or...what... Running this all in WIN7 with ActivePython 2.6.6... import win32api import win32gui hwnd = win32gui.FindWindowEx(0, 0, 0, "Logger32") print "hwnd= ", hwnd message = win32api.RegisterWindowMessage("Logger32 3") win32api.PostMessage(hwnd,message,1,99999) test = win32gui.GetMessage(hwnd,0,0) print "GetMessage: ", test Thanks!!!! -Joe KA3NAM From alan.gauld at btinternet.com Fri Feb 28 19:29:32 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Feb 2014 18:29:32 +0000 Subject: [Tutor] win32api & win32gui help In-Reply-To: References: Message-ID: On 28/02/14 17:22, Joe Bennett wrote: > Looking for a good simple remedial course on getting my python script > to talk to a Windows program. The author of the windows program has > documented the api here: > > http://www.logger32.net/help/Logger32/Using%20the%20Logger32%20External%20Interface.htm This is really way beyond the scope of the tutor list which focuses on the Python language and core modules. You may find somebody here who can answer but you will be much more likely to get a response on the Python Windows mailing list. The gmane newsfeed is here: gmane.comp.python.windows Mark Hammond, the author of Pythonwin, hangs out there along with many other Windows folks. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos