From darrickbledsoe at gmail.com Wed Mar 1 01:21:55 2017 From: darrickbledsoe at gmail.com (darrickbledsoe at gmail.com) Date: Wed, 1 Mar 2017 00:21:55 -0600 Subject: [Tutor] help with and Message-ID: <58b66885.11acca0a.73725.72df@mx.google.com> For some reason I am getting a syntax error when I try and write my second If statement. I cannot find anything wrong with the statement because it is set up the same as all the others I see online. Perhaps someone can inform me why I am getting this. Thanks for your help Darrick Bledsoe II # -*- coding: utf-8 -*- """ Created on Sat Sep 12 19:23:21 2015 @author: Darrick Bledsoe """ wage = eval(input("Enter in the employees hourly wage: ")) #get wage hours_worked = eval(input("Enter in the number of hours worked: ")) #get hours pay = wage * hours_worked # calculate pay ot = ((hours_worked - 40 ) * (1.5) * wage) + (wage * 40) double = ((hours_worked - 40 ) * (2) * wage) + (wage * 40) #calculate overtime pay if (hours_worked <= 40): print (pay) if (hours_worked > 40 and < 60): print (ot) if (hours_worked >= 60): print (double) Sent from Mail for Windows 10 --- This email has been checked for viruses by Avast antivirus software. https://www.avast.com/antivirus From pabitrakumarpati at gmail.com Wed Mar 1 03:18:04 2017 From: pabitrakumarpati at gmail.com (Pabitra Pati) Date: Wed, 1 Mar 2017 13:48:04 +0530 Subject: [Tutor] Understanding the error "method got multiple values for keyword argument " Message-ID: I want to understand the error message I am getting. Below is my code piece :- def total(name, *args): if args: print("%s has total money of Rs %d/- " %(name, sum(args))) else: print("%s's piggy bank has no money" %name) I can call this method passing the extra arguments inside *(). *I know the correct way of passing the arguments.* But, I am passing value for 'name' in form of param=value, *intentionally*, so that it throws me error. However, I am unable to understand the below error message :- >>> total(name="John", *(1, 2, 10) ) Traceback (most recent call last): File "", line 1, in TypeError: total() got multiple values for keyword argument 'name' How Python is evaluating the above call, that it's getting multiple values for the parameter 'name'? How the call is being interpreted internally? Any insight to the same would be appreciated. -- *Thanks,* *Pabitra* From alan.gauld at yahoo.co.uk Wed Mar 1 04:29:04 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 1 Mar 2017 09:29:04 +0000 Subject: [Tutor] help with and In-Reply-To: <58b66885.11acca0a.73725.72df@mx.google.com> References: <58b66885.11acca0a.73725.72df@mx.google.com> Message-ID: On 01/03/17 06:21, darrickbledsoe at gmail.com wrote: > wage = eval(input("Enter in the employees hourly wage: ")) #get wage > hours_worked = eval(input("Enter in the number of hours worked: ")) Don't use eval() like this it is a security risk and is a very bad habit to get into. Instead use an explicit type conversion such as int() or float(). > pay = wage * hours_worked # calculate pay > ot = ((hours_worked - 40 ) * (1.5) * wage) + (wage * 40) > double = ((hours_worked - 40 ) * (2) * wage) + (wage * 40) You don't need all those parentheses around the terms, especially the numbers. > if (hours_worked <= 40): > print (pay) > > if (hours_worked > 40 and < 60): > print (ot) Python sees this as: if (hours_worked > 40) and (< 60): And doesn't know what is intended to be less than 60. You need to be explicit: if hours_worked > 40 and hours_worked < 60: You can also write what you intend in a slightly different form: if (40 < hours_worked < 60): Note: The second form an unusual style that I've only ever seen in Python, most languages insist you use the first version. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Mar 1 04:32:40 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 1 Mar 2017 09:32:40 +0000 Subject: [Tutor] Asking about sending signal to RF receiver through GPIO pins In-Reply-To: References: Message-ID: On 01/03/17 01:29, Quang nguyen wrote: > send the signal to RF receiver through pins in Pi2. I need to send the > signal from clicking a button in UI. > > Can anyone give me some hints? What bit do you need help on? Is it building a UI? Is it clicking a button? Is it sending the signal? For example can you send a signal outside the GUI, say from the Python >>> prompt? Does your GUI display OK? Wjhat toolkit are you using to build it? Can you print a message on screen when you press the button? Show us whatever code you have so far and we might be able to help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Wed Mar 1 04:41:18 2017 From: __peter__ at web.de (Peter Otten) Date: Wed, 01 Mar 2017 10:41:18 +0100 Subject: [Tutor] help with and References: <58b66885.11acca0a.73725.72df@mx.google.com> Message-ID: darrickbledsoe at gmail.com wrote: > For some reason I am getting a syntax error when I try and write my second > If statement. I cannot find anything wrong with the statement because it > is set up the same as all the others I see online. Perhaps someone can > inform me why I am getting this. Thanks for your help > > Darrick Bledsoe II > > # -*- coding: utf-8 -*- > """ > Created on Sat Sep 12 19:23:21 2015 > > @author: Darrick Bledsoe > """ > > > wage = eval(input("Enter in the employees hourly wage: ")) #get wage It is safer to write wage = float(input(...)) if you want a float value. With eval() a user can do nasty things like manipulating your data: $ echo "hello" > precious.txt $ cat precious.txt hello $ python3 Python 3.4.3 (default, Nov 17 2016, 01:08:31) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> wage = eval(input("enter wage ")) enter wage __import__("os").remove("precious.txt") >>> $ cat precious.txt cat: precious.txt: No such file or directory Oops, the file is gone. Even if you write a script for your personal use you should make it a habit to use eval() only if there are significant advantages. > if (hours_worked > 40 and < 60): "< 60" is not a complete expression in Python; you cannot chain it with "and" etc. Possible working alternatives are if hours_worked > 40 and hours_worked < 60: ... and if 40 < hours_worked < 60: ... From alan.gauld at yahoo.co.uk Wed Mar 1 05:00:04 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 1 Mar 2017 10:00:04 +0000 Subject: [Tutor] Understanding the error "method got multiple values for keyword argument " In-Reply-To: References: Message-ID: On 01/03/17 08:18, Pabitra Pati wrote: > def total(name, *args): > if args: > print("%s has total money of Rs %d/- " %(name, sum(args))) > else: > print("%s's piggy bank has no money" %name) > > I can call this method passing the extra arguments inside *(). > *I know the correct way of passing the arguments.* But, I am passing value > for 'name' in form of param=value, *intentionally*, So you expected to get an error? So what exactly are you asking about? Which error did you think you would get? Remember that you are not allowed to pass positional arguments after you pass a named argument. So python sees your call as something like: total(name = "John", 1, 2, 10 ) ie as 4 arguments being passed to name and *args and can't figure out where name stops and *args begins. It could be any of: total( name=("John", 1), 2, 10 ) or total( name=("John", 1, 2), 10 ) or total( name=("John", 1, 2, 10) ) # empty *args is allowed. The whole point of *args is that they represent unnamed arguments, you may not put named arguments in front of them, it's illegal. > However, I am unable to understand the below error message :- > > >>> total(name="John", *(1, 2, 10) ) > Traceback (most recent call last): > File "", line 1, in > TypeError: total() got multiple values for keyword argument 'name' > > How Python is evaluating the above call, that it's getting multiple values > for the parameter 'name'? How the call is being interpreted internally? If you want the technical details of how the interpreter is working there are others better qualified to explain, but since what you are trying to do is not valid Python I'm not sure there is much point in analyzing it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From leamhall at gmail.com Wed Mar 1 05:09:12 2017 From: leamhall at gmail.com (Leam Hall) Date: Wed, 1 Mar 2017 05:09:12 -0500 Subject: [Tutor] Learning Objectives? In-Reply-To: References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com> Message-ID: On 02/28/17 05:24, M Hashmi wrote: > Coding is an art....that helps you craft beautiful things in digital world. > As beginner it's pretty natural to confuse about which learning curve can > benefit you most in future. I see computer science as a science that calls upon our creative nature to produce excellence. Adding constraints like secure coding and TDD push us to even greater artistic expression. Lack of constraints gives us the current standard of non-performant and insecure code. Hence my desire for the basic tools of science and engineering. What do I need to know to produce solid code in a team of solid coders. Leam From __peter__ at web.de Wed Mar 1 05:50:10 2017 From: __peter__ at web.de (Peter Otten) Date: Wed, 01 Mar 2017 11:50:10 +0100 Subject: [Tutor] Understanding the error "method got multiple values for keyword argument " References: Message-ID: Alan Gauld via Tutor wrote: > On 01/03/17 08:18, Pabitra Pati wrote: > >> def total(name, *args): >> if args: >> print("%s has total money of Rs %d/- " %(name, sum(args))) >> else: >> print("%s's piggy bank has no money" %name) >> >> I can call this method passing the extra arguments inside *(). >> *I know the correct way of passing the arguments.* But, I am passing >> value for 'name' in form of param=value, *intentionally*, > > So you expected to get an error? > So what exactly are you asking about? Which error did > you think you would get? > > Remember that you are not allowed to pass positional > arguments after you pass a named argument. So python > sees your call as something like: > > total(name = "John", 1, 2, 10 ) I think total(name="John", *(1, 2, 3)) is rather resolved as total(1, 2, 3, name="John") so that the first argument is both 1 and "John". I conclude that from >>> def total(name, other): ... print("name:", name, "other:", other) ... >>> total(other=42, "John") File "", line 1 SyntaxError: non-keyword arg after keyword arg >>> total(other=42, *["John"]) ('name:', 'John', 'other:', 42) But this is tricky, and I usually resort to trial-and-error when I run into such problems. > ie as 4 arguments being passed to name and > *args and can't figure out where name stops and > *args begins. It could be any of: > > total( name=("John", 1), 2, 10 ) or > total( name=("John", 1, 2), 10 ) or > total( name=("John", 1, 2, 10) ) # empty *args is allowed. > > The whole point of *args is that they represent unnamed > arguments, you may not put named arguments in front of > them, it's illegal. > >> However, I am unable to understand the below error message :- >> >> >>> total(name="John", *(1, 2, 10) ) >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: total() got multiple values for keyword argument 'name' >> >> How Python is evaluating the above call, that it's getting multiple >> values >> for the parameter 'name'? How the call is being interpreted internally? > > If you want the technical details of how the interpreter > is working there are others better qualified to explain, > but since what you are trying to do is not valid Python > I'm not sure there is much point in analyzing it. > From steve at pearwood.info Wed Mar 1 06:07:34 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 1 Mar 2017 22:07:34 +1100 Subject: [Tutor] help with and In-Reply-To: References: <58b66885.11acca0a.73725.72df@mx.google.com> Message-ID: <20170301110734.GV5689@ando.pearwood.info> On Wed, Mar 01, 2017 at 09:29:04AM +0000, Alan Gauld via Tutor wrote: > You need to be explicit: > > if hours_worked > 40 and hours_worked < 60: > > You can also write what you intend in a slightly > different form: > > if (40 < hours_worked < 60): > > Note: > The second form an unusual style that I've only > ever seen in Python, most languages insist you > use the first version. That sort of chained comparison is standard mathematics notation which is hopefully familiar to anyone who has done maths in secondary school. I consider it a serious weakness of other languages that they don't support chained comparisons. Perl6, Coffeescript and Julia are three modern languages which support chained comparisons: https://en.wikipedia.org/wiki/Perl_6#Chained_comparisons http://coffeescript.org/#comparisons http://docs.julialang.org/en/latest/manual/mathematical-operations.html#Chaining-comparisons-1 -- Steve From steve at pearwood.info Wed Mar 1 06:29:39 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 1 Mar 2017 22:29:39 +1100 Subject: [Tutor] Understanding the error "method got multiple values for keyword argument " In-Reply-To: References: Message-ID: <20170301112939.GW5689@ando.pearwood.info> On Wed, Mar 01, 2017 at 01:48:04PM +0530, Pabitra Pati wrote: > I want to understand the error message I am getting. > Below is my code piece :- > > def total(name, *args): > if args: > print("%s has total money of Rs %d/- " %(name, sum(args))) > else: > print("%s's piggy bank has no money" %name) We can simplify the code by just ignoring the body :-) def total(name, *args): pass > I can call this method passing the extra arguments inside *(). > *I know the correct way of passing the arguments.* But, I am passing value > for 'name' in form of param=value, *intentionally*, so that it throws me > error. However, I am unable to understand the below error message :- [...] > TypeError: total() got multiple values for keyword argument 'name' The rules for how function arguments are assigned to parameters are given here: https://docs.python.org/3/reference/expressions.html#calls The documentation even includes an example similar to yours. Basically, if I am reading it correctly, Python starts by building a sequence of empty slots, one for each named parameter: name = plus a slot for any extra arguments. Those slots are filled in using positional arguments, including starred expressions, *then* keyword arguments are assigned, so in your example you get the `name` parameter filled in twice: once as a positional argument, and the second time as the keyword argument. -- Steve From palani at vahaitech.com Wed Mar 1 06:28:31 2017 From: palani at vahaitech.com (Palanikumar Gopalakrishnan) Date: Wed, 1 Mar 2017 16:58:31 +0530 Subject: [Tutor] How to get url call back from the browser Message-ID: *import SimpleHTTPServer import SocketServer PORT = 8000 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever()* I use this code to run simple *http server.* If i enter in browser in *localhost:8000. *It will show the contents of current directory. But If i enter url like this *localhost:8000/sometext* . It will returns 404 error. I want to get this string in my python code to do somthing based this callback. Please guide me to solve this issue -- *Warm Regards,* *Palanikumar Gopalakrishnan *[image: ?] *Developer* From alan.gauld at yahoo.co.uk Wed Mar 1 07:04:54 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 1 Mar 2017 12:04:54 +0000 Subject: [Tutor] Understanding the error "method got multiple values for keyword argument " In-Reply-To: References: Message-ID: On 01/03/17 10:50, Peter Otten wrote: >> sees your call as something like: >> >> total(name = "John", 1, 2, 10 ) > > I think total(name="John", *(1, 2, 3)) > > is rather resolved as > > total(1, 2, 3, name="John") > Ah, yes that makes sense. Thanks for the clarification Peter (and Steven). The bottom line is don't put positional arguments after named ones... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Mar 1 13:31:25 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 1 Mar 2017 18:31:25 +0000 Subject: [Tutor] Learning Objectives? In-Reply-To: References: <775ac1ca-af11-5e43-c691-72e4295f7294@gmail.com> Message-ID: On 01/03/17 10:09, Leam Hall wrote: > I see computer science as a science that calls upon our creative nature > to produce excellence. Adding constraints like secure coding and TDD > push us to even greater artistic expression. Lack of constraints gives > us the current standard of non-performant and insecure code. I'd argue that most of that is software engineering. Computer science is the study of computation, ie how we compute stuff. Software engineering is about the practical application of that to building things. It's like the relationship between physics and traditional engineering (Electrical, Mechanical, Civil etc). Engineers study the basic science but they also study topics like design, ethics, law, economics/accounting and marketing. > Hence my desire for the basic tools of science and engineering. What do > I need to know to produce solid code in a team of solid coders. It's interesting how these things seem to come in groups. Yesterday, after sending my initial response I had lunch with an old friend who is working on a consultancy on the future of Computer Science teaching here in Scotland. We had a long chat about what should be in/out of a modern CS curriculum. That discussion made me rethink the need for lists of criteria because college courses need to do just that. And as we brain-stormed lists of topics we naturally categorized some as mandatory core subjects (eg discrete math, finite state machines, data structures, algorithms etc) and others as optional modules (AI, machine architectures etc). Somebody already suggested looking at the online college courses for ideas, so I guess I'd now second that as probably the best available source. One other place to look is the British Computer Society's web site. I don't know if it's still there but they used to have an Industry Model which included definitions of knowledge areas and levels for different roles (programmer, analyst, software engineer, architect etc) It's now apparently called Skills Framework for the Information Age.(SFIA) Wikipedia has this page as a starter: https://en.wikipedia.org/wiki/SFIAPlus HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From jmssnyder at ucdavis.edu Wed Mar 1 13:23:25 2017 From: jmssnyder at ucdavis.edu (Jason Snyder) Date: Wed, 1 Mar 2017 18:23:25 +0000 Subject: [Tutor] grb.select for multiple times Message-ID: I have a grib2 file with wind data at multiple taus as shown below: 3:485167:d=2017030112:UGRD:10 m above ground:3 hour fcst: 8:1652471:d=2017030112:UGRD:10 m above ground:6 hour fcst: 13:2704909:d=2017030112:UGRD:10 m above ground:9 hour fcst: 18:3865964:d=2017030112:UGRD:10 m above ground:12 hour fcst: 23:5030535:d=2017030112:UGRD:10 m above ground:15 hour fcst: 28:6089549:d=2017030112:UGRD:10 m above ground:18 hour fcst: 33:7148742:d=2017030112:UGRD:10 m above ground:21 hour fcst: 38:8216961:d=2017030112:UGRD:10 m above ground:24 hour fcst: 43:9390488:d=2017030112:UGRD:10 m above ground:27 hour fcst: Now what I would like to do is plot these wind values at the different taus in a time series. I have tried to work with the following code: grbs=pygrib.open(grib) uwind = grbs.select(name='10 metre U wind component') uwnddata=uwind.values however I am not able to from this code get a list of the uwind values over the period of time from 3 to 27 hours at 3 hour intervals. How can I tweak the code to get this desired result? From jmssnyder at ucdavis.edu Wed Mar 1 13:24:41 2017 From: jmssnyder at ucdavis.edu (Jason Snyder) Date: Wed, 1 Mar 2017 18:24:41 +0000 Subject: [Tutor] grb.select for multiple times In-Reply-To: References: Message-ID: In the below email I want to plot the time series of the uwind values at a specific latitude and longitude. On Wed, Mar 1, 2017 at 6:23 PM, Jason Snyder wrote: > I have a grib2 file with wind data at multiple taus as shown below: > > 3:485167:d=2017030112 <(201)%20703-0112>:UGRD:10 m above ground:3 hour > fcst: > 8:1652471:d=2017030112 <(201)%20703-0112>:UGRD:10 m above ground:6 hour > fcst: > 13:2704909:d=2017030112 <(201)%20703-0112>:UGRD:10 m above ground:9 hour > fcst: > 18:3865964:d=2017030112 <(201)%20703-0112>:UGRD:10 m above ground:12 hour > fcst: > 23:5030535:d=2017030112 <(201)%20703-0112>:UGRD:10 m above ground:15 hour > fcst: > 28:6089549:d=2017030112 <(201)%20703-0112>:UGRD:10 m above ground:18 hour > fcst: > 33:7148742:d=2017030112 <(201)%20703-0112>:UGRD:10 m above ground:21 hour > fcst: > 38:8216961:d=2017030112 <(201)%20703-0112>:UGRD:10 m above ground:24 hour > fcst: > 43:9390488:d=2017030112 <(201)%20703-0112>:UGRD:10 m above ground:27 hour > fcst: > > > Now what I would like to do is plot these wind values at the different > taus in a time series. I have tried to work with the following code: > > grbs=pygrib.open(grib) > uwind = grbs.select(name='10 metre U wind component') > uwnddata=uwind.values > > however I am not able to from this code get a list of the uwind values > over the period of time from 3 to 27 hours at 3 hour intervals. How can I > tweak the code to get this desired result? > > > -- Jason Snyder PhD From poojabhalode11 at gmail.com Wed Mar 1 18:40:52 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Wed, 1 Mar 2017 18:40:52 -0500 Subject: [Tutor] Tables in Tkinter Message-ID: Hi, I am trying to create normal tables in Tkinter. Can someone please guide me as to what functions I can use, I looked into tkintertable, but that does not seem to work for me. I tried installing it but it gave me a bunch of errors while installation and does not work. Is there any other simpler way for creating table and configuring them as per needed? Thank you so much. I tried installing tkintertable-1.2.tar.gz file earlier. Please let me know. Thank you Pooja From s.molnar at sbcglobal.net Wed Mar 1 15:20:09 2017 From: s.molnar at sbcglobal.net (Stephen P. Molnar) Date: Wed, 1 Mar 2017 15:20:09 -0500 Subject: [Tutor] Spyder IDE Anaconda3: Problem with Plt.savefig Message-ID: <58B72CF9.7080207@sbcglobal.net> I have written a Python3 program to plot and save UV/VIS spectra from the results of an Orca quantum mechanical calculation. I input the name of the molecule .dat file, without the suffix. Everything is fine until I get to the point where I want to save the figure as name.png using: figure = name+'.png' print(figure) plt.savefig('figure', bbox_inches='tight') where the print statement verifies the nae of the saved figure. The problem is that the saved file is figure.png. Unfortunately, as I am a neophyte to Python programming I don't what I am doing wrong. It's probably a red-faced forehead slapper of a mistake on my part. A point in the right direction to properly naming the saved figure will be muck appreciated. Thanks in advance. -- Stephen P. Molnar, Ph.D. Life is a fuzzy set www.molecular-modeling.net Stochastic and multivariate (614)312-7528 (c) Skype: smolnar1 From dyoo at hashcollision.org Wed Mar 1 20:20:10 2017 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 1 Mar 2017 17:20:10 -0800 Subject: [Tutor] How to get url call back from the browser In-Reply-To: References: Message-ID: Hi Palanikumar, It looks like you're using Python 2, since you're referring to SimpleHTTPServer. But you probably do not want to use SimpleHTTPRequestHandler: it's a local file system server. The docs at https://docs.python.org/2/library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler say: "This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.", and that probably isn't what you want. Instead, you can define your own handler whose logic you can control. You can subclass BaseHTTPRequestHandler, and implement do_GET() . Here is a minimal example: ################################################### import BaseHTTPServer class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Hello world! I see path is: %r" % self.path) if __name__ == '__main__': httpd = BaseHTTPServer.HTTPServer(("", 8080), MyHandler) httpd.serve_forever() ################################################### Within the handler, you can look at attributes like "path" (https://docs.python.org/2.7/library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.path), which You can find more examples at: https://wiki.python.org/moin/BaseHttpServer If you have questions, please feel free to ask! From alan.gauld at yahoo.co.uk Wed Mar 1 20:27:51 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 2 Mar 2017 01:27:51 +0000 Subject: [Tutor] Tables in Tkinter In-Reply-To: References: Message-ID: On 01/03/17 23:40, Pooja Bhalode wrote: > I am trying to create normal tables in Tkinter. First you need to define what a "normal table" is. There is no such thing in standard Tkinter, so any kind of table is not normal. Do you want a simple grid of values? Do you want a spreadsheet type grid with editable cells? Do you want a live link to an underlying data store? Do you want it scrollable? Or re-sizeable? within the form? All of these features are "normal" for tables in different GUI toolkits, but none of them are normal in Tkinter. > as to what functions I can use, I looked into tkintertable, but that does > not seem to work for me. What does "not work" mean? Did it display on screen? Did it have empty values? Were the values not editable (assuming you wanted them to be? You need to be much more specific when describing problems. > I tried installing it but it gave me a bunch of > errors while installation and does not work. How did you install it? What were the errors? What does "not work" mean? (How could it work if the installation gave "a bunch of errors"?) > Is there any other simpler way for creating table and configuring them as > per needed? It depends what you want. Tell us what you are trying to achieve and we may be able to suggest something. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Mar 1 20:32:58 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 2 Mar 2017 01:32:58 +0000 Subject: [Tutor] Spyder IDE Anaconda3: Problem with Plt.savefig In-Reply-To: <58B72CF9.7080207@sbcglobal.net> References: <58B72CF9.7080207@sbcglobal.net> Message-ID: On 01/03/17 20:20, Stephen P. Molnar wrote: > I have written a Python3 program to plot and save UV/VIS spectra from > the results of an Orca quantum mechanical calculation. Caveat: This forum is for help on the core Python language and its standard library. Asking about anything beyond that may require a lot more information about the context - for example few of us will know anything about UV/VIS spectra (even what that means!) However, I'll hazard a guess... > figure = name+'.png' > print(figure) > plt.savefig('figure', bbox_inches='tight') Shouldn't the last line use the variable figure rather than a literal string 'figure' : plt.savefig(figure, bbox_inches='tight') > where the print statement verifies the nae of the saved figure. The > problem is that the saved file is figure.png. I'm guessing that's because you are passing the string 'figure' instead of the variable. But I don;t know anything about your plt object or its savefig() method, not even which library you are using. Is it matplotlib? Or something else? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Mar 1 20:39:12 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 2 Mar 2017 01:39:12 +0000 Subject: [Tutor] grb.select for multiple times In-Reply-To: References: Message-ID: On 01/03/17 18:23, Jason Snyder wrote: > I have a grib2 file with wind data at multiple taus as shown below: This list is for the core Python language and standard library. For anything outside that you are more likely to get answers on the specific library support forum or community. If that fails you need to give us a lot of context. Don;t asume we know anything about your area of speciality, certainly few of us work with wind data, and have no idea what taus are. We are certainly not generally familiar with grib2. > 3:485167:d=2017030112:UGRD:10 m above ground:3 hour fcst: > 8:1652471:d=2017030112:UGRD:10 m above ground:6 hour fcst: > 13:2704909:d=2017030112:UGRD:10 m above ground:9 hour fcst: > > Now what I would like to do is plot these wind values at the different taus > in a time series. I have tried to work with the following code: > > grbs=pygrib.open(grib) > uwind = grbs.select(name='10 metre U wind component') > uwnddata=uwind.values None of that makes any sense to us(*) because it's all in the module. You need to explain what each line is doing, what kind of object you expect back, what the various parameters represent, etc. (In so doing you will often solve your own problem!) (*)Most of us at leadt. You may luck out and find somebody else who uses your module and can help. But it will be a stroke of luck if you do. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From poojabhalode11 at gmail.com Thu Mar 2 09:25:12 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Thu, 2 Mar 2017 09:25:12 -0500 Subject: [Tutor] Tables in Tkinter In-Reply-To: References: Message-ID: Hi Alan, Sorry for being ambiguous earlier. I can make it more clear in this email. I am planning on creating a scrollable table (grid of values) with title labels for each column and rows present in it and a title for the overall table. I saw it online that to create a table in tkinter, I can use a built in module tkintertable but would have to download it. when I tried to install tkintertable using pip: i got the following errors: Poojas-MacBook-Pro:~ poojabhalode$ pip install tkintertable Collecting tkintertable Collecting Pmw (from tkintertable) Installing collected packages: Pmw, tkintertable Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/Pmw' After this, if I tried to import >From tkintertable import TableCanvas It gave me an error saying no module tkintertable found. Can you please suggest me as to what I can do and how I can create the table required? I also want to create another table wherein there would be scrollable rows and columns. There would be one main column, which would be subdivided into three and then the three columns subdivided into more columns. Please let me know. Thank you Pooja On Wed, Mar 1, 2017 at 8:27 PM, Alan Gauld via Tutor wrote: > On 01/03/17 23:40, Pooja Bhalode wrote: > > > I am trying to create normal tables in Tkinter. > > First you need to define what a "normal table" is. > There is no such thing in standard Tkinter, so any > kind of table is not normal. > > Do you want a simple grid of values? > Do you want a spreadsheet type grid with editable cells? > Do you want a live link to an underlying data store? > Do you want it scrollable? Or re-sizeable? within the form? > > All of these features are "normal" for tables in > different GUI toolkits, but none of them are normal > in Tkinter. > > > as to what functions I can use, I looked into tkintertable, but that does > > not seem to work for me. > > What does "not work" mean? > > Did it display on screen? > Did it have empty values? > Were the values not editable (assuming you wanted them to be? > > You need to be much more specific when describing problems. > > > I tried installing it but it gave me a bunch of > > errors while installation and does not work. > > How did you install it? > What were the errors? > What does "not work" mean? (How could it work if the > installation gave "a bunch of errors"?) > > > Is there any other simpler way for creating table and configuring them as > > per needed? > > It depends what you want. Tell us what you are trying > to achieve and we may be able to suggest something. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > 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 > From poojabhalode11 at gmail.com Thu Mar 2 09:26:44 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Thu, 2 Mar 2017 09:26:44 -0500 Subject: [Tutor] Tables in Tkinter In-Reply-To: References: Message-ID: I am currently using python 2.7 in mac system. I think tkinter would be a problem since I use Tkinter for Python 2.7. But I do not know the corresponding part of tkintertable for python 2.7 Thank you Pooja On Thu, Mar 2, 2017 at 9:25 AM, Pooja Bhalode wrote: > Hi Alan, > > Sorry for being ambiguous earlier. I can make it more clear in this email. > I am planning on creating a scrollable table (grid of values) with title > labels for each column and rows present in it and a title for the overall > table. > > I saw it online that to create a table in tkinter, I can use a built in > module tkintertable but would have to download it. > when I tried to install tkintertable using pip: i got the following errors: > > Poojas-MacBook-Pro:~ poojabhalode$ pip install tkintertable > > Collecting tkintertable > > Collecting Pmw (from tkintertable) > > Installing collected packages: Pmw, tkintertable > > Exception: > > Traceback (most recent call last): > > File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", > line 215, in main > > status = self.run(options, args) > > File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", > line 342, in run > > prefix=options.prefix_path, > > File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", > line 784, in install > > **kwargs > > File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", > line 851, in install > > self.move_wheel_files(self.source_dir, root=root, prefix=prefix) > > File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", > line 1064, in move_wheel_files > > isolated=self.isolated, > > File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", > line 345, in move_wheel_files > > clobber(source, lib_dir, True) > > File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", > line 316, in clobber > > ensure_dir(destdir) > > File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", > line 83, in ensure_dir > > os.makedirs(path) > > File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", > line 157, in makedirs > > mkdir(name, mode) > > OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site- > packages/Pmw' > > > After this, if I tried to import > > From tkintertable import TableCanvas > > It gave me an error saying no module tkintertable found. > > Can you please suggest me as to what I can do and how I can create the > table required? I also want to create another table wherein there would be > scrollable rows and columns. There would be one main column, which would be > subdivided into three and then the three columns subdivided into more > columns. > > > Please let me know. > > Thank you > > > Pooja > > On Wed, Mar 1, 2017 at 8:27 PM, Alan Gauld via Tutor > wrote: > >> On 01/03/17 23:40, Pooja Bhalode wrote: >> >> > I am trying to create normal tables in Tkinter. >> >> First you need to define what a "normal table" is. >> There is no such thing in standard Tkinter, so any >> kind of table is not normal. >> >> Do you want a simple grid of values? >> Do you want a spreadsheet type grid with editable cells? >> Do you want a live link to an underlying data store? >> Do you want it scrollable? Or re-sizeable? within the form? >> >> All of these features are "normal" for tables in >> different GUI toolkits, but none of them are normal >> in Tkinter. >> >> > as to what functions I can use, I looked into tkintertable, but that >> does >> > not seem to work for me. >> >> What does "not work" mean? >> >> Did it display on screen? >> Did it have empty values? >> Were the values not editable (assuming you wanted them to be? >> >> You need to be much more specific when describing problems. >> >> > I tried installing it but it gave me a bunch of >> > errors while installation and does not work. >> >> How did you install it? >> What were the errors? >> What does "not work" mean? (How could it work if the >> installation gave "a bunch of errors"?) >> >> > Is there any other simpler way for creating table and configuring them >> as >> > per needed? >> >> It depends what you want. Tell us what you are trying >> to achieve and we may be able to suggest something. >> >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.amazon.com/author/alan_gauld >> Follow my photo-blog on Flickr at: >> 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 >> > > From rafael.knuth at gmail.com Thu Mar 2 08:42:58 2017 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Thu, 2 Mar 2017 14:42:58 +0100 Subject: [Tutor] looping - beginner question Message-ID: I wrote a program that is supposed to take orders from customers in a bar. If the desired drink is available, the customer will be served. If not, he will be informed that the drink is not available. This is what I wrote: bar = ["beer", "coke", "wine"] customer_order = input("What would you like to drink, dear guest? ") for drink in bar: if customer_order != drink: print ("Sorry, we don't serve %s." % customer_order) else: print ("Sure, your %s will be served in a minute!" % customer_order) What I want the program to do is to "silently" loop through the list of drinks and to print the correct answer. Instead, it loops through each item on the list like this: >>> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_4.py == What would you like to drink, dear guest? coke Sorry, we don't serve coke. Sure, your coke will be served in a minute! Sorry, we don't serve coke. >>> From ryan at allwegot.net Thu Mar 2 09:32:42 2017 From: ryan at allwegot.net (Ryan Smith) Date: Thu, 02 Mar 2017 09:32:42 -0500 Subject: [Tutor] feedback on simple python code In-Reply-To: References: Message-ID: On 2/28/17, 3:32 AM, "Tutor on behalf of Peter Otten" wrote: >Ryan Smith wrote: > >> Hi all, >> >> New python student here. I have been using O?reilly?s "Python Beyond the >> Basics: Object Oriented Programming video series". In one of the >> assignments we are to write a simple inheritance hierarchy of three >> classes that write to text files. I have actually written the code for >>the >> assignment and it runs as well as meets the requirements of the >> assignment. I am posting to get feedback on how I can improve this and >> making it more pythonic and concise. >> >> Please keep in mind that I am simply ?simulating" writing to a log file >> and a tabbed delimited file, so I?m not necessarily looking for which >> modules I could have to create actual log files or writing to actual csv >> files. The output of the code should be two text files with text written >> to them that have been passed to the instance of each respective object. >> >> #!/usr/bin/env python >> >> import abc >> import datetime >> >> class WriteFile(object): >> __metaclass__ = abc.ABCMeta >> >> >> @abc.abstractmethod >> def write(self,text): > >You might run a tool like https://pypi.python.org/pypi/pycodestyle over >your >code to ensure it follows common standards. > >> """Write to file""" >> return >> >> >> class LogFile(WriteFile): >> def __init__(self,fh): >> self.fh = fh >> >> >> def write(self, text): >> date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') >> entry = "{0} {1}{2}".format(date, text, '\n') >> with open(self.fh, 'a') as f: >> f.write(entry) >> >> class DelimWrite(WriteFile): >> def __init__(self, fh, delim): >> self.fh = fh >> self.delim = delim >> >> >> def write(self, text): >> with open(self.fh, 'a') as f: >> entry = "" >> for item in text: >> if self.delim in item: >> entry += ' "{0}"{1} '.format(item,self.delim) > >What will happen if text contains double quotes? > >> else: >> entry += item+self.delim > >Have a look at the str.join() method. Example: > >>>> ",".join(["foo", "bar", "baz"]) >'foo,bar,baz' > >> f.write(entry.strip(self.delim) + '\n') > >I will mention another "principle", DRY (don't repeat yourself), i. e. do >not write the same code twice. > >When I look at your code I see that both DelimWrite and LogFile open a >file. >If you want modify your code to accept file objects like sys.stdout you >have >to make changes in both subclasses. To avoid that you might put the file- >writing part into a separate method: > >class WriteFile(object): > def __init__(self, file): > self.file = file > > def write_record(self, record): > with open(self.file, "a") as f: > f.write(self.format_record(record)) > > def format_record(self, record): > return record > > >class LogFile(WriteFile): > def format_record(self, record): > date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') > return "{0} {1}\n".format(date, record) > > >class DelimWrite(WriteFile): > quote = '"' > def __init__(self, file, delimiter): > super(DelimWrite, self).__init__(file) > self.delimiter = delimiter > > def escaped(self, value): > value = str(value) > if self.delimiter in value: > quote = self.quote > value = '"{}"'.format(value.replace(quote, quote + quote)) > return value > > def format_record(self, record): > escaped_rows = (self.escaped(value) for value in record) > return self.delimiter.join(escaped_rows) + "\n" > > >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor > Danny/Peter, Thank you to both of you for your feedback. Peter, I will definitely be adding pycodestyle to my toolkit. You made a good point about creating a separate method for file writing so that both the DelimWrite and the LogFile classes can use them. Also looking at my code I see where my code does repeat with the write() method. I guess I?m still trying to understand polymorphism because that?s what I was aiming for when I wrote the code. Danny, Thank you for the link you provided on Liskov?s principals. To be honest I started reading what you shared and realize it?s gonna take a little time to digest it so that I can apply the principals in future code. I?m sure I will have more questions, but I will just start a separate thread. Again thank you both, Ryan From s.molnar at sbcglobal.net Thu Mar 2 06:12:06 2017 From: s.molnar at sbcglobal.net (Stephen P. Molnar) Date: Thu, 2 Mar 2017 06:12:06 -0500 Subject: [Tutor] Spyder IDE Anaconda3: Problem with Plt.savefig In-Reply-To: References: <58B72CF9.7080207@sbcglobal.net> Message-ID: <58B7FE06.1060005@sbcglobal.net> On 03/01/2017 08:32 PM, Alan Gauld via Tutor wrote: > On 01/03/17 20:20, Stephen P. Molnar wrote: >> I have written a Python3 program to plot and save UV/VIS spectra from >> the results of an Orca quantum mechanical calculation. > > Caveat: This forum is for help on the core Python language > and its standard library. Asking about anything beyond that > may require a lot more information about the context - for > example few of us will know anything about UV/VIS spectra > (even what that means!) > > However, I'll hazard a guess... > >> figure = name+'.png' >> print(figure) >> plt.savefig('figure', bbox_inches='tight') > > Shouldn't the last line use the variable figure > rather than a literal string 'figure' : > > plt.savefig(figure, bbox_inches='tight') > >> where the print statement verifies the nae of the saved figure. The >> problem is that the saved file is figure.png. > > I'm guessing that's because you are passing the string 'figure' > instead of the variable. > > But I don;t know anything about your plt object > or its savefig() method, not even which library > you are using. Is it matplotlib? Or something else? > > HTH > That was the problem. Many thanks. -- Stephen P. Molnar, Ph.D. Life is a fuzzy set www.molecular-modeling.net Stochastic and multivariate (614)312-7528 (c) Skype: smolnar1 From alan.gauld at yahoo.co.uk Thu Mar 2 10:06:28 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 2 Mar 2017 15:06:28 +0000 Subject: [Tutor] looping - beginner question In-Reply-To: References: Message-ID: On 02/03/17 13:42, Rafael Knuth wrote: > bar = ["beer", "coke", "wine"] > > customer_order = input("What would you like to drink, dear guest? ") > > for drink in bar: > if customer_order != drink: > print ("Sorry, we don't serve %s." % customer_order) > else: > print ("Sure, your %s will be served in a minute!" % customer_order) > > What I want the program to do is to "silently" loop through the list So you only want the sorry... message if the loop completes without finding a drink. That means you need to put that print statement after the loop. Python includes a feature for that - a for/else construct. for drink in bar: if drink == customer_order: print(Sure...) break #exit loop and avoid else else: # only if the loop completes normally However, there is another way to do this that doesn't use an explicit loop: the 'in' operator if customer_order in bar: print("sure....) else: print ("Sorry....) hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Thu Mar 2 10:07:59 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 2 Mar 2017 15:07:59 +0000 Subject: [Tutor] Tables in Tkinter In-Reply-To: References: Message-ID: On 02/03/17 14:25, Pooja Bhalode wrote: > when I tried to install tkintertable using pip: i got the following errors: > > OSError: [Errno 13] Permission denied: > '/Library/Python/2.7/site-packages/Pmw' Based on this I'm guessing you need to run pip with sudo? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From leamhall at gmail.com Thu Mar 2 10:02:07 2017 From: leamhall at gmail.com (leam hall) Date: Thu, 2 Mar 2017 10:02:07 -0500 Subject: [Tutor] looping - beginner question In-Reply-To: References: Message-ID: On Thu, Mar 2, 2017 at 8:42 AM, Rafael Knuth wrote: > I wrote a program that is supposed to take orders from customers in a bar. > If the desired drink is available, the customer will be served. If > not, he will be informed that the drink is not available. This is what > I wrote: > > bar = ["beer", "coke", "wine"] > > customer_order = input("What would you like to drink, dear guest? ") > > for drink in bar: > if customer_order != drink: > print ("Sorry, we don't serve %s." % customer_order) > else: > print ("Sure, your %s will be served in a minute!" % > customer_order) > > What I want the program to do is to "silently" loop through the list > of drinks and to print the correct answer. Instead, it loops through > each item on the list like this: > > >>> > == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_4.py > == > What would you like to drink, dear guest? coke > Sorry, we don't serve coke. > Sure, your coke will be served in a minute! > Sorry, we don't serve coke. > >>> > > Rafael, don't forget that your input string might have a newline character that needs to be cleaned off. I think, can't test at the moment. The simplest test might be: if drink in bar: From mats at wichmann.us Thu Mar 2 10:19:40 2017 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 2 Mar 2017 08:19:40 -0700 Subject: [Tutor] looping - beginner question In-Reply-To: References: Message-ID: On 03/02/2017 08:06 AM, Alan Gauld via Tutor wrote: > On 02/03/17 13:42, Rafael Knuth wrote: > >> bar = ["beer", "coke", "wine"] >> >> customer_order = input("What would you like to drink, dear guest? ") >> >> for drink in bar: >> if customer_order != drink: >> print ("Sorry, we don't serve %s." % customer_order) >> else: >> print ("Sure, your %s will be served in a minute!" % customer_order) >> >> What I want the program to do is to "silently" loop through the list > > So you only want the sorry... message if the loop completes without > finding a drink. That means you need to put that print statement after > the loop. Python includes a feature for that - a for/else construct. > > for drink in bar: > if drink == customer_order: > print(Sure...) > break #exit loop and avoid else > else: > # only if the loop completes normally > > However, there is another way to do this that doesn't > use an explicit loop: the 'in' operator > > if customer_order in bar: > print("sure....) > else: > print ("Sorry....) To follow on to what Alan said, you don't need to loop over a list (or tuple, or dictionary, or other "iterable") to find out if it contains an item. You can just test membership directly. From poojabhalode11 at gmail.com Thu Mar 2 16:28:06 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Thu, 02 Mar 2017 21:28:06 +0000 Subject: [Tutor] Tables in Tkinter In-Reply-To: References: Message-ID: Hi Alan, Thank you for that advice. Sorry, I should have caught that. Also, i can look into the documentation of tkintertable for creating the table. Thank you Pooja On Thu, Mar 2, 2017 at 10:12 AM Alan Gauld via Tutor wrote: > On 02/03/17 14:25, Pooja Bhalode wrote: > > > when I tried to install tkintertable using pip: i got the following > errors: > > > > OSError: [Errno 13] Permission denied: > > '/Library/Python/2.7/site-packages/Pmw' > > > Based on this I'm guessing you need to run pip with sudo? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > 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 > From quangnguyen51291 at gmail.com Thu Mar 2 17:20:57 2017 From: quangnguyen51291 at gmail.com (Quang nguyen) Date: Thu, 2 Mar 2017 15:20:57 -0700 Subject: [Tutor] Asking about pi_switch In-Reply-To: References: Message-ID: Hi, Right now, I need to use pi_switch in order to send data through RF system by Pi2. Until now, I installed everything it need from an article on the internet. Those things are python-dev, libboost-python-dev, python-pip, and I used pip to install pi_switch. I think it just compatible with python2, and I cannot import it to python3. Are there any ways I can import it to python3 or execute python2 script which has pi_switch by python3 script?. Thanks From alan.gauld at yahoo.co.uk Thu Mar 2 20:00:59 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 3 Mar 2017 01:00:59 +0000 Subject: [Tutor] Asking about pi_switch In-Reply-To: References: Message-ID: On 02/03/17 22:20, Quang nguyen wrote: > Right now, I need to use pi_switch in order to send data through RF system > by Pi2. Until now, I installed everything it need from an article on the > internet. Those things are python-dev, libboost-python-dev, python-pip, and > I used pip to install pi_switch. > > I think it just compatible with python2, and I cannot import it to python3. > > Are there any ways I can import it to python3 or execute python2 script > which has pi_switch by python3 script?. There are a few compatibility libraries around but your simplest solution is probably to install python2 on your Pi. BTW You might find a Pi forum gets you more answers than this list which is aimed for Python language queries and the standard library. Not too many of us use a Pi (although I confess that I do occasionally) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Thu Mar 2 20:14:11 2017 From: akleider at sonic.net (Alex Kleider) Date: Thu, 02 Mar 2017 17:14:11 -0800 Subject: [Tutor] Asking about pi_switch In-Reply-To: References: Message-ID: <18707e56a05db05980bcbe795a9da858@sonic.net> On 2017-03-02 14:20, Quang nguyen wrote: > Hi, > > Right now, I need to use pi_switch in order to send data through RF > system > by Pi2. Until now, I installed everything it need from an article on > the > internet. Those things are python-dev, libboost-python-dev, python-pip, > and > I used pip to install pi_switch. > > I think it just compatible with python2, and I cannot import it to > python3. > > Are there any ways I can import it to python3 or execute python2 script > which has pi_switch by python3 script?. > > Thanks I'll assume you are using Raspbian as the OS on a Raspberry Pi. Raspbian is a Debian based version of Linux. python2.7 is the default but python3 is also there. I suggest you use virtualenv as follows: sudo apt-get install python-virtualenv cd virtualenv -p python3 venv source venv/bin/activate # This will leave you in a Python 3 environment. pip install py_switch # I assume this is a RPi specific package You can exit the environment with the following command: deactivate You can get back into it by sourcing activate again as shown above. Hope this is helpful. I've been doing a lot of this sort of stuff with the Raspberry Pi and would be happy to keep the conversation going off line for the non Python bits. Alex From akleider at sonic.net Thu Mar 2 20:30:43 2017 From: akleider at sonic.net (Alex Kleider) Date: Thu, 02 Mar 2017 17:30:43 -0800 Subject: [Tutor] Asking about pi_switch In-Reply-To: References: Message-ID: <6e75fecf5b3043cbe30f5be37c94494c@sonic.net> > On 02/03/17 22:20, Quang nguyen wrote: > >> Right now, I need to use pi_switch in order to send data through RF >> system >> by Pi2. Until now, I installed everything it need from an article on >> the >> internet. Those things are python-dev, libboost-python-dev, >> python-pip, and >> I used pip to install pi_switch. >> >> I think it just compatible with python2, and I cannot import it to >> python3. >> >> Are there any ways I can import it to python3 or execute python2 >> script >> which has pi_switch by python3 script?. Sorry, Quang, I got your problem backwards- Raspbian comes with python2.7. Are you sure you are using Python 3? You would have had to take special measures to do so. check here: https://github.com/lexruee/pi-switch-python and note that rpi-rf is recommended instead. From rafael.knuth at gmail.com Fri Mar 3 07:12:23 2017 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Fri, 3 Mar 2017 13:12:23 +0100 Subject: [Tutor] printing items form list Message-ID: I want to print individual items from a list like this: You have a book, towel, shirt, pants in your luggage. This is my code: suitcase = ["book", "towel", "shirt", "pants"] print ("You have a %s in your luggage." % suitcase) Instead of printing out the items on the list, my code appends the list to the string. How do I need to modify my code? == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_7.py == You have a ['book', 'towel', 'shirt', 'pants'] in your luggage. From __peter__ at web.de Fri Mar 3 07:30:23 2017 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Mar 2017 13:30:23 +0100 Subject: [Tutor] printing items form list References: Message-ID: Rafael Knuth wrote: > I want to print individual items from a list like this: > > You have a book, towel, shirt, pants in your luggage. > > This is my code: > > suitcase = ["book", "towel", "shirt", "pants"] > print ("You have a %s in your luggage." % suitcase) > > Instead of printing out the items on the list, my code appends the > list to the string. How do I need to modify my code? Have a look at the str.join() method: >>> suitcase = ["book", "towel", "shirt", "pants"] >>> print("You have a %s in your luggage." % ", ".join(suitcase)) You have a book, towel, shirt, pants in your luggage. See From mats at wichmann.us Fri Mar 3 11:52:08 2017 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 3 Mar 2017 09:52:08 -0700 Subject: [Tutor] printing items form list In-Reply-To: References: Message-ID: <25cc5749-f6e9-cad1-2c45-cfc42f4f075d@wichmann.us> On 03/03/2017 05:12 AM, Rafael Knuth wrote: > I want to print individual items from a list like this: > > You have a book, towel, shirt, pants in your luggage. > > This is my code: > > suitcase = ["book", "towel", "shirt", "pants"] > print ("You have a %s in your luggage." % suitcase) > > Instead of printing out the items on the list, my code appends the > list to the string. How do I need to modify my code? > > == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_7.py == > You have a ['book', 'towel', 'shirt', 'pants'] in your luggage. By way of explanation: suitcase = ["book", "towel", "shirt", "pants"] print(type(suitcase)) print ("You have a %s in your luggage." % suitcase) === You have a ['book', 'towel', 'shirt', 'pants'] in your luggage. suitcase is a list. You explicitly ask for it to be shown a string with "%s", so the list class's string representation method is called to produce what the class thinks is the best way to show what the list contents looks like. that conversion to a string someone else's idea (Python default), but not what you wanted, though; joining with commas is the right choice based on what you said you wanted. From poojabhalode11 at gmail.com Fri Mar 3 11:07:29 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Fri, 3 Mar 2017 11:07:29 -0500 Subject: [Tutor] Tables in Tkinter Message-ID: Hi, I am trying to use tkintertable in Python 2.7 to create a table in GUI using Tkinter. The table that I am trying to get is a table with scrollable rows. I just want to display the data in the table in the Tkinter window. I do not wish to make it interactive, since just want to display the data. it would have two columns: Experiments and sensitivity And number of rows based on the number of experiments present. These number of rows would have a scrollbar attached to it so that the user can scroll to the last row if needed. Can someone please suggest me how I can proceed? I tried reading through the page: https://github.com/dmnfarrell/tkintertable But I am not able to understand how to create or edit the row and column names. I would really appreciate it if you could let me know. Thank you so much. Pooja From poojabhalode11 at gmail.com Fri Mar 3 11:43:20 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Fri, 3 Mar 2017 11:43:20 -0500 Subject: [Tutor] Radiobuttons (two options out of 4) Message-ID: Hi, I am trying to create a GUI with four options out of which the user is supposed to select two. But once the user selected two out of those four options, the others need to get greyed out at that instant. I tried the following thing: *Label(lom, text = "Choose two options from:").grid(row = 9, column = 1, sticky = W)* * check1butt = Checkbutton(lom, text = "A-optimality", variable = check1).grid(row = 10, column = 1, sticky = W)* * check2butt = Checkbutton(lom, text = "D-optimality", variable = check2).grid(row = 11, column = 1, sticky = W)* * check3butt = Checkbutton(lom, text = "E-optimality", variable = check3).grid(row = 12, column = 1, sticky = W)* * check4butt = Checkbutton(lom, text = "Parameter Co-Variance", variable = check4).grid(row = 13, column = 1, sticky = W)* * if check1.get() == 1:* * if check2.get() == 1:* * check3butt.config(state = 'disabled')* * check4butt.config(state = 'disabled')* But here, the other two options do not greyed out after selecting the first and the second option. I am aware that this is still half way there, but this snippet doesnot seem to work the way it should. Can someone please suggest me what I can do? Or any other ways to do this? I was thinking of using Radiobuttons, but then radiobuttons only allow one option to be chosen. Is there a way? Thank you Pooja From zagheni at yahoo.com Fri Mar 3 13:20:32 2017 From: zagheni at yahoo.com (Antonio Zagheni) Date: Fri, 3 Mar 2017 18:20:32 +0000 (UTC) Subject: [Tutor] printing items form list In-Reply-To: References: Message-ID: <1268378263.1408126.1488565232921@mail.yahoo.com> Hello Rafael, I believe you are a beginner... That is another way to do this...----------------------------------------------------------------------------------------------------- suitcase = ["book, ", "towel, ", "shirt, ", "pants"] st = '' for i in suitcase: ??? ??? st = st + i ??? print ("You have a %s in your luggage.") %st ------------------------------------------------------------------------------------------------------------ Best regards... Antonio Zagheni. From: "tutor-request at python.org" To: tutor at python.org Sent: Friday, March 3, 2017 2:00 PM Subject: Tutor Digest, Vol 157, Issue 8 Send Tutor mailing list submissions to ??? tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit ??? https://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to ??? tutor-request at python.org You can reach the person managing the list at ??? tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: ? 1. printing items form list (Rafael Knuth) ? 2. Re: printing items form list (Peter Otten) ---------------------------------------------------------------------- Message: 1 Date: Fri, 3 Mar 2017 13:12:23 +0100 From: Rafael Knuth To: "Tutor at python.org" Subject: [Tutor] printing items form list Message-ID: ??? Content-Type: text/plain; charset=UTF-8 I want to print individual items from a list like this: You have a book, towel, shirt, pants in your luggage. This is my code: suitcase = ["book", "towel", "shirt", "pants"] print ("You have a %s in your luggage." % suitcase) Instead of printing out the items on the list, my code appends the list to the string. How do I need to modify my code? == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_7.py == You have a ['book', 'towel', 'shirt', 'pants'] in your luggage. ------------------------------ Message: 2 Date: Fri, 03 Mar 2017 13:30:23 +0100 From: Peter Otten <__peter__ at web.de> To: tutor at python.org Subject: Re: [Tutor] printing items form list Message-ID: Content-Type: text/plain; charset="ISO-8859-1" Rafael Knuth wrote: > I want to print individual items from a list like this: > > You have a book, towel, shirt, pants in your luggage. > > This is my code: > > suitcase = ["book", "towel", "shirt", "pants"] > print ("You have a %s in your luggage." % suitcase) > > Instead of printing out the items on the list, my code appends the > list to the string. How do I need to modify my code? Have a look at the str.join() method: >>> suitcase = ["book", "towel", "shirt", "pants"] >>> print("You have a %s in your luggage." % ", ".join(suitcase)) You have a book, towel, shirt, pants in your luggage. See ------------------------------ Subject: Digest Footer _______________________________________________ Tutor maillist? -? Tutor at python.org https://mail.python.org/mailman/listinfo/tutor ------------------------------ End of Tutor Digest, Vol 157, Issue 8 ************************************* From __peter__ at web.de Fri Mar 3 13:52:30 2017 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Mar 2017 19:52:30 +0100 Subject: [Tutor] printing items form list References: <1268378263.1408126.1488565232921@mail.yahoo.com> Message-ID: Antonio Zagheni via Tutor wrote: > suitcase = ["book, ", "towel, ", "shirt, ", "pants"] Hm, looks like you opened Rafael's suitcase while he wasn't looking, and sneaked in some commas and spaces ;) That's cheating... From david at graniteweb.com Fri Mar 3 14:01:27 2017 From: david at graniteweb.com (David Rock) Date: Fri, 3 Mar 2017 13:01:27 -0600 Subject: [Tutor] printing items form list In-Reply-To: References: <1268378263.1408126.1488565232921@mail.yahoo.com> Message-ID: > On Mar 3, 2017, at 12:52, Peter Otten <__peter__ at web.de> wrote: > > Antonio Zagheni via Tutor wrote: > >> suitcase = ["book, ", "towel, ", "shirt, ", "pants"] > > Hm, looks like you opened Rafael's suitcase while he wasn't looking, and > sneaked in some commas and spaces ;) > > That's cheating... yeah, just a little. :-) You can use join for this: suitcase = ["book", "towel", "shirt", "pants"] output = ', '.join(suitcase) print ("You have a %s in your luggage.") %output ? David Rock david at graniteweb.com From alan.gauld at yahoo.co.uk Fri Mar 3 14:19:53 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 3 Mar 2017 19:19:53 +0000 Subject: [Tutor] printing items form list In-Reply-To: References: <1268378263.1408126.1488565232921@mail.yahoo.com> Message-ID: On 03/03/17 18:52, Peter Otten wrote: > Antonio Zagheni via Tutor wrote: > >> suitcase = ["book, ", "towel, ", "shirt, ", "pants"] > > Hm, looks like you opened Rafael's suitcase while he wasn't looking, and > sneaked in some commas and spaces ;) > > That's cheating... Its also very difficult to maintain since if you add new items to the suitcase you need to make sure they all have commas except the last one. And inconsistent data formatting in a list is a nightmare. For example, what happens if you decide to sort the list, the last item is no longer last and the commas are all messed up. That's one reason why join() is a better solution, it handles all of that for you. It's also faster, although in a small application you'd never notice the difference. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 3 14:35:25 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 3 Mar 2017 19:35:25 +0000 Subject: [Tutor] Tables in Tkinter In-Reply-To: References: Message-ID: On 03/03/17 16:07, Pooja Bhalode wrote: > The table that I am trying to get is a table with scrollable rows. I just > want to display the data in the table in the Tkinter window. I do not wish > to make it interactive, since just want to display the data. In that case you could just use a scrolled frame (from PMW, which you installed as part of the tkintertable install). Simply add labels using the grid manager into your frame. Set a different background colour for the top row to make them headings and choose appropriate borders and styles. It should be fairly easy to build up a simple display grid that way. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dirkjsoren at gmail.com Fri Mar 3 14:42:44 2017 From: dirkjsoren at gmail.com (DirkJSoren@gmail.com) Date: Fri, 3 Mar 2017 12:42:44 -0700 Subject: [Tutor] printing items form list In-Reply-To: References: <1268378263.1408126.1488565232921@mail.yahoo.com> Message-ID: On 03/03/2017 12:19 PM, Alan Gauld via Tutor wrote: > On 03/03/17 18:52, Peter Otten wrote: >> Antonio Zagheni via Tutor wrote: >> >>> suitcase = ["book, ", "towel, ", "shirt, ", "pants"] >> Hm, looks like you opened Rafael's suitcase while he wasn't looking, and >> sneaked in some commas and spaces ;) >> >> That's cheating... > Its also very difficult to maintain since if you add > new items to the suitcase you need to make sure they > all have commas except the last one. And inconsistent data formatting in > a list is a nightmare. > > For example, what happens if you decide to sort the list, > the last item is no longer last and the commas are all > messed up. > > That's one reason why join() is a better solution, it > handles all of that for you. It's also faster, although > in a small application you'd never notice the difference. > The ','.join(suitcase) is obviously best of all, but if one doesn't know that method, the below suggestion can be fixed with: suitcase = ['book', 'towel', 'shirt', 'pants'] for i in suitcase: st = st + i + ', ' print('You have a s% in your luggage.' % st) From alan.gauld at yahoo.co.uk Fri Mar 3 14:42:58 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 3 Mar 2017 19:42:58 +0000 Subject: [Tutor] Radiobuttons (two options out of 4) In-Reply-To: References: Message-ID: On 03/03/17 16:43, Pooja Bhalode wrote: > I am trying to create a GUI with four options out of which the user is > supposed to select two. But once the user selected two out of those four > options, the others need to get greyed out at that instant. > > I tried the following thing: > > *Label(lom, text = "Choose two options from:").grid(row = 9, column = 1, > sticky = W)* > * check1butt = Checkbutton(lom, text = "A-optimality", variable = > check1).grid(row = 10, column = 1, sticky = W)* > * check2butt = Checkbutton(lom, text = "D-optimality", variable = > check2).grid(row = 11, column = 1, sticky = W)* > * check3butt = Checkbutton(lom, text = "E-optimality", variable = > check3).grid(row = 12, column = 1, sticky = W)* > * check4butt = Checkbutton(lom, text = "Parameter Co-Variance", variable = > check4).grid(row = 13, column = 1, sticky = W)* > * if check1.get() == 1:* > * if check2.get() == 1:* > * check3butt.config(state = 'disabled')* > * check4butt.config(state = 'disabled')* The problem is you are not thinking about this in an event driven way. The two if statements are only ever executed once when you create the GUI, they are never used again. What you need to do is create an event handler that will check how many buttons are checked and if it is 2 set the unchecked buttons to disabled. Then bind that event handler to all four buttons. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From david at graniteweb.com Fri Mar 3 15:00:01 2017 From: david at graniteweb.com (David Rock) Date: Fri, 3 Mar 2017 14:00:01 -0600 Subject: [Tutor] printing items form list In-Reply-To: References: <1268378263.1408126.1488565232921@mail.yahoo.com> Message-ID: <8D7A89C8-F8BD-4A78-B006-81B76E0627A8@graniteweb.com> > On Mar 3, 2017, at 13:42, DirkJSoren at gmail.com wrote: > > On 03/03/2017 12:19 PM, Alan Gauld via Tutor wrote: >> >> That's one reason why join() is a better solution, it >> handles all of that for you. It's also faster, although >> in a small application you'd never notice the difference. >> > The ','.join(suitcase) is obviously best of all, but if one doesn't know that method, the below suggestion can be fixed with: > > suitcase = ['book', 'towel', 'shirt', 'pants'] > > for i in suitcase: > st = st + i + ', ' > > print('You have a s% in your luggage.' % st) There are three issues with that statement. 1. not knowing a method is not an excuse. It?s worth knowing join because it has a lot of flexibility (and it _is_ known because of this discussion) 2. Your code as written doesn?t work because st is not defined before you use it >>> suitcase = ['book', 'towel', 'shirt', 'pants'] >>> for i in suitcase: ... st = st + i + ', ' ... Traceback (most recent call last): File "", line 2, in NameError: name 'st' is not defined 3. Your [fixed] code (added st = ?') and join do NOT do the same thing (note the extra comma and space at the end of yours) join: You have a book, towel, shirt, pants in your luggage. yours: You have a book, towel, shirt, pants, in your luggage. String concatenation with a loop is notorious for adding extra stuff at the end. To get it right, you have to take into account what to do at the end of the list, which adds code complexity. ? David Rock david at graniteweb.com From poojabhalode11 at gmail.com Fri Mar 3 15:59:09 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Fri, 3 Mar 2017 15:59:09 -0500 Subject: [Tutor] Radiobuttons (two options out of 4) In-Reply-To: References: Message-ID: Hi Alan, Thank you for letting me know. I tried putting in the event handlers for the checkbuttons as shown below. num = 0 def selfcheck(event): print "Self Check" num = num + 1 if num == 2: check1butt.config(state = 'disabled') check2butt.config(state = 'disabled') check3butt.config(state = 'disabled') check4sbutt.config(state = 'disabled') Label(lom, text = "Choose two options from:").grid(row = 9, column = 1, sticky = W) check1butt = Checkbutton(lom, text = "A-optimality", variable = check1) check1butt.bind("", selfcheck) check1butt.grid(row = 10, column = 1, sticky = W) check2butt = Checkbutton(lom, text = "D-optimality", variable = check2) check2butt.bind("", selfcheck) check2butt.grid(row = 11, column = 1, sticky = W) check3butt = Checkbutton(lom, text = "E-optimality", variable = check3) check3butt.bind("", selfcheck) check3butt.grid(row = 12, column = 1, sticky = W) check4butt = Checkbutton(lom, text = "Parameter Co-Variance", variable = check4) check4butt.bind("", selfcheck) check4butt.grid(row = 13, column = 1, sticky = W) if check1.get() == 1: if check2.get() == 1: check3butt.config(state = 'disabled') check4butt.config(state = 'disabled') But here, I have the problem where I do not know how to design the function selfcheck. Here, the function should disable the rest of the checkbuttons which are not selected after two options are selected by the user. Can you please let me know how to design the function? Thank you Pooja On Fri, Mar 3, 2017 at 2:42 PM, Alan Gauld via Tutor wrote: > On 03/03/17 16:43, Pooja Bhalode wrote: > > > I am trying to create a GUI with four options out of which the user is > > supposed to select two. But once the user selected two out of those four > > options, the others need to get greyed out at that instant. > > > > I tried the following thing: > > > > *Label(lom, text = "Choose two options from:").grid(row = 9, column = 1, > > sticky = W)* > > * check1butt = Checkbutton(lom, text = "A-optimality", variable = > > check1).grid(row = 10, column = 1, sticky = W)* > > * check2butt = Checkbutton(lom, text = "D-optimality", variable = > > check2).grid(row = 11, column = 1, sticky = W)* > > * check3butt = Checkbutton(lom, text = "E-optimality", variable = > > check3).grid(row = 12, column = 1, sticky = W)* > > * check4butt = Checkbutton(lom, text = "Parameter Co-Variance", variable > = > > check4).grid(row = 13, column = 1, sticky = W)* > > * if check1.get() == 1:* > > * if check2.get() == 1:* > > * check3butt.config(state = 'disabled')* > > * check4butt.config(state = 'disabled')* > > The problem is you are not thinking about this in an event driven way. > The two if statements are only ever executed once when you create the > GUI, they are never used again. > > What you need to do is create an event handler that will check how > many buttons are checked and if it is 2 set the unchecked buttons to > disabled. Then bind that event handler to all four buttons. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > 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 > From poojabhalode11 at gmail.com Fri Mar 3 16:15:56 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Fri, 3 Mar 2017 16:15:56 -0500 Subject: [Tutor] Tables in Tkinter In-Reply-To: References: Message-ID: Hi Alan, Can you please guide me to an example related to this problem? I do not know how to use the scrollable frame, set backgrounds etc. Sorry, I am new to tables in Tkinter. I could not find any examples as well Please let me know. Thank you Pooja On Fri, Mar 3, 2017 at 2:35 PM, Alan Gauld via Tutor wrote: > On 03/03/17 16:07, Pooja Bhalode wrote: > > > The table that I am trying to get is a table with scrollable rows. I just > > want to display the data in the table in the Tkinter window. I do not > wish > > to make it interactive, since just want to display the data. > > In that case you could just use a scrolled frame (from PMW, which you > installed as part of the tkintertable install). Simply add labels > using the grid manager into your frame. Set a different background > colour for the top row to make them headings and choose appropriate > borders and styles. > > It should be fairly easy to build up a simple display grid that way. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > 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 > From jmssnyder at ucdavis.edu Fri Mar 3 17:59:39 2017 From: jmssnyder at ucdavis.edu (Jason Snyder) Date: Fri, 3 Mar 2017 22:59:39 +0000 Subject: [Tutor] Problems with matplotlib Message-ID: I installed the python module matplotlib on a computer and when I try to run a program with the commands: import matplotlib.pyplot as plt I get the following errors: Traceback (most recent call last): File "new.py", line 1, in import matplotlib File "/usr/lib64/python2.7/site-packages/matplotlib/__init__.py", line 151, in from matplotlib.rcsetup import (defaultParams, File "/usr/lib64/python2.7/site-packages/matplotlib/rcsetup.py", line 20, in from matplotlib.colors import is_color_like File "/usr/lib64/python2.7/site-packages/matplotlib/colors.py", line 54, in import matplotlib.cbook as cbook File "/usr/lib64/python2.7/site-packages/matplotlib/cbook.py", line 32, in import new File "/home/www/html/auroratest/new.py", line 8, in plt.scatter(x,y) NameError: name 'plt' is not defined when I try to use something like import matplotlib.image as image I get the following errors: Traceback (most recent call last): File "new.py", line 1, in import matplotlib.image as image File "/usr/lib64/python2.7/site-packages/matplotlib/__init__.py", line 151, in from matplotlib.rcsetup import (defaultParams, File "/usr/lib64/python2.7/site-packages/matplotlib/rcsetup.py", line 20, in from matplotlib.colors import is_color_like File "/usr/lib64/python2.7/site-packages/matplotlib/colors.py", line 54, in import matplotlib.cbook as cbook File "/usr/lib64/python2.7/site-packages/matplotlib/cbook.py", line 32, in import new File "/home/www/html/auroratest/new.py", line 1, in import matplotlib.image as image File "/usr/lib64/python2.7/site-packages/matplotlib/image.py", line 13, in from matplotlib import rcParams ImportError: cannot import name rcParams What is causing these errors and what specific things do I need to do to resolve this. I need this explained clearly in a step by step way. Thanks, Jason -- Jason Snyder PhD From jmssnyder at ucdavis.edu Fri Mar 3 19:28:36 2017 From: jmssnyder at ucdavis.edu (Jason Snyder) Date: Sat, 4 Mar 2017 00:28:36 +0000 Subject: [Tutor] pdf generation problem Message-ID: I have the following program where I am trying to generate a pdf: 1 import matplotlib 2 matplotlib.use('AGG') 3 import matplotlib.pyplot as plt 4 import matplotlib.image as image 5 import matplotlib.gridspec as gridspec 6 from matplotlib.backends.backend_pdf import PdfPages 7 import numpy as np 8 9 np.random.seed(0) 10 11 x, y = np.random.randn(2, 100) 12 13 with PdfPages('wx_plot.pdf') as pdf: 14 fig, (ax1,ax2) = plt.subplots(nrows=2, figsize=(8,11)) 15 gs = gridspec.GridSpec(2, 1, 16 height_ratios=[1.5,3] 17 ) 18 ax1 = plt.subplot(gs[0]) 19 ax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2) 20 ax1.grid(True) 21 ax1.axhline(0, color='black', lw=2) 22 23 ax2 = plt.subplot(gs[1]) 24 ax2.acorr(x, usevlines=True, normed=True, maxlags=50, lw=2) 25 ax2.grid(True) 26 ax2.axhline(0, color='black', lw=2) 27 pdf.savefig('fig') 28 pdf.close() When I run it I get the following error: Traceback (most recent call last): File "testinger.py", line 13, in with PdfPages('wx_plot.pdf') as pdf: AttributeError: __exit__ What is going on here and how do I resolve this issue? From alan.gauld at yahoo.co.uk Fri Mar 3 20:17:40 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 4 Mar 2017 01:17:40 +0000 Subject: [Tutor] Radiobuttons (two options out of 4) In-Reply-To: References: Message-ID: On 03/03/17 20:59, Pooja Bhalode wrote: > I tried putting in the event handlers for the checkbuttons as shown below. > > num = 0 > def selfcheck(event): > print "Self Check" > num = num + 1 > if num == 2: You need num to be inside the function since it needs to be reset to zero on every check. And the increment should only be if the button is checked. Something like(untested pseudo-code) def selfcheck(evt): num = 0 for butt in [butt1,butt2,butt3,butt4]: if butt.isChecked: num += 1 if num == 2 for butt in [butt1,butt2,butt3,butt4]: if not butt.isChecked: butt.disable() else: # if a button is unchecked, re-enable all for butt in [butt1,butt2,butt3,butt4]: butt.enable() You then need to bind that to the mouse click event for each button. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 3 20:21:40 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 4 Mar 2017 01:21:40 +0000 Subject: [Tutor] pdf generation problem In-Reply-To: References: Message-ID: On 04/03/17 00:28, Jason Snyder wrote: > I have the following program where I am trying to generate a pdf: > 6 from matplotlib.backends.backend_pdf import PdfPages > 7 import numpy as np > 13 with PdfPages('wx_plot.pdf') as pdf: > When I run it I get the following error: > > Traceback (most recent call last): > File "testinger.py", line 13, in > with PdfPages('wx_plot.pdf') as pdf: > AttributeError: __exit__ > > What is going on here and how do I resolve this issue? I don't know, but it's not really a python language problem more of a matplotlib/SciPy problem so you should probably try asking first on the SciPy support forum. We don't mind offering general help on third party libraries but that looks like a very specific module issue. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 3 20:47:35 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 4 Mar 2017 01:47:35 +0000 Subject: [Tutor] Tables in Tkinter In-Reply-To: References: Message-ID: On 03/03/17 21:15, Pooja Bhalode wrote: > Hi Alan, > > Can you please guide me to an example related to this problem? I do not > know how to use the scrollable frame, set backgrounds etc. > Sorry, I am new to tables in Tkinter. I could not find any examples as well WE are all new to tables in Tkinter because they don;t exist. You either have to build your own or find a third party one. Here is a very simple 3 row, 2 column table: >>> top = tk.Tk() >>> tab = tk.Frame(top) >>> tk.Label(tab, text="Left", border=2, relief=tk.SUNKEN, width=5).grid(column=0,row=0) >>> tk.Label(tab, text="Right", border=2, relief=tk.SUNKEN, width=5).grid(column=1,row=0) >>> tk.Label(tab, text="1L", border=2, relief=tk.SUNKEN, width=5).grid(column=0,row=1) >>> tk.Label(tab, text="2L", border=2, relief=tk.SUNKEN, width=5).grid(column=0,row=2) >>> tk.Label(tab, text="1R", border=2, relief=tk.SUNKEN, width=5).grid(column=1,row=1) >>> tk.Label(tab, text="2R", border=2, relief=tk.SUNKEN, width=5).grid(column=1,row=2) >>> tab.pack() >>> top.mainloop() I don't have PMW installed but if you substitute tab = pmw.ScrolledFrame(top) for the Frame in my example it might just work! Alternatively there is a ScrolledWindow in Tix, although I've never used it. (Tix also has a Grid and ScrolledGrid pair which I've tried to use but failed to get it to work!) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 3 20:50:32 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 4 Mar 2017 01:50:32 +0000 Subject: [Tutor] Problems with matplotlib In-Reply-To: References: Message-ID: On 03/03/17 22:59, Jason Snyder wrote: > I installed the python module matplotlib on a computer and when I try to > run a program with the commands: > > import matplotlib.pyplot as plt I get the following errors: It could be an installation issue, but really this list is for the core language and standard library. matplotlib is, I think, part of SciPy and you would probably get better support using the dedicated SciPy forum. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Sat Mar 4 02:30:32 2017 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Mar 2017 08:30:32 +0100 Subject: [Tutor] Problems with matplotlib References: Message-ID: Jason Snyder wrote: > I installed the python module matplotlib on a computer and when I try to > run a program with the commands: > > import matplotlib.pyplot as plt I get the following errors: > > Traceback (most recent call last): > File "new.py", line 1, in > import matplotlib > File "/usr/lib64/python2.7/site-packages/matplotlib/__init__.py", line > 151, in > from matplotlib.rcsetup import (defaultParams, > File "/usr/lib64/python2.7/site-packages/matplotlib/rcsetup.py", line > 20, > in > from matplotlib.colors import is_color_like > File "/usr/lib64/python2.7/site-packages/matplotlib/colors.py", line 54, > in > import matplotlib.cbook as cbook > File "/usr/lib64/python2.7/site-packages/matplotlib/cbook.py", line 32, > in > import new > File "/home/www/html/auroratest/new.py", line 8, in > plt.scatter(x,y) > NameError: name 'plt' is not defined > > when I try to use something like import matplotlib.image as image I get > the following errors: > > Traceback (most recent call last): > File "new.py", line 1, in > import matplotlib.image as image > File "/usr/lib64/python2.7/site-packages/matplotlib/__init__.py", line > 151, in > from matplotlib.rcsetup import (defaultParams, > File "/usr/lib64/python2.7/site-packages/matplotlib/rcsetup.py", line > 20, > in > from matplotlib.colors import is_color_like > File "/usr/lib64/python2.7/site-packages/matplotlib/colors.py", line 54, > in > import matplotlib.cbook as cbook > File "/usr/lib64/python2.7/site-packages/matplotlib/cbook.py", line 32, > in > import new This looks like a name clash. There is a module called "new" in Python's standard library, and matplotlib is trying to install that. Instead your own > File "/home/www/html/auroratest/new.py", line 1, in is found. Once you rename your new.py to something else (and remove the corresponding new.pyc) things should start to work again. > import matplotlib.image as image > File "/usr/lib64/python2.7/site-packages/matplotlib/image.py", line 13, > in > from matplotlib import rcParams > ImportError: cannot import name rcParams > > What is causing these errors and what specific things do I need to do to > resolve this. I need this explained clearly in a step by step way. > > Thanks, > > Jason > From __peter__ at web.de Sat Mar 4 02:51:55 2017 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Mar 2017 08:51:55 +0100 Subject: [Tutor] pdf generation problem References: Message-ID: Jason Snyder wrote: > I have the following program where I am trying to generate a pdf: > > 1 import matplotlib > 2 matplotlib.use('AGG') > 3 import matplotlib.pyplot as plt > 4 import matplotlib.image as image > 5 import matplotlib.gridspec as gridspec > 6 from matplotlib.backends.backend_pdf import PdfPages > 7 import numpy as np > 8 > 9 np.random.seed(0) > 10 > 11 x, y = np.random.randn(2, 100) > 12 > 13 with PdfPages('wx_plot.pdf') as pdf: > 14 fig, (ax1,ax2) = plt.subplots(nrows=2, figsize=(8,11)) > 15 gs = gridspec.GridSpec(2, 1, > 16 height_ratios=[1.5,3] > 17 ) > 18 ax1 = plt.subplot(gs[0]) > 19 ax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2) > 20 ax1.grid(True) > 21 ax1.axhline(0, color='black', lw=2) > 22 > 23 ax2 = plt.subplot(gs[1]) > 24 ax2.acorr(x, usevlines=True, normed=True, maxlags=50, lw=2) > 25 ax2.grid(True) > 26 ax2.axhline(0, color='black', lw=2) > 27 pdf.savefig('fig') > 28 pdf.close() > > When I run it I get the following error: > > Traceback (most recent call last): > File "testinger.py", line 13, in > with PdfPages('wx_plot.pdf') as pdf: > AttributeError: __exit__ > > > What is going on here and how do I resolve this issue? You have an old version of matplotlib where the PdfPages class does not yet implement the context manager protocol. You can (1) upgrade the library. In that case line 28 is redundant; just do with PdfPages(...) as pdf: # do stuff (2) continue to use the version you have and close explicitly: pdf = PdfPages(...) # do stuff pdf.close() From tashaburm11 at gmail.com Fri Mar 3 20:37:06 2017 From: tashaburm11 at gmail.com (Tasha Burman) Date: Fri, 3 Mar 2017 20:37:06 -0500 Subject: [Tutor] QUESTION Message-ID: Hello python tutors, I am having difficulty with a power function; what is another way I can do 4**9 without using **? Thanks, Tasha From alan.gauld at yahoo.co.uk Sat Mar 4 03:43:23 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 4 Mar 2017 08:43:23 +0000 Subject: [Tutor] QUESTION In-Reply-To: References: Message-ID: On 04/03/17 01:37, Tasha Burman wrote: > I am having difficulty with a power function; > what is another way I can do 4**9 without using **? You can use the pow() function. answer = pow(4,9) However, I'm not sure that really answers your question? Do you mean that you want to write your own power() function and want help with that? If so ask again with a more specific description of your problem. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Sat Mar 4 03:50:53 2017 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Mar 2017 09:50:53 +0100 Subject: [Tutor] Calculate 4**9 without using **, was Re: QUESTION References: Message-ID: Tasha Burman wrote: > Hello python tutors, > I am having difficulty with a power function; what is another way I can do > 4**9 without using **? Thanks, Hello Tasha, "what is another way I can do 4**9 without using **?" sounds a lot like a homework question -- so you really have to think about it yourself a bit. A few hints: How would you do the calculation with pen and paper? Can you translate that into a Python loop? What kind of loop would you choose to repeat something 9 times? If you are still having difficulties come back here and show us the code you have tried, even if it doesn't work yet. From dvnsarma at gmail.com Sat Mar 4 05:23:44 2017 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Sat, 4 Mar 2017 15:53:44 +0530 Subject: [Tutor] Calculate 4**9 without using **, was Re: QUESTION In-Reply-To: References: Message-ID: Much simpler is 4*4*4*4*4*4*4*4*4 regards, Sarma. On Sat, Mar 4, 2017 at 2:20 PM, Peter Otten <__peter__ at web.de> wrote: > Tasha Burman wrote: > > > Hello python tutors, > > I am having difficulty with a power function; what is another way I can > do > > 4**9 without using **? Thanks, > > Hello Tasha, > > "what is another way I can do 4**9 without using **?" > > sounds a lot like a homework question -- so you really have to think about > it yourself a bit. A few hints: > > How would you do the calculation with pen and paper? > > Can you translate that into a Python loop? What kind of loop would you > choose to repeat something 9 times? > > If you are still having difficulties come back here and show us the code > you > have tried, even if it doesn't work yet. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From __peter__ at web.de Sat Mar 4 05:43:46 2017 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Mar 2017 11:43:46 +0100 Subject: [Tutor] Calculate 4**9 without using **, was Re: QUESTION References: Message-ID: D.V.N.Sarma ??.??.???.???? wrote: > On Sat, Mar 4, 2017 at 2:20 PM, Peter Otten <__peter__ at web.de> wrote: >> "what is another way I can do 4**9 without using **?" >> >> sounds a lot like a homework question -- so you really have to think >> about it yourself a bit. A few hints: >> >> How would you do the calculation with pen and paper? >> >> Can you translate that into a Python loop? What kind of loop would you >> choose to repeat something 9 times? > Much simpler is > > 4*4*4*4*4*4*4*4*4 The idea behind the approach I suggested is to lead towards some level of abstraction. The for-loop can be put into a function, the exponent be given by the user at runtime etc... From gvmcmt at gmail.com Sat Mar 4 11:17:29 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Sat, 4 Mar 2017 21:47:29 +0530 Subject: [Tutor] Calculate 4**9 without using ** Message-ID: Hi, I'm a beginner learning to program with Python. I'm trying to explain a solution in plain English. Please correct me if I'm wrong. Create a function that takes base and exponent as arguments. In the body of the function: set a result variable to the base. User a for-loop with a range of 1 to the exponent. With each iteration, set the result to the product of result times base. After the loop, return the result. Call the function. Regards Sri From poojabhalode11 at gmail.com Sat Mar 4 11:05:01 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Sat, 4 Mar 2017 11:05:01 -0500 Subject: [Tutor] Problems with matplotlib In-Reply-To: References: Message-ID: I had a similar issue when I tried to download matplotlib in my python directory. I think what Peter suggested is correct, if you remove the new file it would work for you. I had the same issue with copy.py file. Hope that helps. On Sat, Mar 4, 2017 at 2:30 AM, Peter Otten <__peter__ at web.de> wrote: > Jason Snyder wrote: > > > I installed the python module matplotlib on a computer and when I try to > > run a program with the commands: > > > > import matplotlib.pyplot as plt I get the following errors: > > > > Traceback (most recent call last): > > File "new.py", line 1, in > > import matplotlib > > File "/usr/lib64/python2.7/site-packages/matplotlib/__init__.py", line > > 151, in > > from matplotlib.rcsetup import (defaultParams, > > File "/usr/lib64/python2.7/site-packages/matplotlib/rcsetup.py", line > > 20, > > in > > from matplotlib.colors import is_color_like > > File "/usr/lib64/python2.7/site-packages/matplotlib/colors.py", line > 54, > > in > > import matplotlib.cbook as cbook > > File "/usr/lib64/python2.7/site-packages/matplotlib/cbook.py", line > 32, > > in > > import new > > File "/home/www/html/auroratest/new.py", line 8, in > > plt.scatter(x,y) > > NameError: name 'plt' is not defined > > > > when I try to use something like import matplotlib.image as image I get > > the following errors: > > > > Traceback (most recent call last): > > File "new.py", line 1, in > > import matplotlib.image as image > > File "/usr/lib64/python2.7/site-packages/matplotlib/__init__.py", line > > 151, in > > from matplotlib.rcsetup import (defaultParams, > > File "/usr/lib64/python2.7/site-packages/matplotlib/rcsetup.py", line > > 20, > > in > > from matplotlib.colors import is_color_like > > File "/usr/lib64/python2.7/site-packages/matplotlib/colors.py", line > 54, > > in > > import matplotlib.cbook as cbook > > File "/usr/lib64/python2.7/site-packages/matplotlib/cbook.py", line > 32, > > in > > import new > > This looks like a name clash. There is a module called "new" in Python's > standard library, and matplotlib is trying to install that. Instead your > own > > > File "/home/www/html/auroratest/new.py", line 1, in > > is found. Once you rename your new.py to something else (and remove the > corresponding new.pyc) things should start to work again. > > > import matplotlib.image as image > > File "/usr/lib64/python2.7/site-packages/matplotlib/image.py", line > 13, > > in > > from matplotlib import rcParams > > ImportError: cannot import name rcParams > > > > What is causing these errors and what specific things do I need to do to > > resolve this. I need this explained clearly in a step by step way. > > > > Thanks, > > > > Jason > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Sat Mar 4 17:56:51 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 4 Mar 2017 22:56:51 +0000 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: On 04/03/17 16:17, Sri Kavi wrote: > I'm a beginner learning to program with Python. I'm trying to explain a > solution in plain English. Please correct me if I'm wrong. See the thread earlier today with the subject QUESTION for more on this topic. > Create a function that takes base and exponent as arguments. > > In the body of the function: > > set a result variable to the base. > Use a for-loop with a range of 1 to the exponent. > With each iteration, set the result to the product of result times base. > After the loop, return the result. Is there anything there that you don't know how to do? If not have a go and if it does not work come back to us with your code and any error messages. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From wombingsac at gmail.com Sat Mar 4 18:05:03 2017 From: wombingsac at gmail.com (Whom Isac) Date: Sun, 05 Mar 2017 09:05:03 +1000 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: <33424b6f-8873-4718-9e6e-5b2c34fadb9c@typeapp.com> Hi there. So if you want to make a function for exponent (e^x)? rather than power such as x**n, then you need to use/import pythons math module such as Numpy. Use: import numpy as np List = [1,2,3,4,5....] np.exp(list) This would give exponential value of each x in the list. If you want to just power by a certain base then use: def powerBase(base,n): ????? return base**n Example print(powerBase(2,3)) should give you 8. That should also do that for you. On Mar 5, 2017, 3:37 AM, at 3:37 AM, Sri Kavi wrote: >Hi, > > >I'm a beginner learning to program with Python. I'm trying to explain a >solution in plain English. Please correct me if I'm wrong. > > >Create a function that takes base and exponent as arguments. > > > >In the body of the function: > >set a result variable to the base. > > > >User a for-loop with a range of 1 to the exponent. > >With each iteration, set the result to the product of result times >base. > > > >After the loop, return the result. > > > >Call the function. > > > > > >Regards >Sri >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor From akleider at sonic.net Sat Mar 4 21:07:23 2017 From: akleider at sonic.net (Alex Kleider) Date: Sat, 04 Mar 2017 18:07:23 -0800 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: On 2017-03-04 08:17, Sri Kavi wrote: > I'm a beginner learning to program with Python. I'm trying to explain a > solution in plain English. Please correct me if I'm wrong. > Create a function that takes base and exponent as arguments. Is seems that you are facing the same problem as Tasha Burman. Sounds like an assignment meant to exercise your use of iteration. i.e. ** and various built in power functions that have been suggested are out of bounds. > In the body of the function: > set a result variable to the base. def pwr(base, exponent): .... res = base ... > User a for-loop with a range of 1 to the exponent. for i in range(begin, end): # The challenge is to pick begin and end. end will be a function of exponent but not exponent itself. I don't think 1 is a good choice for begin. Picking the correct begin is related to dealing with the following: What if any of the following are true, and what should be done in each case? if exponent ==1: ..... if exponent = 0: ..... if exponent < 0: ..... Each of the first two might deserve its own return statement. > > With each iteration, set the result to the product of result times > base. res *= base # same as res = res * base It's a fun little exercise- a bit more complex than I initially thought it would be. Please share your implementation. From steve at pearwood.info Sat Mar 4 22:02:26 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 5 Mar 2017 14:02:26 +1100 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: <20170305030226.GH5689@ando.pearwood.info> On Sat, Mar 04, 2017 at 06:07:23PM -0800, Alex Kleider wrote: > On 2017-03-04 08:17, Sri Kavi wrote: > > >I'm a beginner learning to program with Python. I'm trying to explain a > >solution in plain English. Please correct me if I'm wrong. > > >Create a function that takes base and exponent as arguments. > > Is seems that you are facing the same problem as Tasha Burman. I think you are misunderstanding Sri Kavi's answer. I think that Sri is trying to answer Tasha's question without providing actual working code. This is homework, and Tasha should write the code herself. But Sri has given a description of the algorithm to use. -- Steve From gvmcmt at gmail.com Sat Mar 4 22:06:58 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Sun, 5 Mar 2017 08:36:58 +0530 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: I'm sorry I confused you all. I was trying to reply to Tasha Burman, but I was in digest mode and I didn't know how to turn it off. So far I've been just a lurker here. I also don't know if it's a school assignment. Here's how I would do it. def power(base, exponent): result = base for _ in range(1, exponent): result *= base return result Also, I'm still coming to grips with Python basics and programming in general, so I need your feedback. On Sun, Mar 5, 2017 at 4:26 AM, Alan Gauld via Tutor wrote: > On 04/03/17 16:17, Sri Kavi wrote: > > > I'm a beginner learning to program with Python. I'm trying to explain a > > solution in plain English. Please correct me if I'm wrong. > > See the thread earlier today with the subject QUESTION for > more on this topic. > > > Create a function that takes base and exponent as arguments. > > > > In the body of the function: > > > > set a result variable to the base. > > Use a for-loop with a range of 1 to the exponent. > > With each iteration, set the result to the product of result times base. > > After the loop, return the result. > > Is there anything there that you don't know how to do? > If not have a go and if it does not work come back to us > with your code and any error messages. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > 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 > From gvmcmt at gmail.com Sat Mar 4 23:43:46 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Sun, 5 Mar 2017 10:13:46 +0530 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: Like I just said in my other message, I was trying to reply to Tasha Burman, but I was in digest mode and I didn't know how to change my subscription options in order to reply to individual messages. I also don't know if it's an assignment, but I'm a beginner learning to program, too :) >What if any of the following are true, and what should be done in each case? > if exponent ==1: ..... > if exponent = 0: ..... > if exponent < 0: ..... Here's my implementation. In Python 2.7.12 def power(base, exponent): if exponent == 0: return 1 elif exponent > 0: result = base for _ in xrange(1, exponent): result *= base return result else: exponent = -exponent result = base for _ in xrange(1, exponent): result *= base return 1.0 / result In Python 3.6.0 def power(base, exponent): if exponent == 0: return 1 elif exponent > 0: result = base for _ in range(1, exponent): result *= base return result else: exponent = -exponent result = base for _ in range(1, exponent): result *= base return 1 / result Please share your thoughts. On Sun, Mar 5, 2017 at 7:37 AM, Alex Kleider wrote: > On 2017-03-04 08:17, Sri Kavi wrote: > > I'm a beginner learning to program with Python. I'm trying to explain a >> solution in plain English. Please correct me if I'm wrong. >> > > Create a function that takes base and exponent as arguments. >> > > Is seems that you are facing the same problem as Tasha Burman. > Sounds like an assignment meant to exercise your use of iteration. > i.e. ** and various built in power functions that have been suggested are > out of bounds. > > In the body of the function: >> set a result variable to the base. >> > > def pwr(base, exponent): > .... > res = base > ... > >> User a for-loop with a range of 1 to the exponent. >> > > for i in range(begin, end): # The challenge is to pick begin and end. > > end will be a function of exponent but not exponent itself. > I don't think 1 is a good choice for begin. > Picking the correct begin is related to dealing with the following: > > What if any of the following are true, and what should be done in each > case? > if exponent ==1: ..... > if exponent = 0: ..... > if exponent < 0: ..... > Each of the first two might deserve its own return statement. > > >> With each iteration, set the result to the product of result times base. >> > > res *= base # same as res = res * base > > > It's a fun little exercise- a bit more complex than I initially thought it > would be. > > Please share your implementation. > From __peter__ at web.de Sun Mar 5 05:24:38 2017 From: __peter__ at web.de (Peter Otten) Date: Sun, 05 Mar 2017 11:24:38 +0100 Subject: [Tutor] Calculate 4**9 without using ** References: Message-ID: Sri Kavi wrote: > Like I just said in my other message, I was trying to reply to Tasha > Burman, but I was in digest mode and I didn't know how to change my > subscription options in order to reply to individual messages. I also > don't know if it's an assignment, but I'm a beginner learning to program, > too :) > >>What if any of the following are true, and what should be done in each > case? >> if exponent ==1: ..... >> if exponent = 0: ..... >> if exponent < 0: ..... > > Here's my implementation. > In Python 3.6.0 > > def power(base, exponent): > if exponent == 0: > return 1 > elif exponent > 0: > result = base > > for _ in range(1, exponent): > result *= base > > return result > else: > exponent = -exponent > result = base > > for _ in range(1, exponent): > result *= base > return 1 / result > > Please share your thoughts. You can try to simplify that a bit: - Handle the case with non-negative exponents in one branch - Avoid duplicating the for loop for negative exponents, e. g. by calling power() from within power() Once you have that working you can play around a bit, e. g. - try an alternative implementation using recursion instead of a loop - modify the code to minimize the number of multiplications it needs to perform to get the result From akleider at sonic.net Sun Mar 5 13:03:12 2017 From: akleider at sonic.net (Alex Kleider) Date: Sun, 05 Mar 2017 10:03:12 -0800 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: <2b0b60cce2a7e64cf61cffb23ed952f3@sonic.net> On 2017-03-05 02:24, Peter Otten wrote: > Sri Kavi wrote: > >> Like I just said in my other message, I was trying to reply to Tasha >> Burman, but I was in digest mode and I didn't know how to change my >> subscription options in order to reply to individual messages. I also >> don't know if it's an assignment, but I'm a beginner learning to >> program, >> too :) >> >>> What if any of the following are true, and what should be done in >>> each >> case? >>> if exponent ==1: ..... New discovery: This (if exponent ==1) 'special case' ceases to be special if result is set to 1 rather than to base. It also simplifies the parameters to the range function: range(exponent) rather than range(1, exponent). >>> if exponent = 0: ..... >>> if exponent < 0: ..... If the exponent is negative, one need only reset the base to its reciprocal and the the exponent to its absolute value after which the same algorithm does the job. Alternatively you could simply change the exponent to its absolute value and set a flag and at the end change res to its reciprocal if your flag is set- again avoiding having two separate loops. >> >> Here's my implementation. > >> In Python 3.6.0 >> >> def power(base, exponent): >> if exponent == 0: >> return 1 >> elif exponent > 0: >> result = base >> >> for _ in range(1, exponent): >> result *= base >> >> return result >> else: >> exponent = -exponent >> result = base >> >> for _ in range(1, exponent): >> result *= base >> return 1 / result >> >> Please share your thoughts. > > You can try to simplify that a bit: > > - Handle the case with non-negative exponents in one branch > - Avoid duplicating the for loop for negative exponents, e. g. by > calling > power() from within power() From akleider at sonic.net Sun Mar 5 13:21:17 2017 From: akleider at sonic.net (Alex Kleider) Date: Sun, 05 Mar 2017 10:21:17 -0800 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: <0e40d14abdb232d02bdde37a487eaf72@sonic.net> On 2017-03-05 01:42, Sri Kavi wrote: > I?ve improved it a bit to meet the following conditions: > 1. type(base) == int and exponent == 0 > 2. base == 0 < exponent > 3. (base > 0 or base < 0) and exponent > 0 > 4. base > 0 > exponent > 5. base < 0 > exponent > 6. base == 0 > exponent > > def power(base, exponent): > if type(base) == int and exponent == 0: > return 1 > elif base == 0 < exponent: > return 0 > elif (base > 0 or base < 0) and exponent > 0: > result = base > for _ in range(1, exponent): > result *= base > return result > elif base > 0 > exponent: > exponent = -(exponent) > result = base > for _ in range(1, exponent): > result *= base > return 1 / result > elif base < 0 > exponent: > exponent = -exponent > result = base > for _ in range(1, exponent): > result *= base > return 1 / result > elif base == 0 > exponent: > print('0 cannot be raised to a negative power.') > #Testing first condition > print(power(0, 0)) > print(power(-1, 0)) > print(power(1, 0)) > #Testing second condition > print(power(0, 3)) > #Testing third condition > print(power(2, 3)) > print(power(-2, 3)) > #Testing fourth condition > print(power(2, -3)) > #Testing fifth condition > print(power(-2, -3)) > > #Testing sixth condition > print(power(0, -3)) > > > I don?t know if it?s anywhere near built-in pow() function, but your > reply > made me think about all those conditions and try to see if I can make > my > previous function code a little better. I need your feedback please. > > > Sri You've made your code much more complicated than it need be. Also, what I suggested before can be simplified considerably. The fundamental algorithm is: result = 1 for _ in range(exponent): result = result * base The problem arises if the exponent is 0 or negative, so you only need test for 2 special cases and take appropriate action. You've already dealt with the first: if exponent == 0: return 1 There are two ways of dealing with the other- both mentioned in (a) previous post(s). Keep at it! From akleider at sonic.net Sun Mar 5 13:50:52 2017 From: akleider at sonic.net (Alex Kleider) Date: Sun, 05 Mar 2017 10:50:52 -0800 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: On 2017-03-04 19:06, Sri Kavi wrote: > I'm sorry I confused you all. I was trying to reply to Tasha Burman, > but I > was in digest mode and I didn't know how to turn it off. So far I've > been > just a lurker here. I also don't know if it's a school assignment. > Here's > how I would do it. > > def power(base, exponent): > result = base > > for _ in range(1, exponent): > result *= base > > return result > > Also, I'm still coming to grips with Python basics and programming in > general, so I need your feedback. > > Some new insites: If you initialize result to 1 rather than base, it not only simplifies your range parameter to (exponent) rather than (1, exponent) but ALSO eliminates the need to treat exponent==0 as a special case. So you've only got to deal with exponent<0. def power(base, exponent): """ Returns base**exponent. As yet, does not cope with negative values of exponent. """ result = 1 if exponent<0: pass # earlier posts have suggested what to do for _ in range(exponent): result *= base return result From gvmcmt at gmail.com Sun Mar 5 04:42:29 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Sun, 5 Mar 2017 15:12:29 +0530 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: I?ve improved it a bit to meet the following conditions: 1. type(base) == int and exponent == 0 2. base == 0 < exponent 3. (base > 0 or base < 0) and exponent > 0 4. base > 0 > exponent 5. base < 0 > exponent 6. base == 0 > exponent def power(base, exponent): if type(base) == int and exponent == 0: return 1 elif base == 0 < exponent: return 0 elif (base > 0 or base < 0) and exponent > 0: result = base for _ in range(1, exponent): result *= base return result elif base > 0 > exponent: exponent = -(exponent) result = base for _ in range(1, exponent): result *= base return 1 / result elif base < 0 > exponent: exponent = -exponent result = base for _ in range(1, exponent): result *= base return 1 / result elif base == 0 > exponent: print('0 cannot be raised to a negative power.') #Testing first condition print(power(0, 0)) print(power(-1, 0)) print(power(1, 0)) #Testing second condition print(power(0, 3)) #Testing third condition print(power(2, 3)) print(power(-2, 3)) #Testing fourth condition print(power(2, -3)) #Testing fifth condition print(power(-2, -3)) #Testing sixth condition print(power(0, -3)) I don?t know if it?s anywhere near built-in pow() function, but your reply made me think about all those conditions and try to see if I can make my previous function code a little better. I need your feedback please. Sri On Sun, Mar 5, 2017 at 7:37 AM, Alex Kleider wrote: > On 2017-03-04 08:17, Sri Kavi wrote: > > I'm a beginner learning to program with Python. I'm trying to explain a >> solution in plain English. Please correct me if I'm wrong. >> > > Create a function that takes base and exponent as arguments. >> > > Is seems that you are facing the same problem as Tasha Burman. > Sounds like an assignment meant to exercise your use of iteration. > i.e. ** and various built in power functions that have been suggested are > out of bounds. > > In the body of the function: >> set a result variable to the base. >> > > def pwr(base, exponent): > .... > res = base > ... > >> User a for-loop with a range of 1 to the exponent. >> > > for i in range(begin, end): # The challenge is to pick begin and end. > > end will be a function of exponent but not exponent itself. > I don't think 1 is a good choice for begin. > Picking the correct begin is related to dealing with the following: > > What if any of the following are true, and what should be done in each > case? > if exponent ==1: ..... > if exponent = 0: ..... > if exponent < 0: ..... > Each of the first two might deserve its own return statement. > > >> With each iteration, set the result to the product of result times base. >> > > res *= base # same as res = res * base > > > It's a fun little exercise- a bit more complex than I initially thought it > would be. > > Please share your implementation. > From cmcaine at gmail.com Sun Mar 5 15:02:34 2017 From: cmcaine at gmail.com (Colin Caine) Date: Sun, 5 Mar 2017 20:02:34 +0000 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: Message-ID: It's good that you have thought about the different cases, but now your function is very long. You can make it a lot shorter and simpler if you think about what calculations you want to do with different inputs and what calculation can be shared. On 5 Mar 2017 19:49, "Sri Kavi" wrote: > I?ve improved it a bit to meet the following conditions: > > > > 1. type(base) == int and exponent == 0 > > > > 2. base == 0 < exponent > > > > 3. (base > 0 or base < 0) and exponent > 0 > > > > 4. base > 0 > exponent > > > > 5. base < 0 > exponent > > > > 6. base == 0 > exponent > > > def power(base, exponent): > > if type(base) == int and exponent == 0: > > return 1 > > > elif base == 0 < exponent: > > return 0 > > > elif (base > 0 or base < 0) and exponent > 0: > > result = base > > > for _ in range(1, exponent): > > result *= base > > return result > > > elif base > 0 > exponent: > > exponent = -(exponent) > > result = base > > > for _ in range(1, exponent): > > result *= base > > > > return 1 / result > > > elif base < 0 > exponent: > > exponent = -exponent > > result = base > > > for _ in range(1, exponent): > > result *= base > > return 1 / result > > > elif base == 0 > exponent: > > print('0 cannot be raised to a negative power.') > > > #Testing first condition > > print(power(0, 0)) > > print(power(-1, 0)) > > print(power(1, 0)) > > > #Testing second condition > > print(power(0, 3)) > > #Testing third condition > > print(power(2, 3)) > > print(power(-2, 3)) > > > #Testing fourth condition > > print(power(2, -3)) > > #Testing fifth condition > > print(power(-2, -3)) > > #Testing sixth condition > > print(power(0, -3)) > > > I don?t know if it?s anywhere near built-in pow() function, but your reply > made me think about all those conditions and try to see if I can make my > previous function code a little better. I need your feedback please. > > > Sri > > On Sun, Mar 5, 2017 at 7:37 AM, Alex Kleider wrote: > > > On 2017-03-04 08:17, Sri Kavi wrote: > > > > I'm a beginner learning to program with Python. I'm trying to explain a > >> solution in plain English. Please correct me if I'm wrong. > >> > > > > Create a function that takes base and exponent as arguments. > >> > > > > Is seems that you are facing the same problem as Tasha Burman. > > Sounds like an assignment meant to exercise your use of iteration. > > i.e. ** and various built in power functions that have been suggested are > > out of bounds. > > > > In the body of the function: > >> set a result variable to the base. > >> > > > > def pwr(base, exponent): > > .... > > res = base > > ... > > > >> User a for-loop with a range of 1 to the exponent. > >> > > > > for i in range(begin, end): # The challenge is to pick begin and > end. > > > > end will be a function of exponent but not exponent itself. > > I don't think 1 is a good choice for begin. > > Picking the correct begin is related to dealing with the following: > > > > What if any of the following are true, and what should be done in each > > case? > > if exponent ==1: ..... > > if exponent = 0: ..... > > if exponent < 0: ..... > > Each of the first two might deserve its own return statement. > > > > > >> With each iteration, set the result to the product of result times base. > >> > > > > res *= base # same as res = res * base > > > > > > It's a fun little exercise- a bit more complex than I initially thought > it > > would be. > > > > Please share your implementation. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Sun Mar 5 15:46:29 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 5 Mar 2017 20:46:29 +0000 Subject: [Tutor] Tables in Tkinter In-Reply-To: References: Message-ID: On 04/03/17 01:47, Alan Gauld via Tutor wrote: >> Can you please guide me to an example related to this problem? I had a play and here is a simple DisplayTable widget. Its still not a scrollable frame (although i might get round to that later...) But it takes a list of headings and a 2D list of data values and creates a display grid. You can tweak the colours somewhat. Its a long way from polished but should serve as a starter... ########## displaytable.py ########## try: import Tkinter as tk # v2 except ImportError: import tkinter as tk # v3 class DisplayTable(tk.Frame): def __init__(self, parent, headings, data, hdcolor='red', datacolor='black', gridcolor= 'black', cellcolor='white'): tk.Frame.__init__(self, parent, bg=gridcolor) if len(headings) != len(data[0]): raise ValueError self.headings = headings for index,head in enumerate(headings): width = len(str(head)) cell = tk.Label(self,text=str(head), bg=cellcolor, fg=hdcolor, width=width) cell.grid(row=0,column=index, padx=1, pady=1) for index,row in enumerate(data): self.addRow(index+1,row,datacolor,cellcolor) def addRow(self, row, data, fg='black', bg='white'): for index, item in enumerate(data): width = len(str(self.headings[index])) cell = tk.Label(self,text=str(item), fg=fg, bg=bg, width=width) cell.grid(row=row, column=index, padx=1,pady=1) if __name__ == "__main__": top = tk.Tk() tab = DisplayTable(top, ["Left","Right"], [[1,2], [3,4], [5,6]], datacolor='green') tab.pack() top.mainloop() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From rampappula at gmail.com Sun Mar 5 22:07:37 2017 From: rampappula at gmail.com (ramakrishna reddy) Date: Sun, 5 Mar 2017 19:07:37 -0800 Subject: [Tutor] collections.Callable functionality Message-ID: Hi, Can you please explain the functionality of collections.Callable ? If possible with a code snippet. I could not find a good explanation on google. Thanks, Ram. From rskovron at gmail.com Sun Mar 5 20:33:52 2017 From: rskovron at gmail.com (Rafael Skovron) Date: Sun, 5 Mar 2017 17:33:52 -0800 Subject: [Tutor] Is this a scope issue? Message-ID: This project compares two text files with parcel numbers. I think I'm messing up the function call. I'm getting this error: Traceback (most recent call last): File "amador.py", line 48, in remaining_parcels(auctionlist,removedlist) NameError: name 'auctionlist' is not defined import re fname = 'saclisting.txt' removed = 'removed.txt' def get_parcel_number(fname): #this retrieves parcel numbers from the saclisting file and stores to auctionlist pattern = r'^(\d{3})-(\d{3})-(\d{3})-(\d{3})' auctionlist = [] with open(fname,'r') as file: text = file.readlines() for index,line in enumerate(text): if re.search(pattern,line): #add line to auctionlist if the pattern is found auctionlist.append(line) return auctionlist def get_removed_number(removed): #this grabs the removed parcel numbers and stores to a list pattern = r'^(\d{3})-(\d{3})-(\d{3})-(\d{3})' removedlist = [] with open(removed,'r') as file: text = file.readlines() for index,line in enumerate(text): if re.search(pattern,line): # add line to removedlist removedlist.append(line) return removedlist def remaining_parcels(auctionlist,removedlist): #compares parcels in auctionlist to removedlist and returns parcels that have not bee removed remainingparcels =[] for parcel in auctionlist: if parcel not in removedlist: remainingparcels.append(parcel) return remainingparcels get_parcel_number(fname) get_removed_number(removed) remaining_parcels(auctionlist,removedlist) From alan.gauld at yahoo.co.uk Mon Mar 6 03:20:52 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 6 Mar 2017 08:20:52 +0000 Subject: [Tutor] collections.Callable functionality In-Reply-To: References: Message-ID: On 06/03/17 03:07, ramakrishna reddy wrote: > Can you please explain the functionality of collections.Callable ? If > possible with a code snippet. First of all, do you understand the concept of callable in Python? Any object that can be used like a function is callable. You might have a mixed container of callable and non-callable objects and want to determine at runtime which are which: >>> def f(): return 42 # f is callable >>> lst = [2,'three',f] # only f is callable >>> for item in lst: ... if callable(item): print( item() ) # call it 42 >>> from collections import Callable >>> for item in lst: ... if isinstance((item,Callable): print( item() ) 42 So you can use Callable with isinstance as an alternate to the callable() builtin test. I can't actually think of a situation where I would want to do that but it could arise. Callable is an abstract class that requires an implementation of the method __call__. You can use it as a superclass of your own callable classes. Frankly I'm not sure it's really very useful since you can make your own classes callable by simply adding a __call__ method. And indeed doing so makes your class appear to be an instance of Callable. Somebody obviously thought there was a need for it and persuaded the community. There will be a PEP somewhere you could read. It is 3119... It says among other things: ------------- This PEP proposes a particular strategy for organizing these tests known as Abstract Base Classes, or ABC. ABCs are simply Python classes that are added into an object's inheritance tree to signal certain features of that object to an external inspector. Tests are done using isinstance() , and the presence of a particular ABC means that the test has passed. ------------- So I suspect Callable is simply included for consistency with the other test types. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From gvmcmt at gmail.com Mon Mar 6 02:52:50 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Mon, 6 Mar 2017 13:22:50 +0530 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: <2b0b60cce2a7e64cf61cffb23ed952f3@sonic.net> References: <2b0b60cce2a7e64cf61cffb23ed952f3@sonic.net> Message-ID: I realize how complicated I made it! If exponent is negative, this version takes abs(exponent) and iteratively divides result by base. def power(base, exponent): """ Returns base**exponent. """ if exponent == 0: return 1 elif exponent < 0: result = 1 for _ in range(abs(exponent)): result /= base return result else: result = 1 for _ in range(exponent): result *= base return result If exponent is negative, this version resets base to its reciprocal and exponent to abs(exponent). def power(base, exponent): """ Returns base**exponent. """ if exponent == 0: return 1 elif exponent < 0: base = 1 / base exponent = abs(exponent) result = 1 for _ in range(exponent): result *= base return result else: result = 1 for _ in range(exponent): result *= base return result This version deals with both negative and non-negative exponents in a single loop. I like this. def power(base, exponent): """ Returns base**exponent. """ if exponent == 0: return 1 else: result = 1 for _ in range(abs(exponent)): result *= base if exponent < 0: return 1 / result else: return result I'm learning a lot. Thank you for being so helpful. On Sun, Mar 5, 2017 at 11:33 PM, Alex Kleider wrote: > On 2017-03-05 02:24, Peter Otten wrote: > >> Sri Kavi wrote: >> >> Like I just said in my other message, I was trying to reply to Tasha >>> Burman, but I was in digest mode and I didn't know how to change my >>> subscription options in order to reply to individual messages. I also >>> don't know if it's an assignment, but I'm a beginner learning to program, >>> too :) >>> >>> What if any of the following are true, and what should be done in each >>>> >>> case? >>> >>>> if exponent ==1: ..... >>>> >>> > New discovery: > This (if exponent ==1) 'special case' ceases to be special if result is > set to 1 rather than to base. It also simplifies the parameters to the > range function: range(exponent) rather than range(1, exponent). > > if exponent = 0: ..... >>>> if exponent < 0: ..... >>>> >>> > If the exponent is negative, one need only reset the base to its > reciprocal and the the exponent to its absolute value after which the same > algorithm does the job. > Alternatively you could simply change the exponent to its absolute value > and set a flag and at the end change res to its reciprocal if your flag is > set- again avoiding having two separate loops. > > >>> Here's my implementation. >>> >> >> In Python 3.6.0 >>> >>> def power(base, exponent): >>> if exponent == 0: >>> return 1 >>> elif exponent > 0: >>> result = base >>> >>> for _ in range(1, exponent): >>> result *= base >>> >>> return result >>> else: >>> exponent = -exponent >>> result = base >>> >>> for _ in range(1, exponent): >>> result *= base >>> return 1 / result >>> >>> Please share your thoughts. >>> >> >> You can try to simplify that a bit: >> >> - Handle the case with non-negative exponents in one branch >> - Avoid duplicating the for loop for negative exponents, e. g. by calling >> power() from within power() >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Mon Mar 6 03:28:01 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 6 Mar 2017 08:28:01 +0000 Subject: [Tutor] Is this a scope issue? In-Reply-To: References: Message-ID: On 06/03/17 01:33, Rafael Skovron wrote: > This project compares two text files with parcel numbers. I think I'm > messing up the function call. I'm getting this error: > > Traceback (most recent call last): > File "amador.py", line 48, in > remaining_parcels(auctionlist,removedlist) > NameError: name 'auctionlist' is not defined > Your subject line is correct - it is a scope issue. > fname = 'saclisting.txt' > removed = 'removed.txt' > > def get_parcel_number(fname): > pattern = r'^(\d{3})-(\d{3})-(\d{3})-(\d{3})' > auctionlist = [] Here you create a local variable auctionlist. local variables only exist within the function that creates them. > return auctionlist You return the auctionlist object from the function but.... > > get_parcel_number(fname) You never store the returned object so it gets destroyed. > get_removed_number(removed) > remaining_parcels(auctionlist,removedlist) Now you try calling this function with auctionlist as an argument but thee is no such variable (it only existed inside the first function). You need to store the result of the first function and use that stored value in this function call. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Mon Mar 6 03:31:53 2017 From: __peter__ at web.de (Peter Otten) Date: Mon, 06 Mar 2017 09:31:53 +0100 Subject: [Tutor] collections.Callable functionality References: Message-ID: ramakrishna reddy wrote: > Can you please explain the functionality of collections.Callable ? If > possible with a code snippet. That's a pretty exotic beast that you stumbled upon. >>> from collections.abc import Callable You can use it to check if an object is callable, i. e. works like a function: >>> isinstance("foo", Callable) False >>> isinstance(str, Callable) True >>> isinstance(lambda: 42, Callable) True You can also use it as a baseclass if you want to prevent subclasses from being instantiated unless they implement a __call__() method which makes those instances callable: >>> class C(Callable): pass ... >>> c = C() Traceback (most recent call last): File "", line 1, in TypeError: Can't instantiate abstract class C with abstract methods __call__ >>> class D(C): ... def __call__(self, name="Al"): ... return "You can call me {}".format(name) ... >>> d = D() >>> isinstance(d, Callable) True >>> d() 'You can call me Al' From leamhall at gmail.com Mon Mar 6 12:35:27 2017 From: leamhall at gmail.com (leam hall) Date: Mon, 6 Mar 2017 12:35:27 -0500 Subject: [Tutor] Socket error in class Message-ID: What am I missing? #### class mysocket(): import socket def __init__(self, sock=None); if sock is None: self.sock = socket.socket(socket.socket.AF_NET, socket.socket.SOCK_STREAM) else: self.sock = sock #### Error: NameError: global name "socket" is not defined. From mats at wichmann.us Mon Mar 6 10:35:53 2017 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 6 Mar 2017 08:35:53 -0700 Subject: [Tutor] Is this a scope issue? In-Reply-To: References: Message-ID: <49444565-4482-a16e-e542-156d18f2c638@wichmann.us> On 03/05/2017 06:33 PM, Rafael Skovron wrote: > This project compares two text files with parcel numbers. I think I'm > messing up the function call. I'm getting this error: > > Traceback (most recent call last): > File "amador.py", line 48, in > remaining_parcels(auctionlist,removedlist) > NameError: name 'auctionlist' is not defined > In this code I'd note a couple of things besides "the answer" which was already given. - you seem to have an indentation problem with the last line of each function. Not sure if that was just a paste problem; but the way the "return" statements are placed, they would execute on the first match, not after the whole loop. Indeed, as posted I'd expect you would get an IndentationError because they don't line up with any block; do make sure in your real code they're indented at a level that places them outside the scope of the "with" statement in the first two and outside the "for" loop in the third. - you've got one-liner comments at the beginning of each function definition. Might as well follow convention and turn those into docstrings. As in for example: def get_removed_number(removed): '''this grabs the removed parcel numbers and stores to a list''' - assuming you're a beginner since you are posting here, you could keep in mind as you learn more that many loop+condition test constructs to populate a list can be recoded as a list comprehension. That is: remainingparcels =[] for parcel in auctionlist: if parcel not in removedlist: remainingparcels.append(parcel) is able to be rewritten as: remainingparcels = [parcel for parcel in auctionlist if parcel not in removedlist] at that point you might question whether you even want to have a separate remaining_parcels function, this one-liner could just go in your main body. That's up to you, of course! When I first learned "list comprehensions" I didn't find them more readable than what they can replace; now I definitely do. > > import re > > fname = 'saclisting.txt' > removed = 'removed.txt' > > def get_parcel_number(fname): > #this retrieves parcel numbers from the saclisting file and stores to > auctionlist > > > pattern = r'^(\d{3})-(\d{3})-(\d{3})-(\d{3})' > auctionlist = [] > > > with open(fname,'r') as file: > text = file.readlines() > for index,line in enumerate(text): > if re.search(pattern,line): > #add line to auctionlist if the pattern is found > auctionlist.append(line) > return auctionlist > > def get_removed_number(removed): > #this grabs the removed parcel numbers and stores to a list > pattern = r'^(\d{3})-(\d{3})-(\d{3})-(\d{3})' > removedlist = [] > > with open(removed,'r') as file: > text = file.readlines() > for index,line in enumerate(text): > if re.search(pattern,line): > # add line to removedlist > removedlist.append(line) > return removedlist > > def remaining_parcels(auctionlist,removedlist): > #compares parcels in auctionlist to removedlist and returns parcels that > have not bee removed > remainingparcels =[] > for parcel in auctionlist: > if parcel not in removedlist: > remainingparcels.append(parcel) > return remainingparcels > > > > > get_parcel_number(fname) > get_removed_number(removed) > remaining_parcels(auctionlist,removedlist) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Mon Mar 6 13:06:40 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 6 Mar 2017 18:06:40 +0000 Subject: [Tutor] Socket error in class In-Reply-To: References: Message-ID: On 06/03/17 17:35, leam hall wrote: > What am I missing? I'd start by moving the import out of the class to its more normal position at the top of the file. > #### > class mysocket(): > import socket > def __init__(self, sock=None); > if sock is None: > self.sock = socket.socket(socket.socket.AF_NET, > socket.socket.SOCK_STREAM) > else: > self.sock = sock > > > #### > Error: > NameError: global name "socket" is not defined. I'd then send us the complete error trace so we can see what is causing the error. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Mon Mar 6 13:23:41 2017 From: akleider at sonic.net (Alex Kleider) Date: Mon, 06 Mar 2017 10:23:41 -0800 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: <2b0b60cce2a7e64cf61cffb23ed952f3@sonic.net> Message-ID: <465f4c91535a1543a52761b292f91fcb@sonic.net> On 2017-03-05 23:52, Sri Kavi wrote: > This version deals with both negative and non-negative exponents in a > single loop. I like this. > def power(base, exponent): > """ Returns base**exponent. """ > if exponent == 0: > return 1 > else: > result = 1 > for _ in range(abs(exponent)): > result *= base > if exponent < 0: > return 1 / result > else: > return result > > I'm learning a lot. Thank you for being so helpful. I have enjoyed this little exercise, so thank you for drawing attention to it and continuing to work at it. Note that you don't need the 1st if/else- and even if you did, you wouldn't need the 'else': just 'de-iondent' everything that is in its code block. I believe the following (your code with some deletions) will work: def power(base, exponent): """ Returns base**exponent. """ result = 1 for _ in range(abs(exponent)): result *= base if exponent < 0: return 1 / result else: return result An alternative way to deal with the negative exponent possibility is to test for it at the beginning and if True, set base to its reciprocal and exponent to its absolute value (no need for an else component.) From gvmcmt at gmail.com Mon Mar 6 14:03:17 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Tue, 7 Mar 2017 00:33:17 +0530 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: <465f4c91535a1543a52761b292f91fcb@sonic.net> References: <2b0b60cce2a7e64cf61cffb23ed952f3@sonic.net> <465f4c91535a1543a52761b292f91fcb@sonic.net> Message-ID: Wow, this works like a charm! def power(base, exponent): """ Returns base**exponent. """ result = 1 for _ in range(abs(exponent)): result *= base if exponent < 0: return 1 / result return result On Mon, Mar 6, 2017 at 11:53 PM, Alex Kleider wrote: > On 2017-03-05 23:52, Sri Kavi wrote: > > > > This version deals with both negative and non-negative exponents in a >> single loop. I like this. >> def power(base, exponent): >> """ Returns base**exponent. """ >> if exponent == 0: >> return 1 >> else: >> result = 1 >> for _ in range(abs(exponent)): >> result *= base >> if exponent < 0: >> return 1 / result >> else: >> return result >> >> I'm learning a lot. Thank you for being so helpful. >> > > I have enjoyed this little exercise, so thank you for drawing attention to > it and continuing to work at it. > Note that you don't need the 1st if/else- and even if you did, you > wouldn't need the 'else': just 'de-iondent' everything that is in its code > block. > I believe the following (your code with some deletions) will work: > > def power(base, exponent): > """ Returns base**exponent. """ > result = 1 > for _ in range(abs(exponent)): > result *= base > if exponent < 0: > return 1 / result > else: > return result > > An alternative way to deal with the negative exponent possibility is to > test for it at the beginning and if True, set base to its reciprocal and > exponent to its absolute value (no need for an else component.) > From alan.gauld at yahoo.co.uk Mon Mar 6 14:27:40 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 6 Mar 2017 19:27:40 +0000 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: References: <2b0b60cce2a7e64cf61cffb23ed952f3@sonic.net> <465f4c91535a1543a52761b292f91fcb@sonic.net> Message-ID: On 06/03/17 19:03, Sri Kavi wrote: > Wow, this works like a charm! > def power(base, exponent): > """ Returns base**exponent. """ > result = 1 > for _ in range(abs(exponent)): > result *= base > if exponent < 0: > return 1 / result > return result And just to add to the mix, here's a functional (as in FP) version: from functools import reduce def power(base,exponent): result = reduce(lambda a,b: a*b, [1] + [base]*abs(exponent)) return result if exponent >= 0 else 1/result It basically does the same as the previous version but moves the loop into the reduce function. All to produce an inferior version of a builtin! what fun :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From gvmcmt at gmail.com Mon Mar 6 14:17:46 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Tue, 7 Mar 2017 00:47:46 +0530 Subject: [Tutor] Calculate 4**9 without using ** In-Reply-To: <465f4c91535a1543a52761b292f91fcb@sonic.net> References: <2b0b60cce2a7e64cf61cffb23ed952f3@sonic.net> <465f4c91535a1543a52761b292f91fcb@sonic.net> Message-ID: This. def power(base, exponent): """ Returns base**exponent. """ if exponent < 0: base = 1 / base exponent = abs(exponent) result = 1 for _ in range(exponent): result *= base return result On Mon, Mar 6, 2017 at 11:53 PM, Alex Kleider wrote: > On 2017-03-05 23:52, Sri Kavi wrote: > > > > This version deals with both negative and non-negative exponents in a >> single loop. I like this. >> def power(base, exponent): >> """ Returns base**exponent. """ >> if exponent == 0: >> return 1 >> else: >> result = 1 >> for _ in range(abs(exponent)): >> result *= base >> if exponent < 0: >> return 1 / result >> else: >> return result >> >> I'm learning a lot. Thank you for being so helpful. >> > > I have enjoyed this little exercise, so thank you for drawing attention to > it and continuing to work at it. > Note that you don't need the 1st if/else- and even if you did, you > wouldn't need the 'else': just 'de-iondent' everything that is in its code > block. > I believe the following (your code with some deletions) will work: > > def power(base, exponent): > """ Returns base**exponent. """ > result = 1 > for _ in range(abs(exponent)): > result *= base > if exponent < 0: > return 1 / result > else: > return result > > An alternative way to deal with the negative exponent possibility is to > test for it at the beginning and if True, set base to its reciprocal and > exponent to its absolute value (no need for an else component.) > From mats at wichmann.us Mon Mar 6 16:36:09 2017 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 6 Mar 2017 14:36:09 -0700 Subject: [Tutor] Socket error in class In-Reply-To: References: Message-ID: <214318e0-52c1-3790-00d4-6ea2eac8dff4@wichmann.us> On 03/06/2017 10:35 AM, leam hall wrote: > What am I missing? > > #### > class mysocket(): > import socket > def __init__(self, sock=None); > if sock is None: > self.sock = socket.socket(socket.socket.AF_NET, > socket.socket.SOCK_STREAM) > else: > self.sock = sock > > > #### > Error: > NameError: global name "socket" is not defined. The Python style guide, "PEP8", says this: Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. an import statement creates a module object (if it hasn't been previously imported, that is), and then executes it, leaving the name you imported it as bound to the module object. That means when you do what you did above, "socket" is a name inside the "mysocket" scope, and it's no different than if you defined a class variable - you need to qualify it to access it, it should be available as as self.socket inside a method or as mysocket.socket. But it seems better to do the import at the top instead, then it really looks like a global and there won't be a complaint. Note also in your code (I'm assuming you typed stuff, and did not paste directly from the code you were trying): - your __init__ definition ends with semicolon, not colon - it's AF_INET, not AF_NET - you've doubled "socket" in referring to constants AF_INET and SOCK_STREAM From steve at pearwood.info Mon Mar 6 19:39:10 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 7 Mar 2017 11:39:10 +1100 Subject: [Tutor] Socket error in class In-Reply-To: References: Message-ID: <20170307003909.GL5689@ando.pearwood.info> On Mon, Mar 06, 2017 at 12:35:27PM -0500, leam hall wrote: > What am I missing? Let us start by reading the exception that you get, below the class. That tells us *what* error occurred, but not how or why: > class mysocket(): > import socket > def __init__(self, sock=None); > if sock is None: > self.sock = socket.socket(socket.socket.AF_NET, > socket.socket.SOCK_STREAM) > else: > self.sock = sock > > Error: > NameError: global name "socket" is not defined. It not a *socket* error at all, it is a regular NameError, the same sort of error that you get if you write: x = 1 print(y) # oops I meant x You haven't shown the context for how you get that exception, so I have to guess. You should always show the entire traceback, not just the final line, and you should show the actual line of code that you ran that failed. My GUESS is that you tried to create a mysocket object: mysock = mysocket() and that's when you got the NameError. Or maybe you did something like this: mysock = socket.socket(socket.socket.AF_NET, socket.socket.SOCK_STREAM) and the entire "mysocket" class is irrelevant. You don't give us enough information to tell what you actually did. Either way, the solution is the same: read the exception. It is NameError, so the problem is that Python cannot see the global variable called "socket". Why not? Well, consider this bit of code: class Foo: x = 1 # outside of the class print(x) What would you expect that code to do? Hopefully you expect a NameError: there's no global variable called "x". Setting x inside the class creates a "class variable" (or class attribute, the preferred term to use in Python). You would have to use Foo.x to reference it, not just x. Imports are no different! In your class, you have: class MySocket: import socket but that doesn't create a global variable "socket", it creates a class attribute MySocket.socket. So the fix should be very simple: move the import out of the class and into the top-level, global part of your code: import socket class MySocket: ... That may or may not solve the problem, since I'm only guessing where you get the actual error. If this doesn't solve it, then please write back with the full traceback, not just the final line. -- Steve From gvmcmt at gmail.com Wed Mar 8 14:56:26 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Thu, 9 Mar 2017 01:26:26 +0530 Subject: [Tutor] Lists of duplicates Message-ID: As part of my learning, I was participating in a discussion at: https://discuss.codecademy.com/t/python-lists-of-duplicated-elements/78151 It?s about making a function that returns a list of lists, with each list being all of the elements that are the same as another element in the original list. function([1, 2, 3, 4, 1, 1, 2, 3]) should return [[1, 1, 1], [2, 2], [3, 3], [4]] I wrote and submitted the following function: def sublist_duplicates(lst): sublists = [] for item in set(lst): sublists.append([item] * lst.count(item)) return sublists lst_of_duplicates = [1, 2, 10, 3, 4, 1, 's', 2, 3, 1, 4, 's'] print sublist_duplicates(lst_of_duplicates) A participant told me that that'll grind into a near-halt if there are many different elements, for example range(1_000_000) (1 million unique values, so it checks the whole list (length 1 million) for the count, a million times, a total of 1000 billion operations? I thought he was right. I wrote another version of the function, this time using collections.Counter. from collections import Counter def sublist_duplicates(lst): counts = Counter(lst) sublists = [[k] * counts[k] for k in counts] return sublists _lst = list(range(1000000)) import timeit time = timeit.timeit("sublist_duplicates(_lst)", setup = "from __main__ import sublist_duplicates, _lst", number=1) print("Number of elements in the list: {}".format(len(_lst))) print("Execution time of the function: {} seconds".format(round(time, 2))) I found that the first version works better with a small list, but the second version outperforms the first one when it?s given a considerably big list of data. I?m asking for your comments on these two functions. I?m not even sure if this is how it should be coded. Sri From alan.gauld at yahoo.co.uk Wed Mar 8 20:03:30 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 9 Mar 2017 01:03:30 +0000 Subject: [Tutor] Lists of duplicates In-Reply-To: References: Message-ID: On 08/03/17 19:56, Sri Kavi wrote: > It?s about making a function that returns a list of lists, with each list > being all of the elements that are the same as another element in the > original list. This is one of those problems where there is probably no definitive "correct" answer just different compromises. My first reaction was to sort the initial list then iterate over it creating a new sublist for each change of value. But, it only works for homogenous lists. For mixed types I'd probably opt for a dictionary: def f(lst): res = {} for item in lst: res.setdefault(item,[]).append(item) return list(res.values()) But I've no idea how that performs compared to your methods. > def sublist_duplicates(lst): > sublists = [] > > for item in set(lst): > sublists.append([item] * lst.count(item)) > > return sublists > def sublist_duplicates(lst): > counts = Counter(lst) > sublists = [[k] * counts[k] for k in counts] > return sublists > I found that the first version works better with a small list, but the > second version outperforms the first one when it?s given a considerably big > list of data. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Wed Mar 8 23:29:19 2017 From: akleider at sonic.net (Alex Kleider) Date: Wed, 08 Mar 2017 20:29:19 -0800 Subject: [Tutor] Lists of duplicates In-Reply-To: References: Message-ID: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> On 2017-03-08 17:03, Alan Gauld via Tutor wrote: > On 08/03/17 19:56, Sri Kavi wrote: > >> It?s about making a function that returns a list of lists, with each >> list >> being all of the elements that are the same as another element in the >> original list. > > This is one of those problems where there is probably no > definitive "correct" answer just different compromises. > > My first reaction was to sort the initial list then iterate > over it creating a new sublist for each change of value. > But, it only works for homogenous lists. For mixed types > I'd probably opt for a dictionary: > > def f(lst): > res = {} > for item in lst: > res.setdefault(item,[]).append(item) > return list(res.values()) > > But I've no idea how that performs compared to your methods. The above works BUT how???? Things like this can usually be broken down into their component parts but I've been unsuccessful doing so: def f(lst): res = {} for item in lst: method_res = res.setdefault(item, []) res.method_res.append(item) # res.setdefault(item,[]).append(item) return list(res.values()) res.method_res.append(item) AttributeError: 'dict' object has no attribute 'method_res' Python must be doing some trickery behind the scenes. The algorithm I came up with is: def make_sublists_of_duplicates(original_list): frequency_counter = {} for item in original_list: _ = frequency_counter.setdefault(item, 0) frequency_counter[item] += 1 res = [] for key in frequency_counter: res.append([key for i in range(frequency_counter[key])]) return res although I would argue that the creation of the frequency_counter should be in its own function and then it could be used to create the list of lists IF required. That would get around the criticism of not being able to deal with huge input. From robertvstepp at gmail.com Thu Mar 9 00:14:40 2017 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 8 Mar 2017 23:14:40 -0600 Subject: [Tutor] Lists of duplicates In-Reply-To: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> References: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> Message-ID: On Wed, Mar 8, 2017 at 10:29 PM, Alex Kleider wrote: > On 2017-03-08 17:03, Alan Gauld via Tutor wrote: >> >> My first reaction was to sort the initial list then iterate >> over it creating a new sublist for each change of value. >> But, it only works for homogenous lists. For mixed types >> I'd probably opt for a dictionary: >> >> def f(lst): >> res = {} >> for item in lst: >> res.setdefault(item,[]).append(item) >> return list(res.values()) >> > > The above works BUT > how???? > > Things like this can usually be broken down into their component parts but > I've been unsuccessful doing so: Alex, I think you can break this down as follows: py3: res = {} py3: def key_item_to_res(item): ... res.setdefault(item, []).append(item) ... py3: key_item_to_res(3) py3: res {3: [3]} py3: key_item_to_res(3) py3: res {3: [3, 3]} py3: key_item_to_res(2) py3: res {3: [3, 3], 2: [2]} I think you can play with this and see how Alan's code works. The setdefault(item, []) method checks the dictionary it is acting on for the key, "item". If it finds it then it will execute the "append(item)" method on the sublist attached to that key. If it does not find it, then it creates a new key, "item", attaches the empty list, "[]", to that key, and then appends item to that empty list. boB From akleider at sonic.net Thu Mar 9 01:06:31 2017 From: akleider at sonic.net (Alex Kleider) Date: Wed, 08 Mar 2017 22:06:31 -0800 Subject: [Tutor] Lists of duplicates In-Reply-To: References: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> Message-ID: On 2017-03-08 21:14, boB Stepp wrote: > Alex, I think you can break this down as follows: > > py3: res = {} > py3: def key_item_to_res(item): > ... res.setdefault(item, []).append(item) > ... > py3: key_item_to_res(3) > py3: res > {3: [3]} > py3: key_item_to_res(3) > py3: res > {3: [3, 3]} > py3: key_item_to_res(2) > py3: res > {3: [3, 3], 2: [2]} > > I think you can play with this and see how Alan's code works. The > setdefault(item, []) method checks the dictionary it is acting on for > the key, "item". If it finds it then it will execute the > "append(item)" method on the sublist attached to that key. If it does > not find it, then it creates a new key, "item", attaches the empty > list, "[]", to that key, and then appends item to that empty list. > > > boB It seems you are simply kicking the can down the road rather than explaining how it it is that dot notation actually works. To access a dictionary item one must specify it by name_of_dict[key]. What Allan is (and you also are) doing is using dot notation. Your example uses side effects (which I've been lead to believe is a no no.) The dot notation works (to my surprise) and I was hoping for an explanation of just what is happening. a From __peter__ at web.de Thu Mar 9 03:55:56 2017 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Mar 2017 09:55:56 +0100 Subject: [Tutor] Lists of duplicates References: Message-ID: Alan Gauld via Tutor wrote: > On 08/03/17 19:56, Sri Kavi wrote: > >> It?s about making a function that returns a list of lists, with each list >> being all of the elements that are the same as another element in the >> original list. > > This is one of those problems where there is probably no > definitive "correct" answer just different compromises. > > My first reaction was to sort the initial list then iterate > over it creating a new sublist for each change of value. > But, it only works for homogenous lists. For mixed types > I'd probably opt for a dictionary: > > def f(lst): > res = {} > for item in lst: > res.setdefault(item,[]).append(item) > return list(res.values()) > > But I've no idea how that performs compared to your methods. Performance is probably comparable to the Counter() solution. Digression: There is one important difference that I see as an advantage of Alan's approach -- it keeps the actual values (below I use a defaultdict instead of the setdefault() method): >>> from collections import defaultdict >>> def group(items): ... groups = defaultdict(list) ... for item in items: ... groups[item].append(item) ... return groups ... >>> group([1, 2, 3, True, 2.0, 3.0]) defaultdict(, {1: [1, True], 2: [2, 2.0], 3: [3, 3.0]}) Let's see if we can get output that is a bit more readable: >>> def show(dd): ... for k, v in sorted(dd.items()): print(k, "-->", v) ... >>> show(group([1, 2, 3, True, 2.0, 3.0])) 1 --> [1, True] 2 --> [2, 2.0] 3 --> [3, 3.0] Now it is easy to go one step further and adapt the code to group data by an arbitrary property of item: >>> def groupby(items, key=None): ... if key is None: ... pairs = ((v, v) for v in items) ... else: ... pairs = ((key(v), v) for v in items) ... groups = defaultdict(list) ... for k, v in pairs: ... groups[k].append(v) ... return groups ... >>> show(groupby(["a", "bb", "BB", "CC", "ccc", "bb"])) BB --> ['BB'] CC --> ['CC'] a --> ['a'] bb --> ['bb', 'bb'] ccc --> ['ccc'] >>> show(groupby(["a", "bb", "BB", "CC", "ccc", "bb"], key=str.lower)) a --> ['a'] bb --> ['bb', 'BB', 'bb'] cc --> ['CC'] ccc --> ['ccc'] >>> show(groupby(["a", "bb", "BB", "CC", "ccc", "bb"], key=len)) 1 --> ['a'] 2 --> ['bb', 'BB', 'CC', 'bb'] 3 --> ['ccc'] >>> show(groupby(["a", "bb", "BB", "CC", "ccc", "bb"], key=lambda s: s[:1].lower())) a --> ['a'] b --> ['bb', 'BB', 'bb'] c --> ['CC', 'ccc'] Efficient, flexible -- and you may even sometimes use it for real-world problems. PS: There is a very similar function, itertools.groupby(), in the standard library. In return for the restriction that only adjacent values can be in the same group it works lazily and uses very little memory. From alan.gauld at yahoo.co.uk Thu Mar 9 04:04:28 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 9 Mar 2017 09:04:28 +0000 Subject: [Tutor] Lists of duplicates In-Reply-To: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> References: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> Message-ID: On 09/03/17 04:29, Alex Kleider wrote: >> I'd probably opt for a dictionary: >> >> def f(lst): >> res = {} >> for item in lst: >> res.setdefault(item,[]).append(item) >> return list(res.values()) >> > The above works BUT > how???? setdefault returns the current value for the key or the default, in this case an empty list. So we can split it in two as: for item in lst: val = res.setdefault(item,[]) val.append(item) And since setdefault also assigns the default to the dict if it doesn't exist we don't need to add an extra assignment. We could have used get() instead: for item in lst: sub = res.get(item,[]) sub.append(item) res[item] = sub Is that any clearer? Breaking setdefault() down gives something like: try: sub = res[item] except KeyError: res[item] = [] sub = res[item] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Thu Mar 9 04:10:22 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 9 Mar 2017 09:10:22 +0000 Subject: [Tutor] Lists of duplicates In-Reply-To: References: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> Message-ID: On 09/03/17 06:06, Alex Kleider wrote: > It seems you are simply kicking the can down the road rather than > explaining how it it is that dot notation actually works. The dot notation is just a method access. Dictionaries are like any other object and have many methods. > To access a dictionary item one must specify it by name_of_dict[key]. What makes you think so? There are many ways to access a dictionary, one of which is to use [key]. But there are several methods too and the methods, especially get() are often preferable Try >>> help({}) for more. > What Allan is (and you also are) doing is using dot notation. > Your example uses side effects (which I've been lead to believe is a no > no.) There is a side-effect involved in setdefault() and to be honest I had to do a test before writing my code to be sure that the append() would actually make it back into the dictionary. But there are several Python library features that involve side effects with, perhaps, the list.sort() method being most obvious. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mats at wichmann.us Thu Mar 9 00:22:00 2017 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 8 Mar 2017 22:22:00 -0700 Subject: [Tutor] Lists of duplicates In-Reply-To: References: Message-ID: <37126a81-7239-fd3f-8afb-2a82a66a89ba@wichmann.us> On 03/08/2017 12:56 PM, Sri Kavi wrote: > As part of my learning, I was participating in a discussion at: > > > > https://discuss.codecademy.com/t/python-lists-of-duplicated-elements/78151 > > > > It?s about making a function that returns a list of lists, with each list > being all of the elements that are the same as another element in the > original list. > > > > function([1, 2, 3, 4, 1, 1, 2, 3]) should return [[1, 1, 1], [2, 2], [3, > 3], [4]] > > > I wrote and submitted the following function: > > def sublist_duplicates(lst): > sublists = [] > > for item in set(lst): > sublists.append([item] * lst.count(item)) > > return sublists > > lst_of_duplicates = [1, 2, 10, 3, 4, 1, 's', 2, 3, 1, 4, 's'] > > print sublist_duplicates(lst_of_duplicates) > > A participant told me that that'll grind into a near-halt if there are many > different elements, for example range(1_000_000) (1 million unique values, > so it checks the whole list (length 1 million) for the count, a million > times, a total of 1000 billion operations? > > > I thought he was right. I wrote another version of the function, this time > using collections.Counter. > > from collections import Counter > > def sublist_duplicates(lst): > counts = Counter(lst) > sublists = [[k] * counts[k] for k in counts] > return sublists > > _lst = list(range(1000000)) > > import timeit > > time = timeit.timeit("sublist_duplicates(_lst)", setup = "from __main__ > import sublist_duplicates, _lst", number=1) > > print("Number of elements in the list: {}".format(len(_lst))) > print("Execution time of the function: {} seconds".format(round(time, 2))) > > I found that the first version works better with a small list, but the > second version outperforms the first one when it?s given a considerably big > list of data. > > > I?m asking for your comments on these two functions. I?m not even sure if > this is how it should be coded. Well, my thought was to go for simple. collections.Counter is really designed for this, so why not? First decompose problem: 1. count occurrence of elements in a list 2. emit a list of element/count pairs, each pair as a list repeating the element "count" times as long as count is at least two ("elements that are the same as another element") 3. decide if problem constraints warrant optimization without getting into 3 (there were none in the problem statement), here's what came to mind, looks a lot like your second solution: import random import collections # generate some sample data to work on: nums = [random.randint(1,10) for _ in range(50)] print("list to process:", nums) counted = collections.Counter(nums) print("counts:", counted) countlists = [[item] * counted[item] for item in counted if counted[item] > 1] print("countlists: ", countlists) When I ran this I got: list to process: [2, 6, 1, 2, 2, 5, 6, 6, 10, 2, 3, 8, 6, 6, 4, 2, 8, 2, 1, 1, 8, 4, 3, 5, 6, 6, 6, 4, 5, 1, 1, 8, 6, 3, 6, 10, 2, 7, 9, 4, 3, 6, 2, 4, 10, 4, 5, 1, 2, 7] counts: Counter({6: 11, 2: 9, 1: 6, 4: 6, 3: 4, 5: 4, 8: 4, 10: 3, 7: 2, 9: 1}) countlists: [[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6], [7, 7], [8, 8, 8, 8], [10, 10, 10]] notice value 9 missing from result line, as the count was only 1. From nair.sreekul at gmail.com Thu Mar 9 01:05:10 2017 From: nair.sreekul at gmail.com (Sreekul Nair) Date: Thu, 9 Mar 2017 11:35:10 +0530 Subject: [Tutor] IMAP Login Error - raise self.error(dat[-1]) Message-ID: Dear All, I have tried to search for related issues in StackOverflow and other python forums but to no avail. And I am really growing desperate to resolve this issue. I am not sure who would be able to help me if not you guys. Its an earnest request to please help me understand what I am doing wrong. Below is the Python code that I have written to simply log into my Outlook 365 server. import imaplib mail = imaplib.IMAP4_SSL('mail.o365.mailserver.com') print mail.login('myuserid at domain.com', 'MyPassword') print('Logged in') Running this simple program ends in following error - File "C:\Python27\lib\imaplib.py", line 520, in login raise self.error(dat[-1]) error: LOGIN failed. I have used Python 2.7.12 & 3.6 but to no avail. Request help on this issue. Thanks & regards, Sreekul Nair From gvmcmt at gmail.com Thu Mar 9 05:35:25 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Thu, 9 Mar 2017 16:05:25 +0530 Subject: [Tutor] IMAP Login Error - raise self.error(dat[-1]) In-Reply-To: References: Message-ID: Must be firewall that?s causing the problem? Here?s a third-party IMAP client library called IMAPClient which is easier to use . You may want to take a look at it. http://imapclient.readthedocs.io/en/stable/ Sri On Thu, Mar 9, 2017 at 11:35 AM, Sreekul Nair wrote: > Dear All, > > I have tried to search for related issues in StackOverflow and other python > forums but to no avail. And I am really growing desperate to resolve this > issue. I am not sure who would be able to help me if not you guys. Its an > earnest request to please help me understand what I am doing wrong. > > Below is the Python code that I have written to simply log into my Outlook > 365 server. > > import imaplib > mail = imaplib.IMAP4_SSL('mail.o365.mailserver.com') > print mail.login('myuserid at domain.com', 'MyPassword') > print('Logged in') > > Running this simple program ends in following error - > File "C:\Python27\lib\imaplib.py", line 520, in login > raise self.error(dat[-1]) error: LOGIN failed. > > I have used Python 2.7.12 & 3.6 but to no avail. > > Request help on this issue. > > Thanks & regards, > Sreekul Nair > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Thu Mar 9 05:46:29 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 9 Mar 2017 10:46:29 +0000 Subject: [Tutor] IMAP Login Error - raise self.error(dat[-1]) In-Reply-To: References: Message-ID: On 09/03/17 06:05, Sreekul Nair wrote: > Running this simple program ends in following error - > File "C:\Python27\lib\imaplib.py", line 520, in login > raise self.error(dat[-1]) error: LOGIN failed. First thing to test with errors like this is can you login manually over telnet/ssh using the exact same port and credentials? It's more likely to be a server configuration issue than your Python code. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From nair.sreekul at gmail.com Thu Mar 9 05:43:18 2017 From: nair.sreekul at gmail.com (Sreekul Nair) Date: Thu, 9 Mar 2017 16:13:18 +0530 Subject: [Tutor] IMAP Login Error - raise self.error(dat[-1]) In-Reply-To: References: Message-ID: Hi Sri, Thank you so much for the reply. Really appreciate it. I had thought this might be related to the Firewall. However, I connected to VPN and then tried executing the same program. It still ended in error. Few pointers that I would like to bring to your notice. a) The Ping to my mail.o365..com (This is my outlook server) doesn't work. But I am able to open my emails via http using the same. b) I tried to use imaplib.IMAP_SSL.open method and found the below error - Traceback (most recent call last): File "C:\Sreekul\Python\Dev\sree.py", line 3, in mail.open() File "C:\Python27\lib\imaplib.py", line 1177, in open self.sock = socket.create_connection((host, port)) File "C:\Python27\lib\socket.py", line 575, in create_connection raise err error: [Errno 10061] No connection could be made because the target machine actively refused it The Outlook 365 server IMAP port is 993. I will try to implement the library you gave, but could you please shed some light about what is happening here. Thank you again. Regards, Sreekul Nair Regards Sreekul Nair On Thu, Mar 9, 2017 at 4:05 PM, Sri Kavi wrote: > Must be firewall that?s causing the problem? > > > > Here?s a third-party IMAP client library called IMAPClient which is easier > to use . You may want to take a look at it. > > > http://imapclient.readthedocs.io/en/stable/ > > > Sri > > On Thu, Mar 9, 2017 at 11:35 AM, Sreekul Nair > wrote: > >> Dear All, >> >> I have tried to search for related issues in StackOverflow and other >> python >> forums but to no avail. And I am really growing desperate to resolve this >> issue. I am not sure who would be able to help me if not you guys. Its an >> earnest request to please help me understand what I am doing wrong. >> >> Below is the Python code that I have written to simply log into my Outlook >> 365 server. >> >> import imaplib >> mail = imaplib.IMAP4_SSL('mail.o365.mailserver.com') >> print mail.login('myuserid at domain.com', 'MyPassword') >> print('Logged in') >> >> Running this simple program ends in following error - >> File "C:\Python27\lib\imaplib.py", line 520, in login >> raise self.error(dat[-1]) error: LOGIN failed. >> >> I have used Python 2.7.12 & 3.6 but to no avail. >> >> Request help on this issue. >> >> Thanks & regards, >> Sreekul Nair >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > From steve at pearwood.info Thu Mar 9 08:54:22 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 10 Mar 2017 00:54:22 +1100 Subject: [Tutor] Lists of duplicates In-Reply-To: References: Message-ID: <20170309135421.GQ5689@ando.pearwood.info> On Thu, Mar 09, 2017 at 01:26:26AM +0530, Sri Kavi wrote: > I wrote and submitted the following function: > > def sublist_duplicates(lst): > sublists = [] > for item in set(lst): > sublists.append([item] * lst.count(item)) > return sublists > > lst_of_duplicates = [1, 2, 10, 3, 4, 1, 's', 2, 3, 1, 4, 's'] > > print sublist_duplicates(lst_of_duplicates) > > A participant told me that that'll grind into a near-halt if there are many > different elements, for example range(1_000_000) (1 million unique values, > so it checks the whole list (length 1 million) for the count, a million > times, a total of 1000 billion operations? Correct. lst.count(item) has to walk the entire list, counting elements. It does that in C code, so it is fast, but still, if there are a lot of elements to walk, it takes some time. Then you do it again, and again, and again... For a list with N items, your sublist_duplicates function walks the entire list N*N times. When N is large, N**2 is even larger. > I thought he was right. I wrote another version of the function, this time > using collections.Counter. > > from collections import Counter > > def sublist_duplicates(lst): > counts = Counter(lst) > sublists = [[k] * counts[k] for k in counts] > return sublists > > _lst = list(range(1000000)) [...] > I found that the first version works better with a small list, Yes, but for a small list the total time is likely to be so small that it doesn't really matter. > but the > second version outperforms the first one when it?s given a considerably big > list of data. > > > I?m asking for your comments on these two functions. I?m not even sure if > this is how it should be coded. I agree with your analysis. -- Steve From steve at pearwood.info Thu Mar 9 09:07:28 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 10 Mar 2017 01:07:28 +1100 Subject: [Tutor] Lists of duplicates In-Reply-To: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> References: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> Message-ID: <20170309140726.GR5689@ando.pearwood.info> On Wed, Mar 08, 2017 at 08:29:19PM -0800, Alex Kleider wrote: > Things like this can usually be broken down into their component parts > but I've been unsuccessful doing so: > > def f(lst): > res = {} > for item in lst: > method_res = res.setdefault(item, []) > res.method_res.append(item) > # res.setdefault(item,[]).append(item) > return list(res.values()) > res.method_res.append(item) > > AttributeError: 'dict' object has no attribute 'method_res' > > Python must be doing some trickery behind the scenes. Why do you say that? I'm not sure what result you expected, or what you are trying to do, but you have: res # a dict res.method_res No surprises that this fails with AttributeError. Dicts do not have an attribute or method called "method_res". Perhaps you meant to write: # not this # res.method_res.append( ... ) # this instead method_res.append( ... ) although part of the confusion is that "method_res" is a poorly chosen name. It isn't a method, it is a list. Perhaps it will help if I demonstrate what is going on with setdefault: py> mydict = {} py> alist = mydict.setdefault(1, []) py> alist [] py> mydict {1: []} So when you call setdefault on a dict, if the key is missing, it does two things: - it sets the key to the given default value; - and then it returns that same value. We could write our own setdefault method like this: def setdefault(self, key, default): if key in self: # self is the dictionary itself return self[key] else: self[key] = default return default Notice that default is used twice: it is the *same object*, not a fresh copy. py> id(alist), id(mydict[1]) (3080262860, 3080262860) So if default is a mutable list, changes to that list will show up in two places: py> alist.append(99) py> mydict {1: [99]} -- Steve From steve at pearwood.info Thu Mar 9 09:20:00 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 10 Mar 2017 01:20:00 +1100 Subject: [Tutor] Lists of duplicates In-Reply-To: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> References: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> Message-ID: <20170309142000.GS5689@ando.pearwood.info> On Wed, Mar 08, 2017 at 08:29:19PM -0800, Alex Kleider wrote: > The algorithm I came up with is: > def make_sublists_of_duplicates(original_list): > frequency_counter = {} > for item in original_list: > _ = frequency_counter.setdefault(item, 0) > frequency_counter[item] += 1 > res = [] > for key in frequency_counter: > res.append([key for i in range(frequency_counter[key])]) > return res > > although I would argue that the creation of the frequency_counter should > be in its own function Indeed it should, and that function already exists. It is called collections.Counter. from collections import Counter frequencies = Counter(original_list) -- Steve From chima_eloka at yahoo.com Thu Mar 9 08:28:05 2017 From: chima_eloka at yahoo.com (Eloka Chima) Date: Thu, 9 Mar 2017 13:28:05 +0000 (UTC) Subject: [Tutor] Help!! Code ridden with Bugs References: <1735435946.3514692.1489066085141.ref@mail.yahoo.com> Message-ID: <1735435946.3514692.1489066085141@mail.yahoo.com> I am new to programming but an immersive ?study in the past few weeks have brought me to speed so I can play around with codes but not really mastered them.My assignment below is ridden with bugs and I've done so much to get rid of them but to no avail. Below is the project : Create a class called ShoppingCart. Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items. Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item. Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly. If the quantity of an item to be removed exceeds the current quantity?of that item in the cart, assume that all entries of that item are to be removed. Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough". Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100. Make sure Shop inherits from ShoppingCart. In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one''' And below here is my code: class ShoppingCart(object): ? def __init__(self): ? ? self.items = {} ? ? self.total = 0 ? def add_item(self,item_name,quantity,price): ? ? self.item_name = item_name ? ? self.quantity = quantity ? ? self.price = price? ? ? ? if not self.item_name in self.items: ? ? ? ? self.items[self.item_name] = self.quantity ? ? ? ? self.total +=self.price ? def remove_item(self,item_name,quantity,price): ? ? self.item_name = item_name ? ? self.quantity = quantity ? ? self.price = price ? ? ? for self.item_name in self.items: ? ? ? ? if self.item_name in self.items: ? ? ? ? ? del self.items[self.item_name] ? ? ? ? ? self.total -= self.price ? ? ? ? ? if self.quantity > self.items: ? ? ? ? ? ? self.items = 0 ? ? ? return self.items ? def checkout(self, cash_paid): ? ? self.cash_paid = cash_paid ? ? if self.cash_paid < self.total: ? ? ? self.total -= self.cash_paid ? ? ? return self.total ? ? ? return "Cash paid is not enough" class Shop(ShoppingCart): ? def __init__(self): ? ? self.quantity = 100 ? def remove_item(self): ? ? self.quantity -= 1 ? ? return self.quantity? Below is the tests: import unittest class ShoppingCartTestCases(unittest.TestCase): ? def setUp(self): ? ? self.cart = ShoppingCart() ? ? self.shop = Shop() ? ?? ? def test_cart_property_initialization(self): ? ? self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct') ? ? self.assertIsInstance(self.cart.items, dict, msg='Items is not a dictionary') ? ?? ? def test_add_item(self): ? ? self.cart.add_item('Mango', 3, 10) ? ?? ? ? self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items') ? ? self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items not correct after adding item') ? ?? ? def test_remove_item(self): ? ? self.cart.add_item('Mango', 3, 10) ? ? self.cart.remove_item('Mango', 2, 10) ? ?? ? ? self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item') ? ? self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item') ? ?? ? def test_checkout_returns_correct_balance(self): ? ? self.cart.add_item('Mango', 3, 10) ? ? self.cart.add_item('Orange', 16, 10) ? ?? ? ? self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct') ? ? self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct') ? ?? ? def test_shop_is_instance_of_shopping_cart(self): ? ? self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart') ? def test_shop_remove_item_method(self): ? ? for i in range(15): ? ? ? self.shop.remove_item() ? ? self.assertEqual(self.shop.quantity, 85) From joel.goldstick at gmail.com Thu Mar 9 14:32:25 2017 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 9 Mar 2017 14:32:25 -0500 Subject: [Tutor] Help!! Code ridden with Bugs In-Reply-To: <1735435946.3514692.1489066085141@mail.yahoo.com> References: <1735435946.3514692.1489066085141.ref@mail.yahoo.com> <1735435946.3514692.1489066085141@mail.yahoo.com> Message-ID: On Thu, Mar 9, 2017 at 8:28 AM, Eloka Chima via Tutor wrote: > I am new to programming but an immersive study in the past few weeks have brought me to speed so I can play around with codes but not really mastered them.My assignment below is ridden with bugs and I've done so much to get rid of them but to no avail. > Below is the project : > > Create a class called ShoppingCart. > > Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items. > > Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item. > > Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly. > > If the quantity of an item to be removed exceeds the current quantity of that item in the cart, assume that all entries of that item are to be removed. > > Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough". > > Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100. > > Make sure Shop inherits from ShoppingCart. > > In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one''' > > > > > And below here is my code: > > class ShoppingCart(object): > > def __init__(self): > > self.items = {} > > self.total = 0 > > def add_item(self,item_name,quantity,price): > > self.item_name = item_name > > self.quantity = quantity > > self.price = price > > if not self.item_name in self.items: > > self.items[self.item_name] = self.quantity > > self.total +=self.price > > def remove_item(self,item_name,quantity,price): > > self.item_name = item_name > > self.quantity = quantity > > self.price = price > > for self.item_name in self.items: > > if self.item_name in self.items: > > del self.items[self.item_name] > > self.total -= self.price > > if self.quantity > self.items: > > self.items = 0 > > return self.items > > def checkout(self, cash_paid): > > self.cash_paid = cash_paid > > if self.cash_paid < self.total: > > self.total -= self.cash_paid > > return self.total > > return "Cash paid is not enough" > > class Shop(ShoppingCart): > > def __init__(self): > > self.quantity = 100 > > def remove_item(self): > > self.quantity -= 1 > > return self.quantity > > > > > Below is the tests: > > > > > import unittest > > > > > class ShoppingCartTestCases(unittest.TestCase): > > def setUp(self): > > self.cart = ShoppingCart() > > self.shop = Shop() > > > > def test_cart_property_initialization(self): > > self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct') > > self.assertIsInstance(self.cart.items, dict, msg='Items is not a dictionary') > > > > def test_add_item(self): > > self.cart.add_item('Mango', 3, 10) > > > > self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items') > > self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items not correct after adding item') > > > > def test_remove_item(self): > > self.cart.add_item('Mango', 3, 10) > > self.cart.remove_item('Mango', 2, 10) > > > > self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item') > > self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item') > > > > def test_checkout_returns_correct_balance(self): > > self.cart.add_item('Mango', 3, 10) > > self.cart.add_item('Orange', 16, 10) > > > > self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct') > > self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct') > > > > def test_shop_is_instance_of_shopping_cart(self): > > self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart') > > > > > def test_shop_remove_item_method(self): > > for i in range(15): > > self.shop.remove_item() > > > > > > > self.assertEqual(self.shop.quantity, 85) Welcome. Two things: First, format your code correctly, it is double spaced. Second, what exactly is wrong with your code? If it runs, but outputs the wrong values, point that out. If it fails to run, copy and paste the complete traceback so that others can identify where you have gone wrong. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From gvmcmt at gmail.com Thu Mar 9 12:26:07 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Thu, 9 Mar 2017 22:56:07 +0530 Subject: [Tutor] Help!! Code ridden with Bugs In-Reply-To: <1735435946.3514692.1489066085141@mail.yahoo.com> References: <1735435946.3514692.1489066085141.ref@mail.yahoo.com> <1735435946.3514692.1489066085141@mail.yahoo.com> Message-ID: def checkout(self, cash_paid): self.cash_paid = cash_paid if self.cash_paid < self.total: self.total -= self.cash_paid return self.total return "Cash paid is not enough" You cannot return two values. Sri On Thu, Mar 9, 2017 at 6:58 PM, Eloka Chima via Tutor wrote: > I am new to programming but an immersive study in the past few weeks have > brought me to speed so I can play around with codes but not really mastered > them.My assignment below is ridden with bugs and I've done so much to get > rid of them but to no avail. > Below is the project : > > Create a class called ShoppingCart. > > Create a constructor that takes no arguments and sets the total attribute > to zero, and initializes an empty dict attribute named items. > > Create a method add_item that requires item_name, quantity and price > arguments. This method should add the cost of the added items to the > current value of total. It should also add an entry to the items dict such > that the key is the item_name and the value is the quantity of the item. > > Create a method remove_item that requires similar arguments as add_item. > It should remove items that have been added to the shopping cart and are > not required. This method should deduct the cost of the removed items from > the current total and also update the items dict accordingly. > > If the quantity of an item to be removed exceeds the current quantity of > that item in the cart, assume that all entries of that item are to be > removed. > > Create a method checkout that takes in cash_paid and returns the value of > balance from the payment. If cash_paid is not enough to cover the total, > return "Cash paid not enough". > > Create a class called Shop that has a constructor which takes no arguments > and initializes an attribute called quantity at 100. > > Make sure Shop inherits from ShoppingCart. > > In the Shop class, override the remove_item method, such that calling > Shop's remove_item with no arguments decrements quantity by one''' > > > > > And below here is my code: > > class ShoppingCart(object): > > def __init__(self): > > self.items = {} > > self.total = 0 > > def add_item(self,item_name,quantity,price): > > self.item_name = item_name > > self.quantity = quantity > > self.price = price > > if not self.item_name in self.items: > > self.items[self.item_name] = self.quantity > > self.total +=self.price > > def remove_item(self,item_name,quantity,price): > > self.item_name = item_name > > self.quantity = quantity > > self.price = price > > for self.item_name in self.items: > > if self.item_name in self.items: > > del self.items[self.item_name] > > self.total -= self.price > > if self.quantity > self.items: > > self.items = 0 > > return self.items > > def checkout(self, cash_paid): > > self.cash_paid = cash_paid > > if self.cash_paid < self.total: > > self.total -= self.cash_paid > > return self.total > > return "Cash paid is not enough" > > class Shop(ShoppingCart): > > def __init__(self): > > self.quantity = 100 > > def remove_item(self): > > self.quantity -= 1 > > return self.quantity > > > > > Below is the tests: > > > > > import unittest > > > > > class ShoppingCartTestCases(unittest.TestCase): > > def setUp(self): > > self.cart = ShoppingCart() > > self.shop = Shop() > > > > def test_cart_property_initialization(self): > > self.assertEqual(self.cart.total, 0, msg='Initial value of total not > correct') > > self.assertIsInstance(self.cart.items, dict, msg='Items is not a > dictionary') > > > > def test_add_item(self): > > self.cart.add_item('Mango', 3, 10) > > > > self.assertEqual(self.cart.total, 30, msg='Cart total not correct > after adding items') > > self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items > not correct after adding item') > > > > def test_remove_item(self): > > self.cart.add_item('Mango', 3, 10) > > self.cart.remove_item('Mango', 2, 10) > > > > self.assertEqual(self.cart.total, 10, msg='Cart total not correct > after removing item') > > self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items > not correct after removing item') > > > > def test_checkout_returns_correct_balance(self): > > self.cart.add_item('Mango', 3, 10) > > self.cart.add_item('Orange', 16, 10) > > > > self.assertEqual(self.cart.checkout(265), 75, msg='Balance of > checkout not correct') > > self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', > msg='Balance of checkout not correct') > > > > def test_shop_is_instance_of_shopping_cart(self): > > self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not > a subclass of ShoppingCart') > > > > > def test_shop_remove_item_method(self): > > for i in range(15): > > self.shop.remove_item() > > > > > > > self.assertEqual(self.shop.quantity, 85) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From chima_eloka at yahoo.com Thu Mar 9 13:41:26 2017 From: chima_eloka at yahoo.com (Eloka Chima) Date: Thu, 9 Mar 2017 18:41:26 +0000 (UTC) Subject: [Tutor] Help!! Code ridden with Bugs In-Reply-To: References: <1735435946.3514692.1489066085141.ref@mail.yahoo.com> <1735435946.3514692.1489066085141@mail.yahoo.com> Message-ID: <801832202.3986800.1489084886511@mail.yahoo.com> Your Code Solution Has Errors THERE IS AN ERROR/BUG IN YOUR CODE Results:?Traceback (most recent call last): File "python/nose2/bin/nose2", line 8, in discover() File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 300, in discover return main(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 100, in __init__ super(PluggableTestProgram, self).__init__(**kw) File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__ self.parseArgs(argv) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 133, in parseArgs self.createTests() File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 258, in createTests self.testNames, self.module) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/loader.py", line 67, in loadTestsFromNames for name in event.names] File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/loader.py", line 82, in loadTestsFromName result = self.session.hooks.loadTestsFromName(event) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/events.py", line 224, in __call__ result = getattr(plugin, self.method)(event) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/plugins/loader/testclasses.py", line 119, in loadTestsFromName result = util.test_from_name(name, module) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/util.py", line 106, in test_from_name parent, obj = object_from_name(name, module) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/util.py", line 117, in object_from_name module = __import__('.'.join(parts_copy)) File "/home/ubuntu/Applications/andelabs-server/tmp/58b15152d171bb1a00a61531-586ba236d394751500fff7e4-test.py", line 4, in from tmp.andelabs_58b15152d171bb1a00a61531_586ba236d394751500fff7e4 import * File "/home/ubuntu/Applications/andelabs-server/tmp/andelabs_58b15152d171bb1a00a61531_586ba236d394751500fff7e4.py", line 17 if not self.item_name in self.items: ^IndentationError: unexpected indentI get this error when I run the code. After editing the code I sent.?Thanks. Sent from Yahoo Mail on Android On Thu, 9 Mar 2017 at 6:26 pm, Sri Kavi wrote: ?def checkout(self, cash_paid): ? ? self.cash_paid = cash_paid ? ? if self.cash_paid < self.total: ? ? ? self.total -= self.cash_paid ? ? ? return self.total ? ? ? return "Cash paid is not enough" You cannot return two values. Sri On Thu, Mar 9, 2017 at 6:58 PM, Eloka Chima via Tutor wrote: I am new to programming but an immersive ?study in the past few weeks have brought me to speed so I can play around with codes but not really mastered them.My assignment below is ridden with bugs and I've done so much to get rid of them but to no avail. Below is the project : Create a class called ShoppingCart. Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items. Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item. Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly. If the quantity of an item to be removed exceeds the current quantity?of that item in the cart, assume that all entries of that item are to be removed. Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough". Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100. Make sure Shop inherits from ShoppingCart. In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one''' And below here is my code: class ShoppingCart(object): ? def __init__(self): ? ? self.items = {} ? ? self.total = 0 ? def add_item(self,item_name, quantity,price): ? ? self.item_name = item_name ? ? self.quantity = quantity ? ? self.price = price? ? ? ? if not self.item_name in self.items: ? ? ? ? self.items[self.item_name] = self.quantity ? ? ? ? self.total +=self.price ? def remove_item(self,item_name, quantity,price): ? ? self.item_name = item_name ? ? self.quantity = quantity ? ? self.price = price ? ? ? for self.item_name in self.items: ? ? ? ? if self.item_name in self.items: ? ? ? ? ? del self.items[self.item_name] ? ? ? ? ? self.total -= self.price ? ? ? ? ? if self.quantity > self.items: ? ? ? ? ? ? self.items = 0 ? ? ? return self.items ? def checkout(self, cash_paid): ? ? self.cash_paid = cash_paid ? ? if self.cash_paid < self.total: ? ? ? self.total -= self.cash_paid ? ? ? return self.total ? ? ? return "Cash paid is not enough" class Shop(ShoppingCart): ? def __init__(self): ? ? self.quantity = 100 ? def remove_item(self): ? ? self.quantity -= 1 ? ? return self.quantity? Below is the tests: import unittest class ShoppingCartTestCases( unittest.TestCase): ? def setUp(self): ? ? self.cart = ShoppingCart() ? ? self.shop = Shop() ? ?? ? def test_cart_property_ initialization(self): ? ? self.assertEqual(self.cart. total, 0, msg='Initial value of total not correct') ? ? self.assertIsInstance(self. cart.items, dict, msg='Items is not a dictionary') ? ?? ? def test_add_item(self): ? ? self.cart.add_item('Mango', 3, 10) ? ?? ? ? self.assertEqual(self.cart. total, 30, msg='Cart total not correct after adding items') ? ? self.assertEqual(self.cart. items['Mango'], 3, msg='Quantity of items not correct after adding item') ? ?? ? def test_remove_item(self): ? ? self.cart.add_item('Mango', 3, 10) ? ? self.cart.remove_item('Mango', 2, 10) ? ?? ? ? self.assertEqual(self.cart. total, 10, msg='Cart total not correct after removing item') ? ? self.assertEqual(self.cart. items['Mango'], 1, msg='Quantity of items not correct after removing item') ? ?? ? def test_checkout_returns_correct_ balance(self): ? ? self.cart.add_item('Mango', 3, 10) ? ? self.cart.add_item('Orange', 16, 10) ? ?? ? ? self.assertEqual(self.cart. checkout(265), 75, msg='Balance of checkout not correct') ? ? self.assertEqual(self.cart. checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct') ? ?? ? def test_shop_is_instance_of_ shopping_cart(self): ? ? self.assertTrue(isinstance( self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart') ? def test_shop_remove_item_method( self): ? ? for i in range(15): ? ? ? self.shop.remove_item() ? ? self.assertEqual(self.shop. quantity, 85) ______________________________ _________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/ mailman/listinfo/tutor From chima_eloka at yahoo.com Thu Mar 9 13:42:35 2017 From: chima_eloka at yahoo.com (Eloka Chima) Date: Thu, 9 Mar 2017 18:42:35 +0000 (UTC) Subject: [Tutor] Help!! Code ridden with Bugs In-Reply-To: <801832202.3986800.1489084886511@mail.yahoo.com> References: <1735435946.3514692.1489066085141.ref@mail.yahoo.com> <1735435946.3514692.1489066085141@mail.yahoo.com> <801832202.3986800.1489084886511@mail.yahoo.com> Message-ID: <653078988.3995685.1489084955650@mail.yahoo.com> Is my code okay. Sent from Yahoo Mail on Android On Thu, 9 Mar 2017 at 7:41 pm, Eloka Chima wrote: Your Code Solution Has Errors THERE IS AN ERROR/BUG IN YOUR CODE Results:?Traceback (most recent call last): File "python/nose2/bin/nose2", line 8, in discover() File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 300, in discover return main(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 100, in __init__ super(PluggableTestProgram, self).__init__(**kw) File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__ self.parseArgs(argv) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 133, in parseArgs self.createTests() File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 258, in createTests self.testNames, self.module) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/loader.py", line 67, in loadTestsFromNames for name in event.names] File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/loader.py", line 82, in loadTestsFromName result = self.session.hooks.loadTestsFromName(event) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/events.py", line 224, in __call__ result = getattr(plugin, self.method)(event) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/plugins/loader/testclasses.py", line 119, in loadTestsFromName result = util.test_from_name(name, module) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/util.py", line 106, in test_from_name parent, obj = object_from_name(name, module) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/util.py", line 117, in object_from_name module = __import__('.'.join(parts_copy)) File "/home/ubuntu/Applications/andelabs-server/tmp/58b15152d171bb1a00a61531-586ba236d394751500fff7e4-test.py", line 4, in from tmp.andelabs_58b15152d171bb1a00a61531_586ba236d394751500fff7e4 import * File "/home/ubuntu/Applications/andelabs-server/tmp/andelabs_58b15152d171bb1a00a61531_586ba236d394751500fff7e4.py", line 17 if not self.item_name in self.items: ^IndentationError: unexpected indentI get this error when I run the code. After editing the code I sent.?Thanks. Sent from Yahoo Mail on Android On Thu, 9 Mar 2017 at 6:26 pm, Sri Kavi wrote: ?def checkout(self, cash_paid): ? ? self.cash_paid = cash_paid ? ? if self.cash_paid < self.total: ? ? ? self.total -= self.cash_paid ? ? ? return self.total ? ? ? return "Cash paid is not enough" You cannot return two values. Sri On Thu, Mar 9, 2017 at 6:58 PM, Eloka Chima via Tutor wrote: I am new to programming but an immersive ?study in the past few weeks have brought me to speed so I can play around with codes but not really mastered them.My assignment below is ridden with bugs and I've done so much to get rid of them but to no avail. Below is the project : Create a class called ShoppingCart. Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items. Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item. Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly. If the quantity of an item to be removed exceeds the current quantity?of that item in the cart, assume that all entries of that item are to be removed. Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough". Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100. Make sure Shop inherits from ShoppingCart. In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one''' And below here is my code: class ShoppingCart(object): ? def __init__(self): ? ? self.items = {} ? ? self.total = 0 ? def add_item(self,item_name, quantity,price): ? ? self.item_name = item_name ? ? self.quantity = quantity ? ? self.price = price? ? ? ? if not self.item_name in self.items: ? ? ? ? self.items[self.item_name] = self.quantity ? ? ? ? self.total +=self.price ? def remove_item(self,item_name, quantity,price): ? ? self.item_name = item_name ? ? self.quantity = quantity ? ? self.price = price ? ? ? for self.item_name in self.items: ? ? ? ? if self.item_name in self.items: ? ? ? ? ? del self.items[self.item_name] ? ? ? ? ? self.total -= self.price ? ? ? ? ? if self.quantity > self.items: ? ? ? ? ? ? self.items = 0 ? ? ? return self.items ? def checkout(self, cash_paid): ? ? self.cash_paid = cash_paid ? ? if self.cash_paid < self.total: ? ? ? self.total -= self.cash_paid ? ? ? return self.total ? ? ? return "Cash paid is not enough" class Shop(ShoppingCart): ? def __init__(self): ? ? self.quantity = 100 ? def remove_item(self): ? ? self.quantity -= 1 ? ? return self.quantity? Below is the tests: import unittest class ShoppingCartTestCases( unittest.TestCase): ? def setUp(self): ? ? self.cart = ShoppingCart() ? ? self.shop = Shop() ? ?? ? def test_cart_property_ initialization(self): ? ? self.assertEqual(self.cart. total, 0, msg='Initial value of total not correct') ? ? self.assertIsInstance(self. cart.items, dict, msg='Items is not a dictionary') ? ?? ? def test_add_item(self): ? ? self.cart.add_item('Mango', 3, 10) ? ?? ? ? self.assertEqual(self.cart. total, 30, msg='Cart total not correct after adding items') ? ? self.assertEqual(self.cart. items['Mango'], 3, msg='Quantity of items not correct after adding item') ? ?? ? def test_remove_item(self): ? ? self.cart.add_item('Mango', 3, 10) ? ? self.cart.remove_item('Mango', 2, 10) ? ?? ? ? self.assertEqual(self.cart. total, 10, msg='Cart total not correct after removing item') ? ? self.assertEqual(self.cart. items['Mango'], 1, msg='Quantity of items not correct after removing item') ? ?? ? def test_checkout_returns_correct_ balance(self): ? ? self.cart.add_item('Mango', 3, 10) ? ? self.cart.add_item('Orange', 16, 10) ? ?? ? ? self.assertEqual(self.cart. checkout(265), 75, msg='Balance of checkout not correct') ? ? self.assertEqual(self.cart. checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct') ? ?? ? def test_shop_is_instance_of_ shopping_cart(self): ? ? self.assertTrue(isinstance( self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart') ? def test_shop_remove_item_method( self): ? ? for i in range(15): ? ? ? self.shop.remove_item() ? ? self.assertEqual(self.shop. quantity, 85) ______________________________ _________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/ mailman/listinfo/tutor From mats at wichmann.us Thu Mar 9 14:47:24 2017 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 9 Mar 2017 12:47:24 -0700 Subject: [Tutor] Help!! Code ridden with Bugs In-Reply-To: References: <1735435946.3514692.1489066085141.ref@mail.yahoo.com> <1735435946.3514692.1489066085141@mail.yahoo.com> Message-ID: On 03/09/2017 12:32 PM, Joel Goldstick wrote: > On Thu, Mar 9, 2017 at 8:28 AM, Eloka Chima via Tutor wrote: >> I am new to programming but an immersive study in the past few weeks have brought me to speed so I can play around with codes but not really mastered them.My assignment below is ridden with bugs and I've done so much to get rid of them but to no avail. >> Below is the project : >> >> Create a class called ShoppingCart. >> >> Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items. >> >> Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item. >> >> Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly. >> >> If the quantity of an item to be removed exceeds the current quantity of that item in the cart, assume that all entries of that item are to be removed. >> >> Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough". >> >> Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100. >> >> Make sure Shop inherits from ShoppingCart. that is an odd relationship (I realize it's part of the assignment as you've posted it)... a "Shop" is conceptually a bigger thing than a Shopping Cart what with overall inventories, item descriptions as well as an overall financial picture; you'd almost think the shopping cart would be the subclass. >> >> In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one''' >> >> > >> def checkout(self, cash_paid): >> >> self.cash_paid = cash_paid >> >> if self.cash_paid < self.total: >> >> self.total -= self.cash_paid >> >> return self.total >> >> return "Cash paid is not enough" Here you can't return two things, once you return, you are out of the function, there's no chance to return a second time. Perhaps you meant to have the second return be behind an "else:" statement? I think you must not be expected to take this part of the description this literally, because a financial total amount and a text string are different types of objects, while Python's typing system makes it possible to return either, that doesn't make it a good idea in your API - how are you going to describe to users of this function that it might be a totel, but then again it might be an error message? Giving some thought to how to have a consistent return value and still meet the requirements seems a good idea. Have some other thoughts as well... in your Shop derived class (see above), were you expecting the base class (ShoppingCart) initializer to also run? If so, you better call it. From alan.gauld at yahoo.co.uk Thu Mar 9 15:43:12 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 9 Mar 2017 20:43:12 +0000 Subject: [Tutor] Help!! Code ridden with Bugs In-Reply-To: <1735435946.3514692.1489066085141@mail.yahoo.com> References: <1735435946.3514692.1489066085141.ref@mail.yahoo.com> <1735435946.3514692.1489066085141@mail.yahoo.com> Message-ID: On 09/03/17 13:28, Eloka Chima via Tutor wrote: > My assignment below is ridden with bugs So tell us what they are don;t make us guess and don't expect us to run code which is by your own admission faulty! If you get error messages post them, in full. If it runs but misbehaves tell us what happens - formats your hard drive? Destroys your graphics card? prints a wrong value? What? > class ShoppingCart(object): > > def __init__(self): > self.items = {} > self.total = 0 > > def add_item(self,item_name,quantity,price): > self.item_name = item_name > self.quantity = quantity > self.price = price I don;t think you need these as instance variables, you can just use the values in the parameter. > if not self.item_name in self.items: > self.items[self.item_name] = self.quantity > self.total +=self.price So this becomes... if not item_name in self.items: self.items[item_name] = quantity self.total += price > def remove_item(self,item_name,quantity,price): > self.item_name = item_name > self.quantity = quantity > self.price = price Same thing here > for self.item_name in self.items: You probably shouldn't use an instance variable in a for loop, that's likely to cause some confusing conditions as it will remember the loop value after you exit the method. > > if self.item_name in self.items: This will always be true because you are setting the name in the loop above, so you don't need to check it. > del self.items[self.item_name] And for the same reason this will delete all the items because they are all in the list. > self.total -= self.price > if self.quantity > self.items: > self.items = 0 I'm not sure what you think this doing... > if self.cash_paid < self.total: > > self.total -= self.cash_paid > > return self.total > return "Cash paid is not enough" You can't have two returns like this. Well, technically you can, but the second one will never be reached. That's as far as I got. Please re-post with some more specific information about what you think is wrong. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Thu Mar 9 15:45:45 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 9 Mar 2017 20:45:45 +0000 Subject: [Tutor] Help!! Code ridden with Bugs In-Reply-To: <653078988.3995685.1489084955650@mail.yahoo.com> References: <1735435946.3514692.1489066085141.ref@mail.yahoo.com> <1735435946.3514692.1489066085141@mail.yahoo.com> <801832202.3986800.1489084886511@mail.yahoo.com> <653078988.3995685.1489084955650@mail.yahoo.com> Message-ID: On 09/03/17 18:42, Eloka Chima via Tutor wrote: > Is my code okay. > > THERE IS AN ERROR/BUG IN YOUR CODE > Results: Traceback (most recent call last): File "python/nose2/bin/nose2", line 8, Evidently not. But the error messages are unreadable, please send in plain text. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Thu Mar 9 18:58:49 2017 From: akleider at sonic.net (Alex Kleider) Date: Thu, 09 Mar 2017 15:58:49 -0800 Subject: [Tutor] Lists of duplicates In-Reply-To: <20170309140726.GR5689@ando.pearwood.info> References: <2ec7b1ebccff5a0eac17714cab23ae36@sonic.net> <20170309140726.GR5689@ando.pearwood.info> Message-ID: On 2017-03-09 06:07, Steven D'Aprano wrote: > On Wed, Mar 08, 2017 at 08:29:19PM -0800, Alex Kleider wrote: > >> Things like this can usually be broken down into their component parts >> but I've been unsuccessful doing so: >> >> def f(lst): >> res = {} >> for item in lst: >> method_res = res.setdefault(item, []) >> res.method_res.append(item) >> # res.setdefault(item,[]).append(item) >> return list(res.values()) >> res.method_res.append(item) >> >> AttributeError: 'dict' object has no attribute 'method_res' >> >> Python must be doing some trickery behind the scenes. > > Why do you say that? I'm not sure what result you expected, or what you > are trying to do, but you have: > > res # a dict > res.method_res > > No surprises that this fails with AttributeError. Dicts do not have an > attribute or method called "method_res". > > Perhaps you meant to write: > > # not this > # res.method_res.append( ... ) > > # this instead > method_res.append( ... ) > > > although part of the confusion is that "method_res" is a poorly chosen > name. It isn't a method, it is a list. Thanks again, Steven. I confess to having intended to write res.method_res.append(... but your response made me realize that because lists are mutable it all works without the res. prefix. I chose method_res to refer to the fact that it is the result of a method call. A poor choice I admit. From chima_eloka at yahoo.com Fri Mar 10 05:50:17 2017 From: chima_eloka at yahoo.com (Eloka Chima) Date: Fri, 10 Mar 2017 10:50:17 +0000 (UTC) Subject: [Tutor] Tutor Digest, Vol 157, Issue 24 In-Reply-To: References: Message-ID: <164941459.4648023.1489143017686@mail.yahoo.com> Thank you so much. Your guidance have been helpful, the bugs have been gotten rid of after I reviewed the ?code. But 3 out of 6 of the test is correct, the other 3 is incorrect. Take a look at it and tell me where I went wrong. ? >> Below is my new code: class ShoppingCart(object):? def __init__(self):? ? self.total = 0? ? self.items = {}? def add_item(self, item_name, quantity, price):? ? for item_name in self.items:? ? ? if not item_name in self.items:? ? ? ? self.items["item_name"] = quantity? ? ? ? self.total += price? ? ? ? return self.total? ? return self.items? def remove_item(self, item_name, quantity, price):? ? for item_name in self.items:? ? ? if item_name in self.items:? ? ? ? del self.items["item_name"]? ? ? ? self.total -= price? ? ? else:? ? ? ? if quantity > self.items[quantity]:? ? ? ? ? self.items = 0? ? return self.items? def checkout(self, cash_paid):? ? if cash_paid < self.total :? ? ? self.total -= cash_paid? ? ? return "Cash paid not enough"class Shop(ShoppingCart):? def __init__(self):? ? self.quantity = 100? def remove_item(self):? ? self.quantity -=1? ? return self.quantity >> This is the test for the program: import unittest class ShoppingCartTestCases(unittest.TestCase):? def setUp(self):? ? self.cart = ShoppingCart()? ? self.shop = Shop()? ??? def test_cart_property_initialization(self):? ? self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct')? ? self.assertIsInstance(self.cart.items, dict, msg='Items is not a dictionary')? ??? def test_add_item(self):? ? self.cart.add_item('Mango', 3, 10)? ??? ? self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items')? ? self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items not correct after adding item')? ??? def test_remove_item(self):? ? self.cart.add_item('Mango', 3, 10)? ? self.cart.remove_item('Mango', 2, 10)? ??? ? self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item')? ? self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item')? ??? def test_checkout_returns_correct_balance(self):? ? self.cart.add_item('Mango', 3, 10)? ? self.cart.add_item('Orange', 16, 10)? ??? ? self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct')? ? self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct')? ??? def test_shop_is_instance_of_shopping_cart(self):? ? self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart') ? def test_shop_remove_item_method(self):? ? for i in range(15):? ? ? self.shop.remove_item() ? ? self.assertEqual(self.shop.quantity, 85) >> I get this test result after running it: 1 .? test_add_itemFailure in line 20, in test_add_item self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items') AssertionError: Cart total not correct after adding items2 .? test_checkout_returns_correct_balanceFailure in line 34, in test_checkout_returns_correct_balance self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct') AssertionError: Balance of checkout not correct3 .? test_remove_itemFailure in line 27, in test_remove_item self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item') AssertionError: Cart total not correct after removing item. ? ?? On Thursday, 9 March 2017, 21:39, "tutor-request at python.org" wrote: ----- Forwarded Message ----- Send Tutor mailing list submissions to ??? tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit ??? https://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to ??? tutor-request at python.org You can reach the person managing the list at ??? tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: ? 1. Re: Help!! Code ridden with Bugs (Joel Goldstick) ? 2. Re: Help!! Code ridden with Bugs (Sri Kavi) ? 3. Re: Help!! Code ridden with Bugs (Eloka Chima) On Thu, Mar 9, 2017 at 8:28 AM, Eloka Chima via Tutor wrote: > I am new to programming but an immersive? study in the past few weeks have brought me to speed so I can play around with codes but not really mastered them.My assignment below is ridden with bugs and I've done so much to get rid of them but to no avail. > Below is the project : > > Create a class called ShoppingCart. > > Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items. > > Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item. > > Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly. > > If the quantity of an item to be removed exceeds the current quantity of that item in the cart, assume that all entries of that item are to be removed. > > Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough". > > Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100. > > Make sure Shop inherits from ShoppingCart. > > In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one''' > > > > > And below here is my code: > > class ShoppingCart(object): > >? def __init__(self): > >? ? self.items = {} > >? ? self.total = 0 > >? def add_item(self,item_name,quantity,price): > >? ? self.item_name = item_name > >? ? self.quantity = quantity > >? ? self.price = price > >? ? ? if not self.item_name in self.items: > >? ? ? ? self.items[self.item_name] = self.quantity > >? ? ? ? self.total +=self.price > >? def remove_item(self,item_name,quantity,price): > >? ? self.item_name = item_name > >? ? self.quantity = quantity > >? ? self.price = price > >? ? ? for self.item_name in self.items: > >? ? ? ? if self.item_name in self.items: > >? ? ? ? ? del self.items[self.item_name] > >? ? ? ? ? self.total -= self.price > >? ? ? ? ? if self.quantity > self.items: > >? ? ? ? ? ? self.items = 0 > >? ? ? return self.items > >? def checkout(self, cash_paid): > >? ? self.cash_paid = cash_paid > >? ? if self.cash_paid < self.total: > >? ? ? self.total -= self.cash_paid > >? ? ? return self.total > >? ? ? return "Cash paid is not enough" > > class Shop(ShoppingCart): > >? def __init__(self): > >? ? self.quantity = 100 > >? def remove_item(self): > >? ? self.quantity -= 1 > >? ? return self.quantity > > > > > Below is the tests: > > > > > import unittest > > > > > class ShoppingCartTestCases(unittest.TestCase): > >? def setUp(self): > >? ? self.cart = ShoppingCart() > >? ? self.shop = Shop() > > > >? def test_cart_property_initialization(self): > >? ? self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct') > >? ? self.assertIsInstance(self.cart.items, dict, msg='Items is not a dictionary') > > > >? def test_add_item(self): > >? ? self.cart.add_item('Mango', 3, 10) > > > >? ? self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items') > >? ? self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items not correct after adding item') > > > >? def test_remove_item(self): > >? ? self.cart.add_item('Mango', 3, 10) > >? ? self.cart.remove_item('Mango', 2, 10) > > > >? ? self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item') > >? ? self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item') > > > >? def test_checkout_returns_correct_balance(self): > >? ? self.cart.add_item('Mango', 3, 10) > >? ? self.cart.add_item('Orange', 16, 10) > > > >? ? self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct') > >? ? self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct') > > > >? def test_shop_is_instance_of_shopping_cart(self): > >? ? self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart') > > > > >? def test_shop_remove_item_method(self): > >? ? for i in range(15): > >? ? ? self.shop.remove_item() > > > > > > >? ? self.assertEqual(self.shop.quantity, 85) Welcome. Two things:? First, format your code correctly, it is double spaced. Second, what exactly is wrong with your code?? If it runs, but outputs the wrong values, point that out.? If it fails to run, copy and paste the complete traceback so that others can identify where you have gone wrong. > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays def checkout(self, cash_paid): ? ? self.cash_paid = cash_paid ? ? if self.cash_paid < self.total: ? ? ? self.total -= self.cash_paid ? ? ? return self.total ? ? ? return "Cash paid is not enough" You cannot return two values. Sri On Thu, Mar 9, 2017 at 6:58 PM, Eloka Chima via Tutor wrote: > I am new to programming but an immersive? study in the past few weeks have > brought me to speed so I can play around with codes but not really mastered > them.My assignment below is ridden with bugs and I've done so much to get > rid of them but to no avail. > Below is the project : > > Create a class called ShoppingCart. > > Create a constructor that takes no arguments and sets the total attribute > to zero, and initializes an empty dict attribute named items. > > Create a method add_item that requires item_name, quantity and price > arguments. This method should add the cost of the added items to the > current value of total. It should also add an entry to the items dict such > that the key is the item_name and the value is the quantity of the item. > > Create a method remove_item that requires similar arguments as add_item. > It should remove items that have been added to the shopping cart and are > not required. This method should deduct the cost of the removed items from > the current total and also update the items dict accordingly. > > If the quantity of an item to be removed exceeds the current quantity of > that item in the cart, assume that all entries of that item are to be > removed. > > Create a method checkout that takes in cash_paid and returns the value of > balance from the payment. If cash_paid is not enough to cover the total, > return "Cash paid not enough". > > Create a class called Shop that has a constructor which takes no arguments > and initializes an attribute called quantity at 100. > > Make sure Shop inherits from ShoppingCart. > > In the Shop class, override the remove_item method, such that calling > Shop's remove_item with no arguments decrements quantity by one''' > > > > > And below here is my code: > > class ShoppingCart(object): > >? def __init__(self): > >? ? self.items = {} > >? ? self.total = 0 > >? def add_item(self,item_name,quantity,price): > >? ? self.item_name = item_name > >? ? self.quantity = quantity > >? ? self.price = price > >? ? ? if not self.item_name in self.items: > >? ? ? ? self.items[self.item_name] = self.quantity > >? ? ? ? self.total +=self.price > >? def remove_item(self,item_name,quantity,price): > >? ? self.item_name = item_name > >? ? self.quantity = quantity > >? ? self.price = price > >? ? ? for self.item_name in self.items: > >? ? ? ? if self.item_name in self.items: > >? ? ? ? ? del self.items[self.item_name] > >? ? ? ? ? self.total -= self.price > >? ? ? ? ? if self.quantity > self.items: > >? ? ? ? ? ? self.items = 0 > >? ? ? return self.items > >? def checkout(self, cash_paid): > >? ? self.cash_paid = cash_paid > >? ? if self.cash_paid < self.total: > >? ? ? self.total -= self.cash_paid > >? ? ? return self.total > >? ? ? return "Cash paid is not enough" > > class Shop(ShoppingCart): > >? def __init__(self): > >? ? self.quantity = 100 > >? def remove_item(self): > >? ? self.quantity -= 1 > >? ? return self.quantity > > > > > Below is the tests: > > > > > import unittest > > > > > class ShoppingCartTestCases(unittest.TestCase): > >? def setUp(self): > >? ? self.cart = ShoppingCart() > >? ? self.shop = Shop() > > > >? def test_cart_property_initialization(self): > >? ? self.assertEqual(self.cart.total, 0, msg='Initial value of total not > correct') > >? ? self.assertIsInstance(self.cart.items, dict, msg='Items is not a > dictionary') > > > >? def test_add_item(self): > >? ? self.cart.add_item('Mango', 3, 10) > > > >? ? self.assertEqual(self.cart.total, 30, msg='Cart total not correct > after adding items') > >? ? self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items > not correct after adding item') > > > >? def test_remove_item(self): > >? ? self.cart.add_item('Mango', 3, 10) > >? ? self.cart.remove_item('Mango', 2, 10) > > > >? ? self.assertEqual(self.cart.total, 10, msg='Cart total not correct > after removing item') > >? ? self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items > not correct after removing item') > > > >? def test_checkout_returns_correct_balance(self): > >? ? self.cart.add_item('Mango', 3, 10) > >? ? self.cart.add_item('Orange', 16, 10) > > > >? ? self.assertEqual(self.cart.checkout(265), 75, msg='Balance of > checkout not correct') > >? ? self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', > msg='Balance of checkout not correct') > > > >? def test_shop_is_instance_of_shopping_cart(self): > >? ? self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not > a subclass of ShoppingCart') > > > > >? def test_shop_remove_item_method(self): > >? ? for i in range(15): > >? ? ? self.shop.remove_item() > > > > > > >? ? self.assertEqual(self.shop.quantity, 85) > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Your Code Solution Has Errors THERE IS AN ERROR/BUG IN YOUR CODE Results:?Traceback (most recent call last): File "python/nose2/bin/nose2", line 8, in? discover() File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 300, in discover return main(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 100, in __init__ super(PluggableTestProgram, self).__init__(**kw) File "/usr/lib/python2.7/unittest/main.py", line 94, in __init__ self.parseArgs(argv) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 133, in parseArgs self.createTests() File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/main.py", line 258, in createTests self.testNames, self.module) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/loader.py", line 67, in loadTestsFromNames for name in event.names] File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/loader.py", line 82, in loadTestsFromName result = self.session.hooks.loadTestsFromName(event) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/events.py", line 224, in __call__ result = getattr(plugin, self.method)(event) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/plugins/loader/testclasses.py", line 119, in loadTestsFromName result = util.test_from_name(name, module) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/util.py", line 106, in test_from_name parent, obj = object_from_name(name, module) File "/usr/local/lib/python2.7/dist-packages/nose2-0.5.0-py2.7.egg/nose2/util.py", line 117, in object_from_name module = __import__('.'.join(parts_copy)) File "/home/ubuntu/Applications/andelabs-server/tmp/58b15152d171bb1a00a61531-586ba236d394751500fff7e4-test.py", line 4, in? from tmp.andelabs_58b15152d171bb1a00a61531_586ba236d394751500fff7e4 import * File "/home/ubuntu/Applications/andelabs-server/tmp/andelabs_58b15152d171bb1a00a61531_586ba236d394751500fff7e4.py", line 17 if not self.item_name in self.items: ^IndentationError: unexpected indentI get this error when I run the code. After editing the code I sent.?Thanks. Sent from Yahoo Mail on Android ? On Thu, 9 Mar 2017 at 6:26 pm, Sri Kavi wrote:? ?def checkout(self, cash_paid): ? ? self.cash_paid = cash_paid ? ? if self.cash_paid < self.total: ? ? ? self.total -= self.cash_paid ? ? ? return self.total ? ? ? return "Cash paid is not enough" You cannot return two values. Sri On Thu, Mar 9, 2017 at 6:58 PM, Eloka Chima via Tutor wrote: I am new to programming but an immersive ?study in the past few weeks have brought me to speed so I can play around with codes but not really mastered them.My assignment below is ridden with bugs and I've done so much to get rid of them but to no avail. Below is the project : Create a class called ShoppingCart. Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items. Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item. Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly. If the quantity of an item to be removed exceeds the current quantity?of that item in the cart, assume that all entries of that item are to be removed. Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough". Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100. Make sure Shop inherits from ShoppingCart. In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one''' And below here is my code: class ShoppingCart(object): ? def __init__(self): ? ? self.items = {} ? ? self.total = 0 ? def add_item(self,item_name, quantity,price): ? ? self.item_name = item_name ? ? self.quantity = quantity ? ? self.price = price? ? ? ? if not self.item_name in self.items: ? ? ? ? self.items[self.item_name] = self.quantity ? ? ? ? self.total +=self.price ? def remove_item(self,item_name, quantity,price): ? ? self.item_name = item_name ? ? self.quantity = quantity ? ? self.price = price ? ? ? for self.item_name in self.items: ? ? ? ? if self.item_name in self.items: ? ? ? ? ? del self.items[self.item_name] ? ? ? ? ? self.total -= self.price ? ? ? ? ? if self.quantity > self.items: ? ? ? ? ? ? self.items = 0 ? ? ? return self.items ? def checkout(self, cash_paid): ? ? self.cash_paid = cash_paid ? ? if self.cash_paid < self.total: ? ? ? self.total -= self.cash_paid ? ? ? return self.total ? ? ? return "Cash paid is not enough" class Shop(ShoppingCart): ? def __init__(self): ? ? self.quantity = 100 ? def remove_item(self): ? ? self.quantity -= 1 ? ? return self.quantity? Below is the tests: import unittest class ShoppingCartTestCases( unittest.TestCase): ? def setUp(self): ? ? self.cart = ShoppingCart() ? ? self.shop = Shop() ? ?? ? def test_cart_property_ initialization(self): ? ? self.assertEqual(self.cart. total, 0, msg='Initial value of total not correct') ? ? self.assertIsInstance(self. cart.items, dict, msg='Items is not a dictionary') ? ?? ? def test_add_item(self): ? ? self.cart.add_item('Mango', 3, 10) ? ?? ? ? self.assertEqual(self.cart. total, 30, msg='Cart total not correct after adding items') ? ? self.assertEqual(self.cart. items['Mango'], 3, msg='Quantity of items not correct after adding item') ? ?? ? def test_remove_item(self): ? ? self.cart.add_item('Mango', 3, 10) ? ? self.cart.remove_item('Mango', 2, 10) ? ?? ? ? self.assertEqual(self.cart. total, 10, msg='Cart total not correct after removing item') ? ? self.assertEqual(self.cart. items['Mango'], 1, msg='Quantity of items not correct after removing item') ? ?? ? def test_checkout_returns_correct_ balance(self): ? ? self.cart.add_item('Mango', 3, 10) ? ? self.cart.add_item('Orange', 16, 10) ? ?? ? ? self.assertEqual(self.cart. checkout(265), 75, msg='Balance of checkout not correct') ? ? self.assertEqual(self.cart. checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct') ? ?? ? def test_shop_is_instance_of_ shopping_cart(self): ? ? self.assertTrue(isinstance( self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart') ? def test_shop_remove_item_method( self): ? ? for i in range(15): ? ? ? self.shop.remove_item() ? ? self.assertEqual(self.shop. quantity, 85) ______________________________ _________________ 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 https://mail.python.org/mailman/listinfo/tutor From leamhall at gmail.com Fri Mar 10 07:38:00 2017 From: leamhall at gmail.com (leam hall) Date: Fri, 10 Mar 2017 07:38:00 -0500 Subject: [Tutor] Socket error in class, part the second Message-ID: y'all, Thanks for the explanations! Sorry for the delay in responding, it's been a rough year these past couple weeks. As noted, the fix was to put the "import socket" above the class declaration. What confuses me is that in the calling program I'm importing the class: from mysocket import mysocket In mysocket.py the "import socket" is above the class declaration. This works. I would have thought it would fail as the import statement only imports the class, not the entire module. However, I'm wrong. Still learning. Also, yes, I re-typed everything which is why the errors crept in. The machine I have to run python on precludes cut and paste to the machine I e-mail on. The original code was swiped from Gordan McMillian's tutorial on Python.org. https://docs.python.org/2/howto/sockets.html I'm just trying to make things modular. Again, thanks! Leam From alan.gauld at yahoo.co.uk Fri Mar 10 12:29:11 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 10 Mar 2017 17:29:11 +0000 Subject: [Tutor] Tutor Digest, Vol 157, Issue 24 In-Reply-To: <164941459.4648023.1489143017686@mail.yahoo.com> References: <164941459.4648023.1489143017686@mail.yahoo.com> Message-ID: On 10/03/17 10:50, Eloka Chima via Tutor wrote: Please post in plain text. Your email is unreadable... And please don't reply to the digest, and if you must, then at least delete the irrelevant bits. We've all seen these messages already and some people pay by the byte. > Thank you so much. Your guidance have been helpful, the bugs have been gotten rid of after I reviewed the code. But 3 out of 6 of the test is correct, the other 3 is incorrect. Take a look at it and tell me where I went wrong. >>> Below is my new code: > class ShoppingCart(object): def __init__(self): self.total = 0 self.items = {} def add_item(self, item_name, quantity, price): for item_name in self.items: if not item_name in self.items: self.items["item_name"] = quantity self.total += price return self.total return self.items def remove_item(self, item_name, quantity, price): for item_name in self.items: if item_name in self.items: del self.items["item_name"] self.total -= price else: if quantity > self.items[quantity]: self.items = 0 return self.items def checkout(self, cash_paid): if cash_paid < self.total : self.total -= cash_paid return "Cash paid not enough"class Shop(ShoppingCart): def __init__(self): self.quantity = 100 def remove_item(self): self.quantity -=1 return self.quantity >>> This is the test for the program: > import unittest > class ShoppingCartTestCases(unittest.TestCase): def setUp(self): self.cart = ShoppingCart() self.shop = Shop() def test_cart_property_initialization(self): self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct') self.assertIsInstance(self.cart.items, dict, msg='Items is not a dictionary') def test_add_item(self): self.cart.add_item('Mango', 3, 10) self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items') self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items not correct after adding item') def test_remove_item(self): self.cart.add_item('Mango', 3, 10) self.cart.remove_item('Mango', 2, 10) self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item') self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item') def test_checkout_returns_correct_balance(self): self.cart.add_item('Mango', 3, 10) self.cart.add_item('Orange', 16, 10) self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct') self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct') def test_shop_is_instance_of_shopping_cart(self): self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart') > def test_shop_remove_item_method(self): for i in range(15): self.shop.remove_item() > self.assertEqual(self.shop.quantity, 85) > >>> I get this test result after running it: > 1 . test_add_itemFailure in line 20, in test_add_item self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items') AssertionError: Cart total not correct after adding items2 . test_checkout_returns_correct_balanceFailure in line 34, in test_checkout_returns_correct_balance self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct') AssertionError: Balance of checkout not correct3 . test_remove_itemFailure in line 27, in test_remove_item self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item') AssertionError: Cart total not correct after removing item. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 10 14:11:49 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 10 Mar 2017 19:11:49 +0000 Subject: [Tutor] Socket error in class, part the second In-Reply-To: References: Message-ID: On 10/03/17 12:38, leam hall wrote: > As noted, the fix was to put the "import socket" above the class > declaration. What confuses me is that in the calling program I'm importing > the class: > > from mysocket import mysocket > > In mysocket.py the "import socket" is above the class declaration. This > works. I would have thought it would fail as the import statement only > imports the class, not the entire module. Remember that you are importing the *name* not the actual class code. The class object code remains in the mysocket module where it can still access the socket name that it, in turn, imported. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dbosah at buffalo.edu Fri Mar 10 18:12:52 2017 From: dbosah at buffalo.edu (Daniel Bosah) Date: Fri, 10 Mar 2017 18:12:52 -0500 Subject: [Tutor] Sklearn Message-ID: Can someone explain sklearns to me? I'm a novice at Python, and I would like to use machine learning in my coding. But aren't there libraries like matplotlib I can already use? Why use sklearns? From alan.gauld at yahoo.co.uk Fri Mar 10 19:23:32 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 11 Mar 2017 00:23:32 +0000 Subject: [Tutor] Sklearn In-Reply-To: References: Message-ID: On 10/03/17 23:12, Daniel Bosah wrote: > Can someone explain sklearns to me? Not me, I've never heard of it till now. > I'm a novice at Python, and I would > like to use machine learning in my coding. Why? What do you know about machine learning? What other platforms support it? > But aren't there libraries like > matplotlib I can already use? Probably, but what do you know about matplotlib? How does it relate to machine learning? > Why use sklearns? Because it does what you want to do. What do you want to do? Does sklearns do that? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 10 20:13:38 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 11 Mar 2017 01:13:38 +0000 Subject: [Tutor] Fwd: Re: Sklearn In-Reply-To: References: Message-ID: <19f2c7f3-3f4b-232a-46fd-ae6da8646778@yahoo.co.uk> Forwarding to list... Please use ReplyAll or ReplyList when responding to the tutor list. ------------------ > I would like to carry statistical analyses of populations . > I've been that it's the best package for that sort of thing in Python, > but I'm new to machine learning, so I'm not quite sure. Can you describe what you mean by "machine learning"? This is one of those current buzzwords that has almost as many meanings as there are people using it. If you can give a practical example of the kind of thing you can see yourself using this stuff for then we can advise on whether a library might be suitable or not. And if we don't know (we are focused on the standard library not 3rd party add-ons) where you might get a better response. > Also, I don't want to bother learning R. That's a separate issue, but R is almost a defacto standard in the world of statistics so if you are seriously involved there you probably should make the effort. Alan G On 10/03/17 23:12, Daniel Bosah wrote: > Can someone explain sklearns to me? Not me, I've never heard of it till now. > I'm a novice at Python, and I would > like to use machine learning in my coding. Why? What do you know about machine learning? What other platforms support it? > But aren't there libraries like > matplotlib I can already use? Probably, but what do you know about matplotlib? How does it relate to machine learning? > Why use sklearns? Because it does what you want to do. What do you want to do? Does sklearns do that? From alan.gauld at yahoo.co.uk Sat Mar 11 02:42:09 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 11 Mar 2017 07:42:09 +0000 Subject: [Tutor] Fwd: RE: Fwd: Re: Sklearn In-Reply-To: <6t28u661i79y8n0xm476m7d9.1489201206677@email.android.com> References: <6t28u661i79y8n0xm476m7d9.1489201206677@email.android.com> Message-ID: Forwarding to list... ----------------------- Statistical analysis of datasets. I want libraries that contain algorithms to check for relationships within a dataset. For example, I want to parse through a SES dataset to see any possible connections between student achievement and socioeconomic standing, and correlate that to neighborhood wealth. And I know I should learn R, but I'm also learning Python as my primary language now, and R isn't really a programming language as Python, Java, C++, etc., so I'm not placing it as a primary language to learn at the moment. -------- Original message -------- From: Alan Gauld via Tutor Date: 3/10/17 8:13 PM (GMT-05:00) To: tutor Subject: [Tutor] Fwd: Re: Sklearn Forwarding to list... Please use ReplyAll or ReplyList when responding to the tutor list. ------------------ > I would like to carry statistical analyses of populations . > I've been that it's the best package for that sort of thing in Python, > but I'm new to machine learning, so I'm not quite sure. Can you describe what you mean by "machine learning"? This is one of those current buzzwords that has almost as many meanings as there are people using it. If you can give a practical example of the kind of thing you can see yourself using this stuff for then we can advise on whether a library might be suitable or not. And if we don't know (we are focused on the standard library not 3rd party add-ons) where you might get a better response. > Also, I don't want to bother learning R. That's a separate issue, but R is almost a defacto standard in the world of statistics so if you are seriously involved there you probably should make the effort. Alan G On 10/03/17 23:12, Daniel Bosah wrote: > Can someone explain sklearns to me? Not me, I've never heard of it till now. > I'm a novice at Python, and I would > like to use machine learning in my coding. Why? What do you know about machine learning? What other platforms support it? > But aren't there libraries like > matplotlib I can already use? Probably, but what do you know about matplotlib? How does it relate to machine learning? > Why use sklearns? Because it does what you want to do. What do you want to do? Does sklearns do that? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From matt.williams45.mw at gmail.com Sat Mar 11 08:03:07 2017 From: matt.williams45.mw at gmail.com (Matt Williams) Date: Sat, 11 Mar 2017 13:03:07 +0000 Subject: [Tutor] Fwd: RE: Fwd: Re: Sklearn In-Reply-To: References: <6t28u661i79y8n0xm476m7d9.1489201206677@email.android.com> Message-ID: Having done similar, the options are (depending on the dataset): 1: Python to read, clean and classify data, then R to do the analysis (e.g. regression analysis) 2: Python to read, clean and classify data, and python for the analysis 3: All in R If you want to use Python for the analysis, most people would probably use Pandas for the data cleaning and SciPy for the stats. However, there are alternatives. There is a tutorial that describes almost exactly the same problem as yours here, using Pandas and some other packages: http://blog.yhat.com/posts/logistic-regression-and-python.html HTH, Matt From alan.gauld at yahoo.co.uk Sat Mar 11 14:58:16 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 11 Mar 2017 19:58:16 +0000 Subject: [Tutor] Fwd: RE: Fwd: Re: Sklearn In-Reply-To: References: <6t28u661i79y8n0xm476m7d9.1489201206677@email.android.com> Message-ID: > I want libraries that contain algorithms to check for relationships > within a dataset. For example, I want to parse through a SES dataset to > see any possible connections between student achievement and > socioeconomic standing, and correlate that to neighborhood wealth. Ok, With that background I now return to your original question: > Can someone explain sklearns to me? I'm a novice at Python, > and I would like to use machine learning in my coding. > But aren't there libraries like matplotlib I can already > use? Why use sklearns? Starting at the end first... matplotlib is a plotting library, you give it some raw data and it plots a nice graphical image in any style you choose. Think of it like a programmatic version of the plotting feature in a spreadsheet. sklearn doesn't do that, it will generate the data for you to p[lot with matplotlib if you wish. (At least thats how I interpret the information on the sklearn web page.) So its not either/or - you need both. sklearn, as the sk in the name suggests, is part of SciKit which is a set of add-ons to SciPy, which includes matplotlib. What sklearn brings to the picture, again based on a very quick skim through the introductory material - is a framework for doing machine learning. If you just want to play with its standard datasets then its very easy to use. If you want to use it on your own data it gets harder - you need to format your data into the shape sklearn expects. You then need to specify/select or write the algorithms needed for sklearn to do its learning. Don't underestimate how much preparatory work you will need to do to feed the engine. Its not magic. For what you want, Pandas or Rpy might be able to do it just as easily - but since you don't seem to already know either of those then sklearn would seem to be a reasonable alternative/complementary choice. But if you don't know basic Python well that might be a bigger challenge. Given my level of ignorance about both sklearn and your problem, domain I can't say more than that. I would suggest asking again on the SciPy forum since you are likely to find a lot more people there who have experience of both - and alternatives like Pandas and Rpy. > And I know I should learn R, but I'm also learning > Python as my primary language now, and R isn't > really a programming language as Python, Java, It's not quite as general - I wouldn't try writing games or GUIs or web apps in R. But you can write fully self-contained applications in it if you wish. And for traditional statistical number crunching it's better than either Python or Java. Fortunately you can use R from either language via libraries. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From fal at libero.it Sun Mar 12 18:48:35 2017 From: fal at libero.it (Francesco Loffredo) Date: Sun, 12 Mar 2017 23:48:35 +0100 Subject: [Tutor] Where am I mistaken? (exec not working as I expect) Message-ID: <20170312234835.6566a677@acerfal-roma> Hello everybody! I'm stuck in the effort to access some data fields in a LibreOffice Base form from a Python macro. I did only find a way to access the current document, but that's all. Armed with that, and hoping to find some field names, I wrote a small routine to inspect the types of all elements in that document, and I stumbled in a strange behaviour in the exec() function: it seems that exec() only works if called from the interactive interpreter, while it doesn't if called inside a program. Why? (by the way, if somebody knows how to read currently displayed data from fields in a LibreOffice Base form and put it in some other field on the same form, using a Python macro, I would be very happy...) Francesco Here's my code: (Python 3.5.3 on Linux) import inspect, collections def esplora(xModel): i = 0 questi = [] for x in dir(xModel): qqq = "Non Modif" what = "Nothing" try: what = "Attr?" exec("qqq = inspect.getmembers(xModel.%s)" % x) what = "Attr!!!" if qqq == "Non Modif": try: what = "Type?" exec("qqq = type(xModel.%s)" % x) what = "Type!!!" except: what = "Except2" except: what = "Except1" questi.append(str((x, qqq, what))) i += 1 questi.append(("Totale elementi: %s" % i, )) print("\n".join(questi)) Example data: >>> class prova(object): ... def __init__(self): ... self.abc = "ABC" ... self.num = 123 ... self.tup = ("abc", 321) ... >>> lui = prova() Applied the function to the sample data: incorrect behaviour >>> esplora(lui) ('__class__', 'Non Modif', 'Type!!!') ('__delattr__', 'Non Modif', 'Type!!!') ('__dict__', 'Non Modif', 'Type!!!') ('__dir__', 'Non Modif', 'Type!!!') ('__doc__', 'Non Modif', 'Type!!!') ('__eq__', 'Non Modif', 'Type!!!') ('__format__', 'Non Modif', 'Type!!!') ('__ge__', 'Non Modif', 'Type!!!') ('__getattribute__', 'Non Modif', 'Type!!!') ('__gt__', 'Non Modif', 'Type!!!') ('__hash__', 'Non Modif', 'Type!!!') ('__init__', 'Non Modif', 'Type!!!') ('__le__', 'Non Modif', 'Type!!!') ('__lt__', 'Non Modif', 'Type!!!') ('__module__', 'Non Modif', 'Type!!!') ('__ne__', 'Non Modif', 'Type!!!') ('__new__', 'Non Modif', 'Type!!!') ('__reduce__', 'Non Modif', 'Type!!!') ('__reduce_ex__', 'Non Modif', 'Type!!!') ('__repr__', 'Non Modif', 'Type!!!') ('__setattr__', 'Non Modif', 'Type!!!') ('__sizeof__', 'Non Modif', 'Type!!!') ('__str__', 'Non Modif', 'Type!!!') ('__subclasshook__', 'Non Modif', 'Type!!!') ('__weakref__', 'Non Modif', 'Type!!!') ('abc', 'Non Modif', 'Type!!!') ('num', 'Non Modif', 'Type!!!') ('tup', 'Non Modif', 'Type!!!') Totale elementi: 28 >>> type(lui.tup) >>> dir(lui) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'abc', 'num', 'tup'] >>> Same thing called directly: correct behaviour >>> for x in dir(lui): ... exec("y = type(lui.%s)" % x) ... print((x, y)) ... ('__class__', ) ('__delattr__', ) ('__dict__', ) ('__dir__', ) ('__doc__', ) ('__eq__', ) ('__format__', ) ('__ge__', ) ('__getattribute__', ) ('__gt__', ) ('__hash__', ) ('__init__', ) ('__le__', ) ('__lt__', ) ('__module__', ) ('__ne__', ) ('__new__', ) ('__reduce__', ) ('__reduce_ex__', ) ('__repr__', ) ('__setattr__', ) ('__sizeof__', ) ('__str__', ) ('__subclasshook__', ) ('__weakref__', ) ('abc', ) ('num', ) ('tup', ) >>> From tonifuente at yahoo.co.uk Mon Mar 13 11:54:57 2017 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Mon, 13 Mar 2017 15:54:57 +0000 Subject: [Tutor] While until the end of a list Message-ID: <20170313155457.GA1288@macarra> Hi, I've got this script that goes through an httpd conf file, and gets the related bits of it for a site, and writes a new config with values that I am interested. The problem is that it finds the first chunk and returns it, but I need to go to the end of all chunks list, because there are also some chunks related to the same site that I need to collect (virtualhost *:80 and virtualhost:443). I was I was thinking in a while loop in the find_chunk function that will go through all chunks and return the chunks that site is on, but I don't know how to construct it. Thank you in advance for any suggestion. Toni. cat sites_user: foo.com bar [...] #!/usr/bin/python import sys, re, os token = '\n' chunks = [] current_chunk = [] def find_chunk(site, chunks): for chunk in chunks: if any(site in line for line in chunk): return chunk return None # no appropriate chunk found def new_chunk(chunk, user, site): config = [] for item in chunk: if "DocumentRoot" in item: root_dir = item.rsplit('/', 1)[-1] root_dir = root_dir.strip('\n') config.append(re.sub('/home/httpd/vhosts/[a-zA-Z\d-]{,63}(\.[a-zA-Z\d-]{,63})*/[a-zA-Z\d-]{,63}', '/websites/' + user.rstrip() + '/' + site + '/' + root_dir, item)) elif re.match('', item) is not None: config.append(re.sub('', '', item)) elif re.match('', item) is not None: config.append(re.sub('', '', item)) elif "" in item: config.append(item) elif "Log" in item: config.append(re.sub('/home/httpd/vhosts/[a-zA-Z\d-]{,63}(\.[a-zA-Z\d-]{,63})*/statistics/logs/*', '/websites/' + user.rstrip() + '/logs/' + site + '/', item)) elif "cgi-bin" in item: config.append(re.sub('/home/httpd/vhosts/[a-zA-Z\d-]{,63}(\.[a-zA-Z\d-]{,63})*/cgi-bin/', '/websites/' + user.rstrip() + '/cgi-bin/' + site + '/', item)) elif "ServerAlias" in item: config.append(item) elif "ServerAdmin" in item: config.append(item) else: print "DO NOTHING" return config #for line in open('work/total.configs.txt'): with open('work/total.configs.txt') as openfileobject: for line in openfileobject: if line.startswith(token) and current_chunk: # if line starts with token and the current chunk is not empty chunks.append(current_chunk[:]) # add not empty chunk to chunks current_chunk = [] # make current chunk blank # just append a line to the current chunk on each iteration current_chunk.append(line) chunks.append(current_chunk) # append the last chunk outside the loop for line in open("sites_user.txt"): site, user = line.split(' ', 1) chunk = find_chunk(site, chunks) #chunk.pop(0) print site if chunk is not None: #chunk.pop(0) new_config = new_chunk(chunk, user, site) with open("/tmp/afm/etc/httpd/conf.d/vhosts.inc/%s.conf" % site, "a") as cfile: cfile.write("".join(new_config)) with open("/tmp/afm/etc/httpd/conf.d/vhosts.conf", "a") as vfile: vfile.write("Include conf.d/vhosts.inc/%s.conf\n" % site) else: print >> sys.stderr, "no configuration for site", site EXAMPLE of total.configs.txt: ... ServerName foo.com:443 ServerAlias www.foo.com UseCanonicalName Off SuexecUserGroup katz psacln ServerAdmin hostmaster at foo.com DocumentRoot /home/httpd/vhosts/foo.com/httpsdocs CustomLog /home/httpd/vhosts/foo.com/statistics/logs/access_ssl_log combined ErrorLog /home/httpd/vhosts/foo.com/statistics/logs/error_ssl_log UserDir /home/httpd/vhosts/foo.com/web_users ScriptAlias /cgi-bin/ /home/httpd/vhosts/foo.com/cgi-bin/ Alias /webstat /home/httpd/vhosts/foo.com/statistics/webstat/ Alias /webstat-ssl /home/httpd/vhosts/foo.com/statistics/webstat-ssl/ Alias /ftpstat /home/httpd/vhosts/foo.com/statistics/ftpstat/ SSLEngine on SSLVerifyClient none SSLCertificateFile /usr/local/psa/var/certificates/sMJq9Q php_admin_flag engine on php_admin_value open_basedir "/home/httpd/vhosts/foo.com/httpsdocs:/tmp" SSLRequireSSL Options +Includes +ExecCGI Alias "/error_docs" "/home/httpd/vhosts/foo.com/error_docs" ErrorDocument 400 /error_docs/bad_request.html ErrorDocument 403 /error_docs/forbidden.html ErrorDocument 404 /error_docs/not_found.html ErrorDocument 500 /error_docs/internal_server_error.html ServerName foo.com:80 ServerAlias www.foo.com UseCanonicalName Off SuexecUserGroup katz psacln ServerAdmin "hostmaster at foo.com" DocumentRoot /home/httpd/vhosts/foo.com/httpdocs CustomLog /home/httpd/vhosts/foo.com/statistics/logs/access_log combined ErrorLog /home/httpd/vhosts/foo.com/statistics/logs/error_log UserDir /home/httpd/vhosts/foo.com/web_users ScriptAlias /cgi-bin/ /home/httpd/vhosts/foo.com/cgi-bin/ SSLEngine off php_admin_flag engine on php_admin_value open_basedir "/home/httpd/vhosts/foo.com/httpdocs:/tmp" Options +Includes +ExecCGI Alias "/error_docs" "/home/httpd/vhosts/foo.com/error_docs" ErrorDocument 400 /error_docs/bad_request.html ErrorDocument 403 /error_docs/forbidden.html ErrorDocument 404 /error_docs/not_found.html ErrorDocument 500 /error_docs/internal_server_error.html From david at graniteweb.com Mon Mar 13 12:28:57 2017 From: david at graniteweb.com (David Rock) Date: Mon, 13 Mar 2017 11:28:57 -0500 Subject: [Tutor] While until the end of a list In-Reply-To: <20170313155457.GA1288@macarra> References: <20170313155457.GA1288@macarra> Message-ID: <7906E496-4F5C-41FC-87D1-C74A021398AC@graniteweb.com> > On Mar 13, 2017, at 10:54, Toni Fuente via Tutor wrote: > > Hi, > > I've got this script that goes through an httpd conf file, and gets the > related bits of it for a site, and writes a new config with values that > I am interested. The problem is that it finds the first chunk and > returns it, but I need to go to the end of all chunks list, because > there are also some chunks related to the same site that I need to > collect (virtualhost *:80 and virtualhost:443). I was > > I was thinking in a while loop in the find_chunk function that will go through > all chunks and return the chunks that site is on, but I don't know how to > construct it. You just need to make a list or a dict to store the information for each site, and add the results to it. If you use a list, it would be list.append(), for example. I don?t really follow what you expect the output to be, though. What do you want the results of running the script to look like? ? David Rock david at graniteweb.com From tonifuente at yahoo.co.uk Mon Mar 13 12:48:49 2017 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Mon, 13 Mar 2017 16:48:49 +0000 Subject: [Tutor] While until the end of a list In-Reply-To: <7906E496-4F5C-41FC-87D1-C74A021398AC@graniteweb.com> References: <20170313155457.GA1288@macarra> <7906E496-4F5C-41FC-87D1-C74A021398AC@graniteweb.com> Message-ID: <20170313164849.GB1288@macarra> * David Rock [2017-03-13 11:28:57 -0500]: > > On Mar 13, 2017, at 10:54, Toni Fuente via Tutor wrote: > > > > Hi, > > > > I've got this script that goes through an httpd conf file, and gets the > > related bits of it for a site, and writes a new config with values that > > I am interested. The problem is that it finds the first chunk and > > returns it, but I need to go to the end of all chunks list, because > > there are also some chunks related to the same site that I need to > > collect (virtualhost *:80 and virtualhost:443). I was > > > > I was thinking in a while loop in the find_chunk function that will go through > > all chunks and return the chunks that site is on, but I don't know how to > > construct it. > > You just need to make a list or a dict to store the information for each site, and add the results to it. If you use a list, it would be list.append(), for example. > > I don?t really follow what you expect the output to be, though. > What do you want the results of running the script to look like? At the moment I am writing to a file: with open("/tmp/afm/etc/httpd/conf.d/vhosts.inc/%s.conf" % site, "a") as cfile: cfile.write("".join(new_config)) and whenever finds the first chunck in total_configs.txt writes to it, and doesn't carry on searching for other chunks that contain "site", foo.com, so it won't find the site in port 80. It just writes this: ServerAlias www.foo.com ServerAdmin hostmaster at foo.com ErrorLog /websites/katz/logs/1cfl.com/error_ssl_log ScriptAlias /cgi-bin/ /websites/katz/cgi-bin/1cfl.com/ what I want to write is both: ServerAlias www.foo.com ServerAdmin hostmaster at foo.com ErrorLog /websites/katz/logs/1cfl.com/error_ssl_log ScriptAlias /cgi-bin/ /websites/katz/cgi-bin/1cfl.com/ ServerAlias www.foo.com ServerAdmin hostmaster at foo.com ErrorLog /websites/katz/logs/1cfl.com/error_ssl_log ScriptAlias /cgi-bin/ /websites/katz/cgi-bin/1cfl.com/ From mats at wichmann.us Mon Mar 13 13:12:25 2017 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 13 Mar 2017 11:12:25 -0600 Subject: [Tutor] While until the end of a list In-Reply-To: <20170313164849.GB1288@macarra> References: <20170313155457.GA1288@macarra> <7906E496-4F5C-41FC-87D1-C74A021398AC@graniteweb.com> <20170313164849.GB1288@macarra> Message-ID: <513a72ca-ce4c-e005-421e-e020f5901dd8@wichmann.us> On 03/13/2017 10:48 AM, Toni Fuente via Tutor wrote: > * David Rock [2017-03-13 11:28:57 -0500]: >> You just need to make a list or a dict to store the information for each site, and add the results to it. If you use a list, it would be list.append(), for example. >> >> I don?t really follow what you expect the output to be, though. >> What do you want the results of running the script to look like? > > At the moment I am writing to a file: > > with open("/tmp/afm/etc/httpd/conf.d/vhosts.inc/%s.conf" % site, "a") as cfile: > cfile.write("".join(new_config)) > > and whenever finds the first chunck in total_configs.txt writes to it, and > doesn't carry on searching for other chunks that contain "site", foo.com, so it > won't find the site in port 80. There's an existing project you might be able to make use of... https://pypi.python.org/pypi/parse_apache_configs/0.0.2 it's somewhere on github, I think the PyPi page links to that. From __peter__ at web.de Mon Mar 13 14:57:38 2017 From: __peter__ at web.de (Peter Otten) Date: Mon, 13 Mar 2017 19:57:38 +0100 Subject: [Tutor] While until the end of a list References: <20170313155457.GA1288@macarra> Message-ID: Toni Fuente via Tutor wrote: > Hi, > > I've got this script that goes through an httpd conf file, and gets the > related bits of it for a site, and writes a new config with values that > I am interested. The problem is that it finds the first chunk and > returns it, but I need to go to the end of all chunks list, because > there are also some chunks related to the same site that I need to > collect (virtualhost *:80 and virtualhost:443). I was > > I was thinking in a while loop in the find_chunk function that will go > through all chunks and return the chunks that site is on, but I don't know > how to construct it. > > Thank you in advance for any suggestion. Currently the structure of your script seems to be chunks = load_chunks() for site in get_sites(): interesting_chunk = find_chunk(site, chunks) if interesting_chunk is not None: do_stuff_with(interesting_chunk) If I am understanding you correctly you want chunks = load_chunks() for site in get_sites(): for interesting_chunk in find_chunks(site, chunks): do_stuff_with(interesting_chunk) One way to make that work was already mentioned, have find_chunks return a list: def find_chunks(site, chunks): matches = [] for chunk in chunks: if any(site in line for line in chunk): matches.append(chunk) return matches Another is to use a generator: def find_chunks(site, chunks): for chunk in chunks: if any(site in line for line in chunk): yield chunk From jarod_v6 at libero.it Mon Mar 13 17:19:32 2017 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Mon, 13 Mar 2017 22:19:32 +0100 (CET) Subject: [Tutor] Problem on parsing data Message-ID: <7686670.4683541489439972324.JavaMail.httpd@webmail-05.iol.local> I have a csv file with "," as separator. If I try to separate using ",": I have many different rows some with 30 columns some with 50 depend on many "," In [105]: dimension_columns = [] In [106]: with open(nomi) as f: for i in f: lines = i.rstrip("\n").split(",") if "#" not in lines[0]: dimension_columns.append(len(lines)) .....: In [108]: set(dimension_columns) Out[108]: {30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 53, 54, 59} The last coluns are as string "........." but they contqin some "," so using that script they parse. In [99]: lines Out[99]: ['chr10', '19896830', '19896830', 'C', 'A', '"intergenic"', '"ARL5B(dist=929890)', 'PLXDC2(dist=208542)"', 'NA', 'NA', '"Score=458;Name=lod=97"', 'NA', 'NA', '"0.83"', '"rs7909976"', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', '"chr10\t19896830\trs7909976\tC\tA\t.\tREJECT\tDB\tGT:AD:BQ:DP:FA\t0:0', '69:.:69:1.00\t0/1:0', '37:32:37:1.00"'] What can I do for parse better that file and Have only the comma outside the string ? From david at graniteweb.com Mon Mar 13 18:03:17 2017 From: david at graniteweb.com (David Rock) Date: Mon, 13 Mar 2017 17:03:17 -0500 Subject: [Tutor] Problem on parsing data In-Reply-To: <7686670.4683541489439972324.JavaMail.httpd@webmail-05.iol.local> References: <7686670.4683541489439972324.JavaMail.httpd@webmail-05.iol.local> Message-ID: <4A96749C-186A-4223-A18E-E5795322F78F@graniteweb.com> > On Mar 13, 2017, at 16:19, jarod_v6--- via Tutor wrote: > > > What can I do for parse better that file and Have only the comma outside the string ? > I recommend using the cvs module rather than try to write your own. https://docs.python.org/2/library/csv.html ? David Rock david at graniteweb.com From steve at pearwood.info Mon Mar 13 21:21:57 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 14 Mar 2017 12:21:57 +1100 Subject: [Tutor] Where am I mistaken? (exec not working as I expect) In-Reply-To: <20170312234835.6566a677@acerfal-roma> References: <20170312234835.6566a677@acerfal-roma> Message-ID: <20170314012156.GV5689@ando.pearwood.info> Hello Francesco, and welcome! My comments below. On Sun, Mar 12, 2017 at 11:48:35PM +0100, Francesco Loffredo via Tutor wrote: > I did only find a way to access the current document, but that's > all. Armed with that, and hoping to find some field names, I wrote a > small routine to inspect the types of all elements in that document, > and I stumbled in a strange behaviour in the exec() function: it seems > that exec() only works if called from the interactive interpreter, > while it doesn't if called inside a program. > Why? That is definitely not the case. You must be misinterpreting what you are seeing. Unfortunately, your code is so complex I cannot easily see where the problem is. Perhaps later I will have time to study it in more detail, or somebody else will. But you do not need exec here at all. exec is a very powerful command, but you should treat it as for experts only. Instead of writing: exec("qqq = inspect.getmembers(xModel.%s)" % x) a much safer way is: qqq = inspect.getmembers(getattr(xModel, x)) which is faster, easier to understand, and easier to debug. I also see you have not one, but two bare except clauses: try: ... except: ... This is not a good idea! Please read this: https://realpython.com/blog/python/the-most-diabolical-python-antipattern/ I think your code is too complex. Here is a simpler function which does what you describe as "correct behaviour": def esplora(xModel): i = 0 for i, name in enumerate(dir(xModel), 1): what = type(getattr(xModel, name)) print(name, what) print("Totale elementi: %s" % i) class prova(object): def __init__(self): self.abc = "ABC" self.num = 123 self.tup = ("abc", 321) lui = prova() esplora(lui) which gives this result: __class__ __delattr__ __dict__ __dir__ __doc__ __eq__ __format__ __ge__ __getattribute__ __gt__ __hash__ __init__ __le__ __lt__ __module__ __ne__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __sizeof__ __str__ __subclasshook__ __weakref__ abc num tup Totale elementi: 28 Hope this helps! -- Steve From __peter__ at web.de Tue Mar 14 05:18:29 2017 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Mar 2017 10:18:29 +0100 Subject: [Tutor] Where am I mistaken? (exec not working as I expect) References: <20170312234835.6566a677@acerfal-roma> <20170314012156.GV5689@ando.pearwood.info> Message-ID: Steven D'Aprano wrote: > Hello Francesco, and welcome! > > My comments below. > > On Sun, Mar 12, 2017 at 11:48:35PM +0100, Francesco Loffredo via Tutor > wrote: > >> I did only find a way to access the current document, but that's >> all. Armed with that, and hoping to find some field names, I wrote a >> small routine to inspect the types of all elements in that document, >> and I stumbled in a strange behaviour in the exec() function: it seems >> that exec() only works if called from the interactive interpreter, >> while it doesn't if called inside a program. >> Why? > > That is definitely not the case. You must be misinterpreting what you > are seeing. Unfortunately, your code is so complex I cannot easily see > where the problem is. Perhaps later I will have time to study it in more > detail, or somebody else will. I think the underlying problem is that Python 3 doesn't give you write access to the function's namespace: >>> def f(): ... x = "a" ... exec("print(x); x = 'b'; print(x)") ... print(x) ... >>> f() a b a Here exec()'s namespace is initialized with a copy of the local namespace whereas on the module level where global and local namespace are identical it operates directly on the module namespace: >>> x = "a" >>> exec("print(x); x = 'b'; print(x)") a b >>> x 'b' While exec() is the wrong choice in most cases (Steven already proposed a better way to solve your problem) you can see the rebound names if you pass a namespace explicitly: >>> def f(): ... ns = dict(x="a") ... exec("print(x); x = 'b'; print(x)", ns) ... print(ns["x"]) ... >>> f() a b b > But you do not need exec here at all. exec is a very powerful command, > but you should treat it as for experts only. Instead of writing: > > exec("qqq = inspect.getmembers(xModel.%s)" % x) > > a much safer way is: > > qqq = inspect.getmembers(getattr(xModel, x)) > > which is faster, easier to understand, and easier to debug. > > I also see you have not one, but two bare except clauses: > > try: > ... > except: > ... > > > This is not a good idea! Please read this: > > https://realpython.com/blog/python/the-most-diabolical-python-antipattern/ > > > I think your code is too complex. Here is a simpler function which does > what you describe as "correct behaviour": > > def esplora(xModel): > i = 0 > for i, name in enumerate(dir(xModel), 1): > what = type(getattr(xModel, name)) > print(name, what) > print("Totale elementi: %s" % i) > > > class prova(object): > def __init__(self): > self.abc = "ABC" > self.num = 123 > self.tup = ("abc", 321) > > lui = prova() > > esplora(lui) > > > > which gives this result: > > __class__ > __delattr__ > __dict__ > __dir__ > __doc__ > __eq__ > __format__ > __ge__ > __getattribute__ > __gt__ > __hash__ > __init__ > __le__ > __lt__ > __module__ > __ne__ > __new__ > __reduce__ > __reduce_ex__ > __repr__ > __setattr__ > __sizeof__ > __str__ > __subclasshook__ > __weakref__ > abc > num > tup > Totale elementi: 28 > > > > > Hope this helps! > > > From tonifuente at yahoo.co.uk Tue Mar 14 07:20:13 2017 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Tue, 14 Mar 2017 11:20:13 +0000 Subject: [Tutor] While until the end of a list In-Reply-To: References: <20170313155457.GA1288@macarra> Message-ID: <20170314112013.GA1152@macarra> * Peter Otten <__peter__ at web.de> [2017-03-13 19:57:38 +0100]: > > Toni Fuente via Tutor wrote: > > > Hi, > > > > I've got this script that goes through an httpd conf file, and gets the > > related bits of it for a site, and writes a new config with values that > > I am interested. The problem is that it finds the first chunk and > > returns it, but I need to go to the end of all chunks list, because > > there are also some chunks related to the same site that I need to > > collect (virtualhost *:80 and virtualhost:443). I was > > > > I was thinking in a while loop in the find_chunk function that will go > > through all chunks and return the chunks that site is on, but I don't know > > how to construct it. > > > > Thank you in advance for any suggestion. > > Currently the structure of your script seems to be > > chunks = load_chunks() > for site in get_sites(): > interesting_chunk = find_chunk(site, chunks) > if interesting_chunk is not None: > do_stuff_with(interesting_chunk) > > If I am understanding you correctly you want > > chunks = load_chunks() > for site in get_sites(): > for interesting_chunk in find_chunks(site, chunks): > do_stuff_with(interesting_chunk) > > > One way to make that work was already mentioned, have find_chunks return a > list: > > def find_chunks(site, chunks): > matches = [] > for chunk in chunks: > if any(site in line for line in chunk): > matches.append(chunk) > return matches I've used the return list solution, that gave me a list of lists with the different chunks, so I needed to convert it into a list of strings before I could use it with the regular expression matching functions: def new_chunk(chunk, user, site): config = [] strings_chunk = list(itertools.chain.from_iterable(chunk)) for item in strings_chunk: if "DocumentRoot" in item: root_dir = item.rsplit('/', 1)[-1] root_dir = root_dir.strip('\n') config.append(re.sub('/home/httpd/vhosts/[a-zA-Z\d-]{,63}(\.[a-zA-Z\d-]{,63})*/[a-zA-Z\d-]{,63}', '/websites/' + user.rstrip() + '/' + site + '/' + root_dir, item)) [...] Thank you all for your help! From __peter__ at web.de Tue Mar 14 09:09:15 2017 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Mar 2017 14:09:15 +0100 Subject: [Tutor] While until the end of a list References: <20170313155457.GA1288@macarra> <20170314112013.GA1152@macarra> Message-ID: Toni Fuente via Tutor wrote: > strings_chunk = list(itertools.chain.from_iterable(chunk)) > for item in strings_chunk: ... Note that if you are iterating over strings_chunk just once there is no need to create an in-memory list. for item in itertools.chain.from_iterable(chunk): ... will work, too, without the consumption of time and memory needed to build the list. From tonifuente at yahoo.co.uk Tue Mar 14 09:31:13 2017 From: tonifuente at yahoo.co.uk (Toni Fuente) Date: Tue, 14 Mar 2017 13:31:13 +0000 Subject: [Tutor] While until the end of a list In-Reply-To: References: <20170313155457.GA1288@macarra> <20170314112013.GA1152@macarra> Message-ID: <20170314133113.GC1152@macarra> > > for item in itertools.chain.from_iterable(chunk): > ... > > will work, too, without the consumption of time and memory needed to build > the list. > Thank you Peter, yes it works as I wanted like that. From madhur.venkat at gmail.com Tue Mar 14 10:29:26 2017 From: madhur.venkat at gmail.com (Madhu Venkat) Date: Tue, 14 Mar 2017 09:29:26 -0500 Subject: [Tutor] cx_Oracle and Pyinstaller Message-ID: Reg: https://mail.python.org/pipermail/tutor/2014-December/103608.html Hi, I am connecting to Oracle little differently, not using TNSnames.ORA file. Here is a line of code to show how I am connecting. def connect(self): try: Conn = cx_Oracle.connect (self.dsn) except cx_Oracle.DatabaseError as exception: dsn has all the required connection info. In this case, I believe I don't need TNSnames.ora file, please confirm. Though I I have multiple script files (not just one) only one connects to DB. DB connect script is imported in to other script file, that file is imported in to another file (for modular programs I had to do this). In this case, do I place all script files along with the DLLs in c:\python2.7\ folder before I run the installer? Should run the installer against the parent script (this is not the DB connect.py) ? -- Thank you, Madhu Venkat From alan.gauld at yahoo.co.uk Tue Mar 14 16:23:08 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 14 Mar 2017 20:23:08 +0000 Subject: [Tutor] cx_Oracle and Pyinstaller In-Reply-To: References: Message-ID: On 14/03/17 14:29, Madhu Venkat wrote: > try: > Conn = cx_Oracle.connect (self.dsn) > except cx_Oracle.DatabaseError as exception: > > dsn has all the required connection info. > > In this case, I believe I don't need TNSnames.ora file, please confirm. I don't know about Oracle under Python but it sounds reasonable. Hopefully someone else will confirm. > In this case, do I place all script files along with the DLLs in > c:\python2.7\ folder before I run the installer? But this sounds wrong. Just to be clear... Which specific installer are you talking about? What exactly are you installing and how? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From sreenath.cg at gmail.com Tue Mar 14 16:48:45 2017 From: sreenath.cg at gmail.com (Sreenathan Nair) Date: Wed, 15 Mar 2017 02:18:45 +0530 Subject: [Tutor] Django REST API Question In-Reply-To: References: Message-ID: Hi, I am trying to setup a django REST based service, following is my setup: MySQL DB Table (Inventory) contents is retrieved by a Django REST API query and finally passed as a list of dictionaries to a python code which will then implement some business logic based on this list. The working requirement right now is that there is no plan for users interacting with the app using a web interface (planning to use a QT desktop app for this). What I have so far, I've setup the models and model serializers, in my view I've defined a ListApiView with a get_quey_set method that will return a Response object with my list using json.dumps. The python code that does the query is using request.get on a url in order to get this json formatted list to work on. My question is if this is a valid approach to what I am trying to achieve? Am I missing something in the setup and/or would anyone recommend an alternative approach to doing this? I'm using Python 2.7 with the latest build of Django and the Django REST framework, presently everything is running on a testing machine using CentOS 7. Any feedback is greatly appreciated, thank you for your time. From fal at libero.it Wed Mar 15 08:24:56 2017 From: fal at libero.it (Francesco Loffredo) Date: Wed, 15 Mar 2017 13:24:56 +0100 Subject: [Tutor] Where am I mistaken? (exec not working as I expect) In-Reply-To: References: <20170312234835.6566a677@acerfal-roma> <20170314012156.GV5689@ando.pearwood.info> Message-ID: <5f5d4bf9-682b-2b0b-b4b7-caef987b10c3@libero.it> On 14/03/2017, Steven D'Aprano wrote: > But you do not need exec here at all. exec is a very powerful command, > but you should treat it as for experts only. Instead of writing: > > exec("qqq = inspect.getmembers(xModel.%s)" % x) > > a much safer way is: > > qqq = inspect.getmembers(getattr(xModel, x)) > > which is faster, easier to understand, and easier to debug. > > I also see you have not one, but two bare except clauses: > > try: > ... > except: > ... > > > This is not a good idea! Please read this: > > https://realpython.com/blog/python/the-most-diabolical-python-antipattern/ > > > I think your code is too complex. Here is a simpler function which does > what you describe as "correct behaviour": > > def esplora(xModel): > i = 0 > for i, name in enumerate(dir(xModel), 1): > what = type(getattr(xModel, name)) > print(name, what) > print("Totale elementi: %s" % i) and Peter Otten wrote: > I think the underlying problem is that Python 3 doesn't give you write > access to the function's namespace: > >>>> def f(): > ... x = "a" > ... exec("print(x); x = 'b'; print(x)") > ... print(x) > ... >>>> f() > a > b > a > > Here exec()'s namespace is initialized with a copy of the local namespace > whereas on the module level where global and local namespace are identical > it operates directly on the module namespace: > >>>> x = "a" >>>> exec("print(x); x = 'b'; print(x)") > a > b >>>> x > 'b' > > While exec() is the wrong choice in most cases (Steven already proposed a > better way to solve your problem) you can see the rebound names if you pass > a namespace explicitly: > >>>> def f(): > ... ns = dict(x="a") > ... exec("print(x); x = 'b'; print(x)", ns) > ... print(ns["x"]) > ... >>>> f() > a > b > b > First of all, many thanks to both of you, Steven and Peter! Steven taught me how to use getattr() instead of directly inspecting the results of dir(), thus leading me unlock the inner structure of the document I'm exploring; Peter solved the puzzle I stumbled on while searching, and taught me something about function namespace. As to the use of exec() and bare except, Steven, I read the post you linked some time ago, and I thoroughly understand those are very dangerous and complex commands. But I think I used them with all due caution. Due to my ignorance about getattr(), I tried first using type(name) and later with inspect.getmembers(name), but both of them only applied to the string I gave them, instead of its meaning. That's why I felt forced to use exec. And it worked, while in the interpreter. I'm happy I did, because this made me learn something from you! (well, after a full weekend spent in failing efforts... ;-) ) As to the two bare excepts, I just don't care what the exception is, I'm only interested in knowing if there has been one, and I properly signalled it. So I think this is a proper use case for a bare except. The output of dir(XSCRIPTCONTEXT.getDocument()), my real problem, is 290 items long, and some of them (e.g. the first one, "AllVersions") cannot be accessed at all. So I always get at least one exception, but I just don't care of them. After your help, I modified my routine, still using a bare except: # --------------------------------------------------------------------------- # this only works as a Python macro called from LibreOffice xModel = XSCRIPTCONTEXT.getDocument() i = 0 questi = [] for i, name in enumerate(dir(xModel), 1): try: qqq = inspect.getmembers(getattr(xModel, name)) except: qqq = "-NO AVAIL-" questi.append(str((name, qqq))+"\n") questi.append(str(("Totale elementi:", " %s" % i))) resultstring = "\n\n".join(questi) # --------------------------------------------------------------------------- and the first lines of its much awaited output: ============================================================= ('AllVersions', '-NO AVAIL-') ... ('Args', [('__add__', ), ('__class__', ), ('__contains__', ), ('__delattr__', ), ('__dir__', ), ('__doc__', "tuple() -> empty tuple\ntuple(iterable) -> tuple initialized from iterable's items\n\nIf the argument is a tuple, the return value is the same object."), ('__eq__', ), ('__format__', ), ('__ge__', ), ('__getattribute__', ), ('__getitem__', ), ('__getnewargs__', ), ('__gt__', ), ('__hash__', ), ('__init__', ), ('__iter__', ), ('__le__', ), ('__len__', ), ('__lt__', ), ('__mul__', ), ('__ne__', ), ('__new__', ), ('__reduce__', ), ('__reduce_ex__', ), ('__repr__', ), ('__rmul__', ), ('__setattr__', ), ('__sizeof__', ), ('__str__', ), ('__subclasshook__', ), ('count', ), ('index', )]) ('AutoStyles', [('CharacterStyles', pyuno object (com.sun.star.style.XAutoStyleFamily)0x7f2d30765c00{, supportedInterfaces={com.sun.star.style.XAutoStyleFamily,com.sun.star.lang.XTypeProvider,com.sun.star.uno.XWeak}}), ('Count', 3), ('ElementNames', ('CharacterStyles', 'RubyStyles', 'ParagraphStyles')), ('ElementType', )>), ('ImplementationId', ), ('ParagraphStyles', pyuno object (com.sun.star.style.XAutoStyleFamily)0x7f2d30765b20{, supportedInterfaces={com.sun.star.style.XAutoStyleFamily,com.sun.star.lang.XTypeProvider,com.sun.star.uno.XWeak}}), ('RubyStyles', pyuno object (com.sun.star.style.XAutoStyleFamily)0x7f2cf6ad3f20{, supportedInterfaces={com.sun.star.style.XAutoStyleFamily,com.sun.star.lang.XTypeProvider,com.sun.star.uno.XWeak}}), ('Types', ()>, )>, )>)), ('getByIndex', ), ('getByName', ), ('getCount', ), ('getElementNames', ), ('getElementType', ), ('getImplementationId', ), ('getTypes', ), ('hasByName', ), ('hasElements', ), ('queryAdapter', ), ('queryInterface', )]) ... ('Totale elementi:', ' 290') ====================================================== Now I just have to search these 290 haystacks to find the fields I created in this form... but at least I have a magnifying glass. THANKS ! Francesco From aaliyahebrahim21 at gmail.com Thu Mar 16 01:11:47 2017 From: aaliyahebrahim21 at gmail.com (Aaliyah Ebrahim) Date: Thu, 16 Mar 2017 07:11:47 +0200 Subject: [Tutor] Summing arrays Message-ID: Hi guys! I hope you can assist me with understanding and fixing my error below. Thanks for this amazing forum :) def sum2(N): b = np.arange(1,N+1,1) mylist = [ ] for i in b: terms = 2*(1+3**(i-1)) a = mylist.append[terms] return np.sum(mylist) print(sum2(N=50)) ---------------------------------------------------------------------------TypeError Traceback (most recent call last) in () 10 return np.sum(mylist) 11 ---> 12 print(sum2(N=50)) in sum2(N) 7 8 terms = 2*(1+3**(i-1))----> 9 mylist.append[terms] 10 return np.sum(mylist) 11 TypeError: 'builtin_function_or_method' object is not subscriptable Aaliyah From alan.gauld at yahoo.co.uk Thu Mar 16 05:12:30 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 16 Mar 2017 09:12:30 +0000 Subject: [Tutor] Summing arrays In-Reply-To: References: Message-ID: On 16/03/17 05:11, Aaliyah Ebrahim wrote: > def sum2(N): > > b = np.arange(1,N+1,1) > mylist = [ ] > for i in b: > terms = 2*(1+3**(i-1)) > a = mylist.append[terms] > return np.sum(mylist) > terms = 2*(1+3**(i-1))----> 9 mylist.append[terms] 10 > return np.sum(mylist) 11 > TypeError: 'builtin_function_or_method' object is not subscriptable You are using [] to call append instead of (). It should be a = mylist.append(terms) However, most of your function could be replaced by a list comprehension: def sum2(N): mylist = [2*(1+3**(i-1)) for i in np.arange(1,N+1,1) ] return np.sum(mylist) And I'm not sure the np versions of the functions will give much advantage over the standard range() and sum() Any time you see a structure like aList = [] for aList.append() You should consider whether a comprehension would be more suitable -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Thu Mar 16 05:33:05 2017 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Mar 2017 10:33:05 +0100 Subject: [Tutor] Summing arrays References: Message-ID: Aaliyah Ebrahim wrote: > Hi guys! I hope you can assist me with understanding and fixing my error > below. Thanks for this amazing forum :) > > > def sum2(N): > > b = np.arange(1,N+1,1) > mylist = [ ] > for i in b: > > > terms = 2*(1+3**(i-1)) > a = mylist.append[terms] The immediate problem is that append is a method, the line above should be mylist.append(terms) As the append() method always returns None the assignment a = ... does not do anything useful and should be avoided. > return np.sum(mylist) > > print(sum2(N=50)) However, with the fix above you will still run into overflow errors with your code. I suggest that you use Python's integer arithmetic and forget about numpy for now: $ cat tmp1.py import numpy as np def sum2(N): b = np.arange(1,N+1,1) mylist = [] for i in b: terms = 2*(1+3**(i-1)) mylist.append(terms) return np.sum(mylist) def sum2a(N): mylist = [] for i in range(1, N+1): mylist.append(2*(1+3**(i-1))) return sum(mylist) print("N=5:", sum2(5), sum2a(5)) print("N=50:", sum2(50), sum2a(50)) $ python3 tmp1.py N=5: 252 252 tmp1.py:7: RuntimeWarning: overflow encountered in long_scalars terms = 2*(1+3**(i-1)) N=50: 6048575297968530476 717897987691852588770348 Both the numpy and the non-numpy version can be written more concisely (and for the numpy version the rewritten version is more efficient, too): $ cat tmp2.py import numpy as np def sum2(N): b = np.arange(1, N+1, 1, dtype=float) a = 2*(1+3**(b-1)) return a.sum() def sum2a(N): return sum(2*(1+3**(i-1)) for i in range(1, N+1)) print("N=5:", sum2(5), sum2a(5)) print("N=50:", sum2(50), sum2a(50)) $ python3 tmp2.py N=5: 252.0 252 N=50: 7.17897987692e+23 717897987691852588770348 (Specifying dtype=float forces floating point arithmetic which is inexact) From wolfgang.maier at biologie.uni-freiburg.de Thu Mar 16 05:38:42 2017 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Thu, 16 Mar 2017 10:38:42 +0100 Subject: [Tutor] Summing arrays In-Reply-To: References: Message-ID: On 03/16/2017 10:12 AM, Alan Gauld via Tutor wrote: > On 16/03/17 05:11, Aaliyah Ebrahim wrote: > >> def sum2(N): >> >> b = np.arange(1,N+1,1) >> mylist = [ ] >> for i in b: >> terms = 2*(1+3**(i-1)) >> a = mylist.append[terms] >> return np.sum(mylist) > >> terms = 2*(1+3**(i-1))----> 9 mylist.append[terms] 10 >> return np.sum(mylist) 11 >> TypeError: 'builtin_function_or_method' object is not subscriptable > > You are using [] to call append instead of (). > It should be > a = mylist.append(terms) > > However, most of your function could be replaced by > a list comprehension: > > def sum2(N): > mylist = [2*(1+3**(i-1)) for i in np.arange(1,N+1,1) ] > return np.sum(mylist) > > And I'm not sure the np versions of the functions will > give much advantage over the standard range() and sum() > > Any time you see a structure like > > aList = [] > for > aList.append() > > You should consider whether a comprehension would > be more suitable > Alternatively, you could even use a generator expression (essentially, just omitting the brackets from Alan's suggestion) and avoid keeping mylist in memory like this: def sum2(N): return np.sum(2*(1+3**(i-1)) for i in np.arange(1,N+1,1)) In addition, I'd agree with Alan that the advantage of using numpy functionality in this function seems quite questionable. You'd probably get pretty much the same performance with just: def sum2(N): return sum(2*(1+3**(i-1)) for i in range(1,N+1,1)) Best, Wolfgang From wolfgang.maier at biologie.uni-freiburg.de Thu Mar 16 05:47:59 2017 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Thu, 16 Mar 2017 10:47:59 +0100 Subject: [Tutor] Summing arrays In-Reply-To: References: Message-ID: On 03/16/2017 10:38 AM, Wolfgang Maier wrote: > > In addition, I'd agree with Alan that the advantage of using numpy > functionality in this function seems quite questionable. You'd probably > get pretty much the same performance with just: > > def sum2(N): > return sum(2*(1+3**(i-1)) for i in range(1,N+1,1)) > Or, if you really want to leverage the power of numpy (and are willing to pay the price of possibly inexact calculations) rewrite your function as Peter shows in his reply. From __peter__ at web.de Thu Mar 16 06:10:11 2017 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Mar 2017 11:10:11 +0100 Subject: [Tutor] Summing arrays References: Message-ID: Peter Otten wrote: > (Specifying dtype=float forces floating point arithmetic which is inexact) I found a way to avoid the error: >>> import numpy as np >>> def sum2(N): ... a = np.arange(1, N+1, dtype=object) ... return (2*(1+3**(a-1))).sum() ... >>> sum2(50) 717897987691852588770348 As this operates on int objects rather than C/machine language numbers this will probably be significantly slower than dtype=int or dtype=float. From joaquin.henriquez at countercept.com Thu Mar 16 05:10:07 2017 From: joaquin.henriquez at countercept.com (Joaquin Henriquez) Date: Thu, 16 Mar 2017 09:10:07 +0000 Subject: [Tutor] EXTERNAL: Summing arrays In-Reply-To: References: Message-ID: >def sum2(N): > b = np.arange(1,N+1,1) > mylist = [ ] > for i in b: > terms = 2*(1+3**(i-1)) > a = mylist.append[terms] > return np.sum(mylist) >print(sum2(N=50)) You have an error such as: a = mylist.append(terms) From aaliyahebrahim21 at gmail.com Fri Mar 17 07:43:42 2017 From: aaliyahebrahim21 at gmail.com (Aaliyah Ebrahim) Date: Fri, 17 Mar 2017 13:43:42 +0200 Subject: [Tutor] Maximum value in an array Message-ID: Hi I am trying to practice the following question for my test tomorrow. Please help me find my errors. *Consider the following displacement sequence [x1; x2;..... x11] and velocity sequence [v1; v2;....... v11]:x[k+1] = x[k]+ 0.1 v[k]v[k+1] = v[k] - 10* x[k] + 0.1 sin(0.1* k *theta)Compute the maximum displacement from the displacementsequence. Use theta = 1 [rad] and theinitial values x1 = 0 and v1 = 0.* Here is my code: x = np.zeros(11) v = np.zeros(11) x[0] = 1 v[0] = 1 a = np.arange(1,10,1) for k in a: x[k+1] = x[k] + 0.1*v[k] v[k+1] = v[k] - 10*x[k] +0.1*sin(0.1*k*1) print(x.max()) *This was a follow-up question with a suggested answer:Repeat the maximum displacement computation for theta = 1; 2,3.... 20 [rad] and store the maximum displacement for each in a list.from math import sinmax_disp = []omega_values = range(1, 21, 1)for omega in omega_values: x = [0.0] * 11 v = [0.0] * 11 for k in range(10): x[k+1] = x[k] + 0.1 * v[k] v[k+1] = v[k] - 10 * x[k] + 0.1 * sin(0.1 * omega * (k + 1)) max_disp.append( max(x) ) print(max_disp)* My question is what do the lines in red mean? Thank you for your time. From __peter__ at web.de Fri Mar 17 13:02:03 2017 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Mar 2017 18:02:03 +0100 Subject: [Tutor] Maximum value in an array References: Message-ID: Aaliyah Ebrahim wrote: > Hi Hello again. Was your previous question answered to your satisfaction? > I am trying to practice the following question for my test tomorrow. > Please help me find my errors. > *Consider the following displacement sequence [x1; x2;..... x11] and > velocity sequence [v1; v2;....... v11]:x[k+1] = x[k]+ 0.1 v[k]v[k+1] = > v[k] - 10* x[k] + 0.1 sin(0.1* k *theta)Compute the maximum displacement > from the displacementsequence. Use theta = 1 [rad] and theinitial values > x1 = 0 and v1 = 0.* A few hints: The above description uses x1, ..., x11 to describe the entries in the sequence. Python on the other side uses zero-based indices: x[0], ..., x[10] # eleven entries A good start might be to convert the above task to that system before you begin coding. Be careful about the one place where k is not an array index. > Here is my code: > x = np.zeros(11) > v = np.zeros(11) > > x[0] = 1 > v[0] = 1 Where do the ones come from? > a = np.arange(1,10,1) How many entries does a have? How many should it actually have? > for k in a: > x[k+1] = x[k] + 0.1*v[k] > v[k+1] = v[k] - 10*x[k] +0.1*sin(0.1*k*1) Does this loop ever use the inital values v[0] and x[0]? > print(x.max()) > *This was a follow-up question with a suggested answer:Repeat the maximum > displacement computation for theta = 1; 2,3.... 20 [rad] and store the > maximum displacement for each in a list.from math import sinmax_disp = > []omega_values = range(1, 21, 1)for omega in omega_values: x = > [[0.0] > * 11 v = [0.0] * 11 for k in range(10): x[k+1] = x[k] + 0.1 * > v[k] v[k+1] = v[k] - 10 * x[k] + 0.1 * sin(0.1 * omega * (k + 1)) > max_disp.append( max(x) ) print(max_disp)* > My question is what do the lines in red mean? I'm sorry I see garbled text rather than colors. Please try to compose your messages using text only, not HTML. Thank you. From aaliyahebrahim21 at gmail.com Fri Mar 17 10:46:14 2017 From: aaliyahebrahim21 at gmail.com (Aaliyah Ebrahim) Date: Fri, 17 Mar 2017 16:46:14 +0200 Subject: [Tutor] While condition Message-ID: Hi, in my code below, why is it returning a value that is greater than 1200 if my condition is that the value should be less than 1200? Thank you. def sum_list(val): list_sum = 0 n =0 mylist = [] while list_sum < val: n = n+1 term = n**2 list_sum = list_sum + term mylist.append(list_sum) return list_sum,n,mylist print(sum_list(1200)) This is the output: (1240, 15, [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225]) From alan.gauld at yahoo.co.uk Fri Mar 17 15:18:01 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 17 Mar 2017 19:18:01 +0000 Subject: [Tutor] While condition In-Reply-To: References: Message-ID: On 17/03/17 14:46, Aaliyah Ebrahim wrote: > Hi, in my code below, why is it returning a value that is greater than 1200 > if my condition is that the value should be less than 1200? Your condition is that it be less than 1200 when it enters the loop body. That means it will *always* be 1200 or greater when it exits the loop. In this case n is 14 when it enters the last loop iteration so the loop body does: n = n+1 -> 15 term = n**2 -> 225 list_sum = list_sum + term -> 1240 That means that when it entered the loop the value was 1240-225 = 1015, which is less than 1200. > def sum_list(val): > list_sum = 0 > n =0 > mylist = [] > while list_sum < val: > n = n+1 > term = n**2 > list_sum = list_sum + term > > mylist.append(list_sum) > return list_sum,n,mylist > > print(sum_list(1200)) > > This is the output: > (1240, 15, [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225]) Incidentally it looks as if your code actually did mylist.append(term) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From rafael.knuth at gmail.com Sun Mar 19 08:17:03 2017 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sun, 19 Mar 2017 13:17:03 +0100 Subject: [Tutor] tiny, little issue with list Message-ID: LogActivities = [] prompt = ("What have you done today? ") prompt += ("Enter 'quit' to exit. ") while True: activity = input(prompt) LogActivities.append(activity) if activity == "quit": print("Let me recap. This is what you've done today: %s." % ", " .join(LogActivities)) This program is supposed to take user input and to log his activities into a list. All works well, only when the user quits, the program adds 'quit' to LogActivities. How do I prevent my program from doing this? Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> = RESTART: C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python Code/PPC_159.py = What have you done today? Enter 'quit' to exit. shower What have you done today? Enter 'quit' to exit. walk the dog What have you done today? Enter 'quit' to exit. drink coffee What have you done today? Enter 'quit' to exit. prepare lunch What have you done today? Enter 'quit' to exit. take coding lesson What have you done today? Enter 'quit' to exit. quit Let me recap. This is what you've done today: shower, walk the dog, drink coffee, prepare lunch, take coding lesson, quit. What have you done today? Enter 'quit' to exit. From alan.gauld at yahoo.co.uk Sun Mar 19 12:01:52 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 19 Mar 2017 16:01:52 +0000 Subject: [Tutor] tiny, little issue with list In-Reply-To: References: Message-ID: On 19/03/17 12:17, Rafael Knuth wrote: > LogActivities = [] > prompt = ("What have you done today? ") > prompt += ("Enter 'quit' to exit. ") I'm not sure why you put that on two lines but thats just a nit pick... > while True: This will loop forever unless you explicitly break, return or hit an exception. You should fix that. > activity = input(prompt) > LogActivities.append(activity) You append activity regardless of what it is so obviously you include the 'quit'. > if activity == "quit": > print("Let me recap. This is what you've done today: %s." % ", > " .join(LogActivities)) Then after appending it you test to see if its quit then print a message(but don;t actually quit, see above) To avoid the append you could put the test for quit at the top of the loop and put the append lines in an else: if activity == 'quit': print.... # and break? else: append.... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From marc.sebek at gmail.com Sun Mar 19 15:20:42 2017 From: marc.sebek at gmail.com (Marc Sebek) Date: Mon, 20 Mar 2017 08:20:42 +1300 Subject: [Tutor] Tutor Digest, Vol 157, Issue 39 In-Reply-To: References: Message-ID: Hi Rafael You are appending quit to the list, before checking to see if quit has been typed. You could move the "if Statement" up in the code and add an else statement, so Quit is not appended to the list first thing. while True: activity = input(prompt) if activity == "quit": print("Let me recap. This is what you've done today: %s." % ", " .join(LogActivities)) else: LogActivities.append(activity) But you have an infinite loop here too, so unless you are adding more to this, and plan to get out the loop, you should also add a break statment: ++++++++++++++++++++++++++++++++++++ if activity == "quit": print("Let me recap. This is what you've done today: %s." % ", " .join(LogActivities)) break ###<<< wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > Today's Topics: > > 1. tiny, little issue with list (Rafael Knuth) > > > ---------- Forwarded message ---------- > From: Rafael Knuth > To: "Tutor at python.org" > Cc: > Bcc: > Date: Sun, 19 Mar 2017 13:17:03 +0100 > Subject: [Tutor] tiny, little issue with list > LogActivities = [] > prompt = ("What have you done today? ") > prompt += ("Enter 'quit' to exit. ") > > while True: > activity = input(prompt) > LogActivities.append(activity) > > if activity == "quit": > print("Let me recap. This is what you've done today: %s." % ", > " .join(LogActivities)) > > This program is supposed to take user input and to log his activities > into a list. > All works well, only when the user quits, the program adds 'quit' to > LogActivities. > How do I prevent my program from doing this? > > Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 > 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > >>> > = RESTART: C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python > Code/PPC_159.py = > What have you done today? Enter 'quit' to exit. shower > What have you done today? Enter 'quit' to exit. walk the dog > What have you done today? Enter 'quit' to exit. drink coffee > What have you done today? Enter 'quit' to exit. prepare lunch > What have you done today? Enter 'quit' to exit. take coding lesson > What have you done today? Enter 'quit' to exit. quit > Let me recap. This is what you've done today: shower, walk the dog, > drink coffee, prepare lunch, take coding lesson, quit. > What have you done today? Enter 'quit' to exit. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > From Edzard at stroomli.nl Mon Mar 20 15:37:42 2017 From: Edzard at stroomli.nl (Edzard de Vries) Date: Mon, 20 Mar 2017 19:37:42 +0000 Subject: [Tutor] CSV file Reading in python Message-ID: I have a CSV which I want to be able to read in Python. I don't know the exact syntax and I get error messages. Where can I find the syntax to do this. I juiste starter learning Python. Edzard. From gvmcmt at gmail.com Mon Mar 20 05:17:49 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Mon, 20 Mar 2017 14:47:49 +0530 Subject: [Tutor] tiny, little issue with list In-Reply-To: References: Message-ID: Hi Rafael, LogActivities = [] prompt = ("What have you done today? Enter 'quit' to exit. ") while True: activity = input(prompt) # Do this here so 'quit' is not appended to the list if activity == 'quit': # To get out of the loop break # If still in the loop, append this activity to the list # Note, no else statement here LogActivities.append(activity) # Do this outside the loop if LogActivities: # See if the list is not empty print("Let me recap. This is what you've done today: %s." % ", " .join(LogActivities)) Sri On Sun, Mar 19, 2017 at 5:47 PM, Rafael Knuth wrote: > LogActivities = [] > prompt = ("What have you done today? ") > prompt += ("Enter 'quit' to exit. ") > > while True: > activity = input(prompt) > LogActivities.append(activity) > > if activity == "quit": > print("Let me recap. This is what you've done today: %s." % ", > " .join(LogActivities)) > > This program is supposed to take user input and to log his activities > into a list. > All works well, only when the user quits, the program adds 'quit' to > LogActivities. > How do I prevent my program from doing this? > > Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 > 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > >>> > = RESTART: C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python > Code/PPC_159.py = > What have you done today? Enter 'quit' to exit. shower > What have you done today? Enter 'quit' to exit. walk the dog > What have you done today? Enter 'quit' to exit. drink coffee > What have you done today? Enter 'quit' to exit. prepare lunch > What have you done today? Enter 'quit' to exit. take coding lesson > What have you done today? Enter 'quit' to exit. quit > Let me recap. This is what you've done today: shower, walk the dog, > drink coffee, prepare lunch, take coding lesson, quit. > What have you done today? Enter 'quit' to exit. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From niihung at gmail.com Mon Mar 20 18:09:55 2017 From: niihung at gmail.com (=?UTF-8?B?4Kiq4Kmw4Kic4Ki+4KisIOCoquCpsOConOCovuCorOCpgA==?=) Date: Mon, 20 Mar 2017 15:09:55 -0700 Subject: [Tutor] HTML module for Python Message-ID: Hi Looking for recommendations on Python module to use to generate HTML pages/tables, other HTML content. Kindly help. Regards Ni From rafael.knuth at gmail.com Tue Mar 21 13:20:21 2017 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Tue, 21 Mar 2017 18:20:21 +0100 Subject: [Tutor] Using Class Properly - early beginner question Message-ID: I am trying to write a food shopping list. The user should be able to add items to that shopping list, and later on decide what should happen to those purchased foods: instantly consumed or stored. My initial idea was to create a parent class to populate the shopping list and a child class to manage the purchased items as described above. While writing the parent class, I ran into the following issue: How do I properly declare a variable that takes user input? Do I write methods in the same fashion like in a regular function? And how do I call that class properly? This is what I came up with: class BuyFoods(object): def __init__(self, outlet): self.outlet = outlet def CreateShoppingList(self, shopping_list, prompt, food): self.shopping_list = shopping_list self.prompt = prompt self.food = food shopping_list = [] prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") food = input(prompt) while food != "quit": shopping_list.append(food) food = input(prompt) print("You just purchased these foods: %s." % ", ".join(shopping_list)) Tesco = BuyFoods("Tesco") Tesco.CreateShoppingList() That's the error message I get: Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> == RESTART: C:\Users\Rafael\Documents\01 - BIZ\PYTHON\Python Code\PPC_28.py == Traceback (most recent call last): File "C:\Users\Rafael\Documents\01 - BIZ\PYTHON\Python Code\PPC_28.py", line 136, in Tesco.CreateShoppingList() TypeError: CreateShoppingList() missing 3 required positional arguments: 'shopping_list', 'prompt', and 'food' >>> From david at graniteweb.com Tue Mar 21 22:26:33 2017 From: david at graniteweb.com (David Rock) Date: Tue, 21 Mar 2017 21:26:33 -0500 Subject: [Tutor] CSV file Reading in python In-Reply-To: References: Message-ID: > On Mar 20, 2017, at 14:37, Edzard de Vries wrote: > > I have a CSV which I want to be able to read in Python. I don't know the exact syntax and I get error messages. Where can I find the syntax to do this. > I juiste starter learning Python. Edzard, Please post your code and the errors you are getting so we can see what issue you are having. ? David Rock david at graniteweb.com From robertvstepp at gmail.com Tue Mar 21 22:48:49 2017 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 21 Mar 2017 21:48:49 -0500 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: On Tue, Mar 21, 2017 at 12:20 PM, Rafael Knuth wrote: > > While writing the parent class, I ran into the following issue: > How do I properly declare a variable that takes user input? > Do I write methods in the same fashion like in a regular function? > And how do I call that class properly? When you "call the class" as you put it, you are asking the class to create a specific, new instance of that class, a new object. You may or may not have to pass one or more arguments into the __init__ method of that class. How do you know? What parameters (other than "self") does the __init__ method have? It needs those to create an object instance. What is required depends on how you set up your class' __init__ method. Once you have created an object from a class, then you may access attributes or methods defined for that object using "dot" notation. Methods are very much like functions with the exception that they are tied to an object, thus the "self" parameter which refers to that object instance. > This is what I came up with: > > class BuyFoods(object): > def __init__(self, outlet): > self.outlet = outlet > def CreateShoppingList(self, shopping_list, prompt, food): > self.shopping_list = shopping_list > self.prompt = prompt > self.food = food > shopping_list = [] > prompt = ("Which foods would you like to purchase?\nEnter > 'quit' to exit. ") > food = input(prompt) > > while food != "quit": > shopping_list.append(food) > food = input(prompt) > > print("You just purchased these foods: %s." % ", ".join(shopping_list)) > > Tesco = BuyFoods("Tesco") Here is where you created your new object, "Tesco". Now you can access *this* object's methods and attributes with the dot notation. > Tesco.CreateShoppingList() And here you try to access the "CreateShoppingList" method of the object "Tesco". [Note: It is customary to use the same naming conventions for methods that you use for functions. So instead of using camel case for the method's name, it would be more customary to use a name format, "create_shopping_list".] But notice in your class definition that this method requires the following arguments to be passed into it: self, shopping_list, prompt, and food. You provided "self" automatically by creating the object, "Tesco", and accessing its "CreateShoppingList()" method, but you did not provide the other arguments. Thus the error message you get below. You would need to call it something like: Tesco.CreateShoppingList(['milk', 'bread', 'oranges'], 'Which foods would you like to purchase?\nEnter "quit" to exit.', 'spam') This would clear the immediate errors, but the logic of your method is not designed to make use of these arguments being passed in. Instead, you do nothing with them and basically ask for all of this information again. Does this make sense to you? > That's the error message I get: > > Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 > 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. >>>> > == RESTART: C:\Users\Rafael\Documents\01 - BIZ\PYTHON\Python Code\PPC_28.py == > Traceback (most recent call last): > File "C:\Users\Rafael\Documents\01 - BIZ\PYTHON\Python > Code\PPC_28.py", line 136, in > Tesco.CreateShoppingList() > TypeError: CreateShoppingList() missing 3 required positional > arguments: 'shopping_list', 'prompt', and 'food' So in your method, to do what it looks like you are trying to do *with arguments*, you should be doing things like: food = input(self.prompt) self.shopping_list.append(self.food) etc. But if you truly want the user to be inputting this information, then you don't want your method to have these arguments! So you have to choose which approach you want to do. HTH! -- boB From alan.gauld at yahoo.co.uk Wed Mar 22 03:29:14 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 22 Mar 2017 07:29:14 +0000 Subject: [Tutor] HTML module for Python In-Reply-To: References: Message-ID: On 20/03/17 22:09, ????? ?????? wrote: > Looking for recommendations on Python module to use to generate HTML > pages/tables, other HTML content. Kindly help. While thee are some modules that help with this most Python programs I've seen just generate the HTML directly as strings. There is no direct equivalent of, say, Perl's CGI module. However, if you are using a web framework, it will generally provide a templating mechanism which will separate out the HTML code (the view) from your Python code (the model and controller). So if you give is more information about what the HTML is being used for, we might be able to provide more help. Is it part of a web application or just a data file that you make available to some third party? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Mar 22 03:31:17 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 22 Mar 2017 07:31:17 +0000 Subject: [Tutor] CSV file Reading in python In-Reply-To: References: Message-ID: On 20/03/17 19:37, Edzard de Vries wrote: > I have a CSV which I want to be able to read in Python. Are you using the csv module? Have you read the documentation for that? It gives several examples. If not already then use csv. If you are using it and still have problems send the code and errors, otherwise we will just be guessing. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From gvmcmt at gmail.com Tue Mar 21 22:42:18 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Wed, 22 Mar 2017 08:12:18 +0530 Subject: [Tutor] CSV file Reading in python In-Reply-To: References: Message-ID: Hi, Reading (and processing and writing) CSV files https://github.com/slott56/introduction-python-csv/blob/master/README.md On Mar 22, 2017 06:18, "Edzard de Vries" wrote: I have a CSV which I want to be able to read in Python. I don't know the exact syntax and I get error messages. Where can I find the syntax to do this. I juiste starter learning Python. Edzard. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From gvmcmt at gmail.com Tue Mar 21 22:59:09 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Wed, 22 Mar 2017 08:29:09 +0530 Subject: [Tutor] HTML module for Python In-Reply-To: References: Message-ID: Hi, Please take a look at https://pypi.python.org/pypi/html On Mar 22, 2017 06:24, "????? ??????" wrote: > Hi > > Looking for recommendations on Python module to use to generate HTML > pages/tables, other HTML content. Kindly help. > > Regards > Ni > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From rafael.knuth at gmail.com Wed Mar 22 08:30:42 2017 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Wed, 22 Mar 2017 13:30:42 +0100 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: thanks for your feedback! @boB I wrote a function that does exactly what I want, and that is: Create a shopping list and then let the user decide which items (food) are supposed to be instantly consumed and which ones stored. def ManageFood(): create_shopping_list = [] prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") food = input(prompt) while food != "quit": create_shopping_list.append(food) food = input(prompt) print("These are your foods on your shopping list: %s." % ", " .join(create_shopping_list)) eat_food = [] store_food = [] for food in create_shopping_list: print("You bought this item: %s. " % (food)) prompt = input("What would you like to do with it?\nEnter 'eat' or 'store'. ") if prompt == "eat": eat_food.append(food) elif prompt == "store": store_food.append(food) print("Food you want to eat now: %s." % ", " .join(eat_food)) print("Food you want to store: %s." % ", " .join(store_food)) ManageFood() PS: Please let me know if you have any suggestions how to write my code above in a shorter, more elegant fashion (it does what it's supposed to do, but not sure if a pro would write it same way I did). Besides that, I want to take it a step further and rewrite the function above as a class, and I don't know how exactly how to do this. (coding newbie pains ... I just learned the basics about classes in Python, but nowhere could I find examples of how to properly initialize classes, given that it operates solely with user input - same goes with with calling that class properly). Here's how far I got on my own: class FoodShopping(object): def __init__ (self, create_shoppping_list, prompt, food, eat_food, store_food): self.create_shopping_list = create_shopping_list self.prompt = prompt self.food = food self.eat_food = eat_food self.store_food = store_food def ManageFood(self, create_shopping_list, prompt, food, eat_food, store_food): create_shopping_list = [] prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") food = input(prompt) while food != "quit": create_shopping_list.append(food) food = input(prompt) print("These are your foods on your shopping list: %s." % ", " .join(create_shopping_list)) eat_food = [] store_food = [] for food in create_shopping_list: print("You bought this item: %s. " % (food)) prompt = input("What would you like to do with it?\nEnter 'eat' or 'store'. ") if prompt == "eat": eat_food.append(food) elif prompt == "store": store_food.append(food) print("Food you want to eat now: %s." % (eat_food)) print("Food you want to store: %s." % (store_food)) FoodShopping() That's the error message I get when executing my code: Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python Code/PPC_29.py == Traceback (most recent call last): File "C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python Code/PPC_29.py", line 140, in FoodShopping() TypeError: __init__() missing 5 required positional arguments: 'create_shoppping_list', 'prompt', 'food', 'eat_food', and 'store_food' >>> From yosi.levy99 at gmail.com Wed Mar 22 12:10:03 2017 From: yosi.levy99 at gmail.com (Yosef Levy) Date: Wed, 22 Mar 2017 18:10:03 +0200 Subject: [Tutor] how to redirect input from pipe Message-ID: Hello All, I am running with Python 2.7 I have to run script that could have get arguments in two ways: 1. argument + file name. 2. argument + input from pipe. example for 1: ./my_script.py -t 1,2,3 file_name.txt example for 2: grep snd file_name.txt | ./my_script.py -t 1,2,3 I am using "parse_known_args" to parse the rest of args when pipe exists. and capture with: "fileinput". My problem is that this does not run always, for second option. Any idea how could I get standard input with additional flag? for example, running with pipe option will be like this: grep snd file_name.txt | ./my_script.py -t 1,2,3 - where the additional "-" at the end will indicate script to get standard input. Rgds. ============================================ my script: ----------------------------------------------------------------------- #!/usr/bin/python import fileinput import argparse class TAG(object): pass tag = TAG () parser = argparse.ArgumentParser() parser.add_argument('-t', help = "tags,\n for example: -t 35,150,39") args, unk = parser.parse_known_args(namespace=tag) tag_list = tag.t.split(',') for line in fileinput.input(unk): print line ------------------------------------------------------------------------------- From richmcewan at icloud.com Wed Mar 22 17:17:43 2017 From: richmcewan at icloud.com (Richard Mcewan) Date: Wed, 22 Mar 2017 21:17:43 +0000 Subject: [Tutor] Help with function scoping Message-ID: <437DA200-9760-40EB-A654-DF2FC0BEE1A3@icloud.com> Hi I wonder if you can help. I'm confused about how functions should work. Below is some code I write to check my understanding. I'm expecting two functions to be defined. Then called. One returns a random number. The other user input (guessing the number). I expect the return values to act like variables that I can use in a while loop. The programme asks for the user input then crashes. The error report says 'NameError:The name 'userGuess' is not defined. My understanding is wrong somewhere. I thought functions would allow me to return values I could use elsewhere without having to define them initially. I.e. Encapsulation. I've looked for other examples but get the same issue. I expect a function to return a variable I can use elsewhere. Not sure how to do. In the case below I'm not sure how I can use the work of the function elsewhere. Advice welcome. Richard Using Pythonista App on iOS with Python 2.7 on iPhone 5s # coding: utf-8 import random #guess number game #computer generates random number def generateNumber(): computerGuess = int(random.randrange(0,101)) return computerGuess #get user def getUser(): userGuess = int(input('Guess a number')) return userGuess #call for computer and user generateNumber() getUser() #loop to check guess and report while userGuess != computerGuess: if userGuess < computerGuess: print('Too low') getUser() elif userGuess > computerGuess: print('Too high') getUser() elif userGuess > computerGuess: print('Correct!') #Add counter of guess later Sent from my iPhone From joel.goldstick at gmail.com Wed Mar 22 20:24:44 2017 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 22 Mar 2017 20:24:44 -0400 Subject: [Tutor] Help with function scoping In-Reply-To: <437DA200-9760-40EB-A654-DF2FC0BEE1A3@icloud.com> References: <437DA200-9760-40EB-A654-DF2FC0BEE1A3@icloud.com> Message-ID: On Wed, Mar 22, 2017 at 5:17 PM, Richard Mcewan wrote: > Hi > > I wonder if you can help. > > I'm confused about how functions should work. Below is some code I write to check my understanding. > > I'm expecting two functions to be defined. Then called. One returns a random number. The other user input (guessing the number). > > I expect the return values to act like variables that I can use in a while loop. > > The programme asks for the user input then crashes. The error report says 'NameError:The name 'userGuess' is not defined. > > My understanding is wrong somewhere. I thought functions would allow me to return values I could use elsewhere without having to define them initially. I.e. Encapsulation. > > I've looked for other examples but get the same issue. I expect a function to return a variable I can use elsewhere. Not sure how to do. In the case below I'm not sure how I can use the work of the function elsewhere. > > Advice welcome. > > Richard > > Using Pythonista App on iOS with Python 2.7 on iPhone 5s > > # coding: utf-8 > import random > > #guess number game > > #computer generates random number > def generateNumber(): > computerGuess = int(random.randrange(0,101)) > return computerGuess > > #get user > def getUser(): > userGuess = int(input('Guess a number')) > return userGuess > > #call for computer and user > generateNumber() > getUser() You don't assign your return values above, try this: computerGuess = generateNumber() userGuess = getUser() Also, you should copy and paste your full traceback when you post here. It will give the line number of the error > > #loop to check guess and report > while userGuess != computerGuess: > if userGuess < computerGuess: > print('Too low') > getUser() > elif userGuess > computerGuess: > print('Too high') > getUser() > elif userGuess > computerGuess: > print('Correct!') > > #Add counter of guess later > > > Sent from my iPhone > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From __peter__ at web.de Wed Mar 22 20:38:37 2017 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Mar 2017 01:38:37 +0100 Subject: [Tutor] how to redirect input from pipe References: Message-ID: Yosef Levy wrote: > Hello All, > > I am running with Python 2.7 > I have to run script that could have get arguments in two ways: > 1. argument + file name. > 2. argument + input from pipe. > > example for 1: > ./my_script.py -t 1,2,3 file_name.txt > > example for 2: > grep snd file_name.txt | ./my_script.py -t 1,2,3 > > I am using "parse_known_args" to parse the rest of args when pipe exists. > and capture with: "fileinput". > > My problem is that this does not run always, for second option. > Any idea how could I get standard input with additional flag? > for example, running with pipe option will be like this: > grep snd file_name.txt | ./my_script.py -t 1,2,3 - > where the additional "-" at the end will indicate script to get standard > input. It's not clear to me why you use parse_known_args(). The examples you give above seem to be covered by $ cat tmp.py #!/usr/bin/env python import argparse import fileinput parser = argparse.ArgumentParser() parser.add_argument("--tags", "-t") parser.add_argument("files", metavar="file", nargs="*") args = parser.parse_args() print args.tags for line in fileinput.input(args.files): print line.strip() $ cat greek.txt alpha beta gamma delta $ cat numbers.txt ONE TWO Reading from a file: $ ./tmp.py -t 1,2,3 numbers.txt 1,2,3 ONE TWO Reading from two files: $ ./tmp.py -t 1,2,3 numbers.txt greek.txt 1,2,3 ONE TWO alpha beta gamma delta Reading from stdin: $ grep ^[ab] greek.txt | ./tmp.py -t 1,2,3 1,2,3 alpha beta Reading from a file, then stdin, then another file: $ grep ^[ab] greek.txt | ./tmp.py -t 1,2,3 numbers.txt - numbers.txt 1,2,3 ONE TWO alpha beta ONE TWO $ From alan.gauld at yahoo.co.uk Wed Mar 22 20:41:09 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 23 Mar 2017 00:41:09 +0000 Subject: [Tutor] Help with function scoping In-Reply-To: <437DA200-9760-40EB-A654-DF2FC0BEE1A3@icloud.com> References: <437DA200-9760-40EB-A654-DF2FC0BEE1A3@icloud.com> Message-ID: On 22/03/17 21:17, Richard Mcewan wrote: > I'm expecting two functions to be defined. Then called. And thats what you've got. But... > One returns a random number. The other user input (guessing the number). And thats also what you've got but you don't do anything with the returned value you just ignore it. You need to assign the result to a variable. > I expect the return values to act like variables that I can use in a while loop. The return values are just values like any other. Just as you can do x = 42 # assign the value 42 to the variable x you can also do y = myFunction() # assign return value from myFunction to variable y > ...The error report says 'NameError:The name 'userGuess' is not defined. Which is true, you use it but you never assign a value to it. You need to do something like: userGuess = getUser() Although the name is poor since you are not getting the User you are getting a number... > My understanding is wrong somewhere. You are confusing values and variables. Variables in Python are labels that we attach to values (aka objects) so that we can refer to those values later in our code. > I thought functions would allow me to return values > I could use elsewhere without having to define them They return values. But you need to assign those values to variables to be able to use them. > initially. I.e. Encapsulation. None of this has anything to do with encapsulation. Functions encapsulate an algorithm and the data needed to perform that algorithm, they return a value without you needing to know how the value was worked out. That is encapsulation. > I've looked for other examples but get the same issue. The simplest examples are the built in functions, such as pow() or len() len('freddy') Doesn't do anything(*) because we throw the result away. L = len('freddy') assigns the return value from len() to the variable L. > I expect a function to return a variable I can use elsewhere. No, functions return values not variables. You create the variables because its you that will use them. How could the function possibly know what you want to call the variable? It cannot, it just returns the result of some operation or calculation. Only you know what you are going to use that for, so you can create a variable with a suitably descriptive name. > In the case below I'm not sure how I can use the work of the function elsewhere. Just assign it to a variable. Then use the variable. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Wed Mar 22 22:49:09 2017 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 22 Mar 2017 21:49:09 -0500 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: On Wed, Mar 22, 2017 at 7:30 AM, Rafael Knuth wrote: > thanks for your feedback! @boB > ...(it does what it's > supposed to do, but not sure if a pro would write it same way I did). I'll leave it to others to evaluate your function which I snipped as I am not a pro! ~(:>)) > > Besides that, I want to take it a step further and rewrite the > function above as a class, and I don't know how exactly how to do > this. I'm not sure if you read the entirety of my answer to your previous post. I tried to point out that you had some issues with how you were passing in arguments, and then not doing anything constructive with them. You might want to look that over again. For now I will give you something that will generate a shopping list without passing in any arguments, which seems to be mostly what you are trying to do. I am not trying to duplicate your work exactly, but here goes what I have for you: ---------------------------------------------------------------------------------- #!/usr/bin/env python3 class GroceryListMaker: # Explicit inheritance from "object" is optional in Py 3. def __init__(self): self.shopping_list = [] self.prompt = ('What food items would you like to buy?\n(Type "quit"' ' to exit): ') def make_shopping_list(self): while True: food = input(self.prompt) if food == 'quit': break else: self.shopping_list.append(food) def display_shopping_list(self): print('\n\nYour shopping list now has the following items:\n') for item_number, item in enumerate(self.shopping_list): print('%s. %s' % (item_number, item)) if __name__ == '__main__': my_shopping_list = GroceryListMaker() my_shopping_list.make_shopping_list() my_shopping_list.display_shopping_list() ---------------------------------------------------------------------------------- I won't claim that this is the greatest piece of code as I am a learner like yourself. But when I run the above I get: ---------------------------------------------------------------------------------- > python -i buy_food.py What food items would you like to buy? (Type "quit" to exit): spam What food items would you like to buy? (Type "quit" to exit): limberger cheese What food items would you like to buy? (Type "quit" to exit): rotten eggs What food items would you like to buy? (Type "quit" to exit): green ham What food items would you like to buy? (Type "quit" to exit): quit Your shopping list now has the following items: 0. spam 1. limberger cheese 2. rotten eggs 3. green ham >>> ---------------------------------------------------------------------------------- See if the above makes things any clearer. As for your efforts below, you are again failing to pass in the necessary arguments that you specify in __init__(). That is what your error traceback is trying to tell you. You had the same issue last time. What I am talking about I'll try to illustrate with a simple example: ---------------------------------------------------------------------------------- Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. py3: class TextRepeater: ... def __init__(self, text_to_repeat): ... self.text_to_repeat = text_to_repeat ... def echo_text(self): ... print(self.text_to_repeat) ... py3: text_repeater = TextRepeater('Is "Monty Python and the Holy Grail" great or what?') py3: text_repeater.echo_text() Is "Monty Python and the Holy Grail" great or what? py3: ---------------------------------------------------------------------------------- Does this make object initialization with a passed in argument any clearer? > (coding newbie pains ... I just learned the basics about classes in > Python, but nowhere could I find examples of how to properly > initialize classes, given that it operates solely with user input - > same goes with with calling that class properly). Here's how far I got > on my own: > > class FoodShopping(object): > def __init__ (self, create_shoppping_list, prompt, food, eat_food, > store_food): > self.create_shopping_list = create_shopping_list > self.prompt = prompt > self.food = food > self.eat_food = eat_food > self.store_food = store_food > > def ManageFood(self, create_shopping_list, prompt, food, eat_food, > store_food): > create_shopping_list = [] > prompt = ("Which foods would you like to purchase?\nEnter > 'quit' to exit. ") > food = input(prompt) > > while food != "quit": > create_shopping_list.append(food) > food = input(prompt) > > print("These are your foods on your shopping list: %s." % ", " > .join(create_shopping_list)) > eat_food = [] > store_food = [] > for food in create_shopping_list: > print("You bought this item: %s. " % (food)) > prompt = input("What would you like to do with it?\nEnter > 'eat' or 'store'. ") > if prompt == "eat": > eat_food.append(food) > elif prompt == "store": > store_food.append(food) > print("Food you want to eat now: %s." % (eat_food)) > print("Food you want to store: %s." % (store_food)) > > FoodShopping() > > That's the error message I get when executing my code: > > Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 > 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. >>>> > == RESTART: C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python Code/PPC_29.py == > Traceback (most recent call last): > File "C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python > Code/PPC_29.py", line 140, in > FoodShopping() > TypeError: __init__() missing 5 required positional arguments: > 'create_shoppping_list', 'prompt', 'food', 'eat_food', and > 'store_food' >>>> HTH! -- boB From mats at wichmann.us Wed Mar 22 20:20:03 2017 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 22 Mar 2017 18:20:03 -0600 Subject: [Tutor] Help with function scoping In-Reply-To: <437DA200-9760-40EB-A654-DF2FC0BEE1A3@icloud.com> References: <437DA200-9760-40EB-A654-DF2FC0BEE1A3@icloud.com> Message-ID: <54a851b4-db33-c75b-b8ff-15cbeda9933d@wichmann.us> On 03/22/2017 03:17 PM, Richard Mcewan wrote: > Hi > > I wonder if you can help. > > I'm confused about how functions should work. Below is some code I write to check my understanding. > > I'm expecting two functions to be defined. Then called. One returns a random number. The other user input (guessing the number). > > I expect the return values to act like variables that I can use in a while loop. > > The programme asks for the user input then crashes. The error report says 'NameError:The name 'userGuess' is not defined. > > My understanding is wrong somewhere. I thought functions would allow me to return values I could use elsewhere without having to define them initially. I.e. Encapsulation. > > I've looked for other examples but get the same issue. I expect a function to return a variable I can use elsewhere. Not sure how to do. In the case below I'm not sure how I can use the work of the function elsewhere. You mention "scoping", so... a variable defined in a particular scope is not visible outside that scope. That's fine, because you then return it, but what you're returning is the value, not the variable. You need to save that value. The "simple fix" is to assign the function returns to the variables you want, see below: > Advice welcome. > > Richard > > Using Pythonista App on iOS with Python 2.7 on iPhone 5s > > # coding: utf-8 > import random > > #guess number game > > #computer generates random number > def generateNumber(): > computerGuess = int(random.randrange(0,101)) > return computerGuess > > #get user > def getUser(): > userGuess = int(input('Guess a number')) > return userGuess > > #call for computer and user > generateNumber() > getUser() # try this: computerGuess = generateNumber() userGuess = getUser() # note these two names in the global scope are not # the same as the identical names in function # scopes, but there is no clash either, because # of scoping rules > > #loop to check guess and report > while userGuess != computerGuess: > if userGuess < computerGuess: > print('Too low') > getUser() > elif userGuess > computerGuess: > print('Too high') > getUser() > elif userGuess > computerGuess: > print('Correct!') > > #Add counter of guess later > > > Sent from my iPhone > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From mats at wichmann.us Wed Mar 22 23:56:11 2017 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 22 Mar 2017 21:56:11 -0600 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: <386a5cc5-3c30-6648-bd0d-73e79f718d72@wichmann.us> On 03/22/2017 06:30 AM, Rafael Knuth wrote: > thanks for your feedback! @boB > > I wrote a function that does exactly what I want, and that is: > Create a shopping list and then let the user decide which items (food) > are supposed to be instantly consumed and which ones stored. > > def ManageFood(): > create_shopping_list = [] > prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") > food = input(prompt) > > while food != "quit": > create_shopping_list.append(food) > food = input(prompt) > > print("These are your foods on your shopping list: %s." % ", " > .join(create_shopping_list)) > eat_food = [] > store_food = [] > for food in create_shopping_list: > print("You bought this item: %s. " % (food)) > prompt = input("What would you like to do with it?\nEnter > 'eat' or 'store'. ") > if prompt == "eat": > eat_food.append(food) > elif prompt == "store": > store_food.append(food) > print("Food you want to eat now: %s." % ", " .join(eat_food)) > print("Food you want to store: %s." % ", " .join(store_food)) > > ManageFood() > > PS: Please let me know if you have any suggestions how to write my > code above in a shorter, more elegant fashion (it does what it's > supposed to do, but not sure if a pro would write it same way I did). You could think here about how you described the food items: they have an attribute which is either eat or store... it's not just a (string) name, but also how you intend to categorize tht tiem. It's possible a dictionary - a collection of name/value pairs - could be a more natural way to capture the data than multiple lists. So perhaps a datastructure like: { ('asparagus', 'eat'), ('beans', 'store'), ... } Up to you, just an observation. > > Besides that, I want to take it a step further and rewrite the > function above as a class, and I don't know how exactly how to do > this. > (coding newbie pains ... I just learned the basics about classes in > Python, but nowhere could I find examples of how to properly > initialize classes, given that it operates solely with user input - > same goes with with calling that class properly). Here's how far I got > on my own: Rule 1: Python is not specifically an object-oriented language. If the problem you're trying to solve is best served by a class-based approach, by all means, it will work fine that way. But there's nothing /forcing/ you (unless it's a learning assignment, that is: "how do I do this using classes") to turn an implementation into a class. After that thought, what do you want the class to represent? The whole shopping cart? A single food item? The latter actually feels a bit more natural to me, but I'm not the one inventing the problem. On to some details. > > class FoodShopping(object): > def __init__ (self, create_shoppping_list, prompt, food, eat_food, > store_food): > self.create_shopping_list = create_shopping_list > self.prompt = prompt > self.food = food > self.eat_food = eat_food > self.store_food = store_food (a) you can store the prompt in the instance, sure, but the prompt is neither unique to the instance (which means it doesn't need to be there), nor is it really anything to do with the class, which means it doesn't really need to be a class variable either. (b) see above: eat vs store isn't really two different things, it's one - and maybe it's a boolean: eat = True vs eat = False. Though you might think of other states later, and then it's not a boolean any more. (c) probably what you wanted here was not to pass in the three list items, but to initialize them. And the other parameters perhaps aren't really things needed up front, so you might even end up with an initializer that looks like this: def __init__(self): self.create_shopping_list = [] self.eat_food = [] self.store_food = [] Like magic that would fix the initial error your program stopped on - the initializer wanted multiple args and didn't get them (see below). > def ManageFood(self, create_shopping_list, prompt, food, eat_food, > store_food): > create_shopping_list = [] > prompt = ("Which foods would you like to purchase?\nEnter > 'quit' to exit. ") This makes no sense... you're passing in "prompt", but then overriding it in the method. So why pass it in at all? > food = input(prompt) > > while food != "quit": > create_shopping_list.append(food) > food = input(prompt) > > print("These are your foods on your shopping list: %s." % ", " > .join(create_shopping_list)) > eat_food = [] > store_food = [] You already created instance variables create_shopping_list, eat_food and store_food. Don't redo those in the method, use the instance variables (self.create_shopping_list, self.eat_food, self.store_food). > for food in create_shopping_list: > print("You bought this item: %s. " % (food)) > prompt = input("What would you like to do with it?\nEnter > 'eat' or 'store'. ") > if prompt == "eat": > eat_food.append(food) > elif prompt == "store": > store_food.append(food) > print("Food you want to eat now: %s." % (eat_food)) > print("Food you want to store: %s." % (store_food)) all those references (create_shopping_list, eat_food, store_food) need to be self.x instead of x > > FoodShopping() This line creates an instance of the class. You need to do something with that instance object or it's just lost... typically something like: shopping = FoodShopping() Then, to the error: the call to instantiate the class causes, after the actual construction is done, the initializer (__init__) method to be called. You declared that method to take six arguments, one of which is the implied instance reference (self), so you need to supply the other five arguments to the call to instantiate - that's how Python is set up. Python isn't, say C# - where everything has to happen inside a class definition, even the main method that causes the real work to happen. A class definition does no actual work, it just causes a class object to be created, and a reference to that object to be assigned to the name you gave the class. Then when you "call" the class through that variable, the work starts happening. > > That's the error message I get when executing my code: > > Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 > 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. >>>> > == RESTART: C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python Code/PPC_29.py == > Traceback (most recent call last): > File "C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python > Code/PPC_29.py", line 140, in > FoodShopping() > TypeError: __init__() missing 5 required positional arguments: > 'create_shoppping_list', 'prompt', 'food', 'eat_food', and > 'store_food' And in the end, your program does nothing... you instantiate a class, then don't save any reference to the instance object that will be created, which means it will just be lost (no reference -> garbage collected). And you have a method in the class which does all the interesting work, but the method is never called. I know this is a lot of comments without providing a actual fix of the code, but maybe after thinking about some of this stuff you'll come back with a new iteration we can comment on. Good luck! From alan.gauld at yahoo.co.uk Thu Mar 23 05:58:38 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 23 Mar 2017 09:58:38 +0000 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: On 22/03/17 12:30, Rafael Knuth wrote: > I wrote a function that does exactly what I want, and that is: > Create a shopping list and then let the user decide which items (food) > are supposed to be instantly consumed and which ones stored. That's a good start, because it means you understand your requirements. > def ManageFood(): > create_shopping_list = [] > prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") > food = input(prompt) > > while food != "quit": > create_shopping_list.append(food) > food = input(prompt) > > print("These are your foods on your shopping list: %s." % ", " > .join(create_shopping_list)) > eat_food = [] > store_food = [] > for food in create_shopping_list: > print("You bought this item: %s. " % (food)) > prompt = input("What would you like to do with it?\nEnter > 'eat' or 'store'. ") > if prompt == "eat": > eat_food.append(food) > elif prompt == "store": > store_food.append(food) > print("Food you want to eat now: %s." % ", " .join(eat_food)) > print("Food you want to store: %s." % ", " .join(store_food)) > > ManageFood() > > PS: Please let me know if you have any suggestions how to write my > code above in a shorter, more elegant fashion The first thing to say is that shorter does not mean more elegant, often more elegant code is shorter, but sometimes its longer. Elegance is more about structuring the code into clearly defined pieces, avoiding redundancy and repetition and encouraging reuse. And it should be easy to read and understand too! If converting from a function to classes its very common for the classes to have a lot more code than the original function. But you trade that for more reusable code. Which begs the question of whether you need classes? - are you likely to reuse the class? If not it may not be worth the effort. (Although it might still be worth doing if it clarifies the code and makes it easier to maintain - will it be maintained? Or is it throw-away code?) But let's assume this is just a training exercise and you want to convert to OOP just for the experience. > ... not sure if a pro would write it same way I did). The answer is no, for several reasons, but probably not the ones you expect! > Besides that, I want to take it a step further and rewrite the > function above as a class, and I don't know how exactly how to do > this. OK, I'll discuss one approach to this below, but there are many OOP "methodologies", this is just one that I personally find works for small/medium projects. > (coding newbie pains ... I just learned the basics about classes in > Python, but nowhere could I find examples of how to properly > initialize classes, given that it operates solely with user input - > same goes with with calling that class properly). There is a very important programming principle (not just for classes) that says you should separate out the data processing from the user interaction. So your initial design concept is flawed - the first reason a pro would not write your code the way you did. So maybe you need a separate class (or just a function) to represent the UI? That class can then interact5 with your data models. And talking about your data models... Classes represent objects, things. Things that can do stuff. So you should not normally have classes that *manage* other things, the things should manage themselves. The exception is when you have a container like your shopping list. The list is a single thing (a class) that should manage itself. It should control what goes in and out of the list but it should not be manipulating its contents, it should be providing access to its contents for the user of the list to manipulate. So it looks like we have maybe 3 kinds of object here. 1) The UI - could just be a function 2) The list - almost certainly a class 3) the items in the list - probably a class but we need to know more To decide what these classes look like its often useful to imagine that they already exist and think about how you want to use them. (The formal way to do this is to create a CRC card - Google it if interested) Lets assume the UI is a function and that it is using the other 2 classes. The structure of our code is roughly: # create and populate a FoodList lst = FoodList() while True: item = input('What is the item? (quit to exit) ') if item == 'quit': break food = Food(item) lst.add(food) print(lst.contents()) # Separate thev list into eats and stores eats = FoodList() store = FoodList() for food in lst.contents(): action = input('What action do you want for %s?' % food.name) if action == 'eat': eats.add(food) if action == 'store': store.add(food) print('Items to eat now: %s' % eats.contents()) print('Items to store: %s' % store.contents()) Looking at that code we see that we have 3 lists of food. We also see that a FoodList should be able to add items and return its contents. We also see that the Food objects don't do much except store their name, so probably we can just use strings and not bother with a class. So the final program consists of a GUI function (that looks a lot like the pseudo code above) and a single class: class FoodList: def __init__(self): self.data = [] def add(self, item): self.data.append(item) def contents(): return self.data[:] # return a copy Of course that's not doing anything that a normal list couldn't do, so we don't really need a class at all in this case, but hopefully, as a learning exercise, it shows the kind of thought process you might use. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From richmcewan at icloud.com Thu Mar 23 06:15:17 2017 From: richmcewan at icloud.com (Richard Mcewan) Date: Thu, 23 Mar 2017 10:15:17 +0000 Subject: [Tutor] Help with function scoping Message-ID: <2D71400E-8D98-47CC-89F3-EA65E6E401F3@icloud.com> Hi Thanks Mats, Joel and Alan for helpful advice. This code (below) behaves as I wanted now. And think I see where I was going wrong with functions. Thank you very much. Richard Ps I'll reflect on appropriate variable names also. # coding: utf-8 import random #guess number game #computer generates random number def generateNumber(): computerGuess = int(random.randrange(0,101)) return computerGuess #get user def getUser(): userGuess = int(raw_input('Guess a number')) return userGuess #call for computer and user computerGuess = generateNumber() userGuess = getUser() #loop to check guess and report while userGuess != computerGuess: if userGuess < computerGuess: print('Too low') userGuess = getUser() elif userGuess > computerGuess: print('Too high') userGuess = getUser() print('Correct!') #Add counter of guess later. Sent from my iPhone From alan.gauld at yahoo.co.uk Thu Mar 23 08:38:55 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 23 Mar 2017 12:38:55 +0000 Subject: [Tutor] Help with function scoping In-Reply-To: <2D71400E-8D98-47CC-89F3-EA65E6E401F3@icloud.com> References: <2D71400E-8D98-47CC-89F3-EA65E6E401F3@icloud.com> Message-ID: On 23/03/17 10:15, Richard Mcewan wrote: > #loop to check guess and report > while userGuess != computerGuess: > if userGuess < computerGuess: > print('Too low') > userGuess = getUser() > elif userGuess > computerGuess: > print('Too high') > userGuess = getUser() One tiny tweak would be to remove the userGuess = getUser() lines from the if/elif structure and just have a single assignment at the end of the loop. It just saves duplication and so means less work if you ever have to change that line. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From richmcewan at icloud.com Thu Mar 23 13:38:13 2017 From: richmcewan at icloud.com (Richard Mcewan) Date: Thu, 23 Mar 2017 17:38:13 +0000 Subject: [Tutor] Help with scoping Message-ID: <9E1AC648-B7EA-460A-8D2A-4803566A6303@icloud.com> Hi Thanks Alan and all. I've incorporated your points. I've explored how values are returned and used by functions. I switched to Python to check a Swift3 bug and I think I can see a number of issues more clearly now. I put the count and call for next user guess back a tab at the end of the while loop instead of duplicating at the end of if conditions. Appreciate the help. Will come back to the list with new topics in the future no doubt and look forward to mailings. Thanks Richard Code from 2.7 Python running on Pythonista iOS app. # coding: utf-8 import random #guess number game #number to guess def generateNumber(): someValue = int(random.randrange(0,101)) return someValue #sic #get user guess def getUser(): userGuess = int(raw_input('Guess a number: ')) return userGuess #loop to check guess and report def main(): count = 0 #call for hidden number and user 1st guess hiddenNumber = generateNumber() userGuess = getUser() #main loop to report on guess while userGuess != hiddenNumber: if userGuess < hiddenNumber: print('Too low\n') elif userGuess > hiddenNumber: print('Too high\n') #note new position count +=1 userGuess = getUser() print('Correct! ' , count+1, 'guesses') main() #future: deal with bad input. #invite user to set size of game. #Range of fun messages reported. #Record best scores. From robertvstepp at gmail.com Fri Mar 24 17:41:39 2017 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 24 Mar 2017 16:41:39 -0500 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: I'm forwarding this to Tutor. Please respond to the whole group and not just me personally, so you can have access to the experts as well as allowing all of us learners the opportunity to learn more. I can't respond now, but will try to do so later. On Fri, Mar 24, 2017 at 6:51 AM, Rafael Knuth wrote: > Thank you so much for your help. > I have a question: When creating an instance of GroceryListMaker, you are using: > > if __name__ == "__main__": > > What is that specifically for? > I tested your code and both worked, with and without > if __name__ == "__main__": > > a) > > if __name__ == "__main__": > my_shopping_list = GroceryListMaker() > my_shopping_list.make_shopping_list() > my_shopping_list.display_shopping_list() > > b) > > my_shopping_list = GroceryListMaker() > my_shopping_list.make_shopping_list() > my_shopping_list.display_shopping_list() > > Can you explain? > Thanks :) > >> class GroceryListMaker: # Explicit inheritance from "object" is >> optional in Py 3. >> def __init__(self): >> self.shopping_list = [] >> self.prompt = ('What food items would you like to buy?\n(Type "quit"' >> ' to exit): ') >> >> def make_shopping_list(self): >> while True: >> food = input(self.prompt) >> if food == 'quit': >> break >> else: >> self.shopping_list.append(food) >> >> def display_shopping_list(self): >> print('\n\nYour shopping list now has the following items:\n') >> for item_number, item in enumerate(self.shopping_list): >> print('%s. %s' % (item_number, item)) >> >> if __name__ == '__main__': >> my_shopping_list = GroceryListMaker() >> my_shopping_list.make_shopping_list() >> my_shopping_list.display_shopping_list() -- boB From robertvstepp at gmail.com Fri Mar 24 17:42:14 2017 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 24 Mar 2017 16:42:14 -0500 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: I'm forwarding this to Tutor. Please respond to the whole group and not just me personally, so you can have access to the experts as well as allowing all of us learners the opportunity to learn more. On Fri, Mar 24, 2017 at 9:05 AM, Rafael Knuth wrote: > I have another question :) > I noticed that you split your class into three methods: > > def __init__(self): > # initialize instances of class > > def make_shopping_list(self): > # input > > def display_shopping_list(self): > # output > > I was wondering what common practices are to structure a class? > Thanks :) > > class GroceryListMaker: > def __init__(self): > self.shopping_list = [] > self.prompt = ("what food items would you like to buy?\nType > 'quit to exit: ") > > def make_shopping_list(self): > while True: > food = input(self.prompt) > if food == "quit": > break > else: > self.shopping_list.append(food) > > def display_shopping_list(self): > print("\n\nYour shopping list now has the following items:\n") > for item_number, item in enumerate(self.shopping_list): > print("%s. %s" % (item_number, item)) > > if __name__ == "__main__": > my_shopping_list = GroceryListMaker() > my_shopping_list.make_shopping_list() > my_shopping_list.display_shopping_list() -- boB From alan.gauld at yahoo.co.uk Fri Mar 24 21:32:52 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 25 Mar 2017 01:32:52 +0000 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: On 24/03/17 21:41, boB Stepp wrote: >> I have a question: When creating an instance of GroceryListMaker, you are using: >> >> if __name__ == "__main__": >> >> What is that specifically for? Its a common trick in Python that enables a single file to act as both a module and a program. When a script is imported Python sets its __name__ attribute to the name of the module. When a script is executed directly Python sets its __name__ to __main__. Thus >> if __name__ == "__main__": >> my_shopping_list = GroceryListMaker() >> my_shopping_list.make_shopping_list() >> my_shopping_list.display_shopping_list() Means only execute the three indented lines if running the file directly, do not execute them if the file is being imported. Whereas: >> my_shopping_list = GroceryListMaker() >> my_shopping_list.make_shopping_list() >> my_shopping_list.display_shopping_list() will result in the three lines being executed regardless of whether the file is imported or executed directly. You will see this idiom in many files even when they are not intended to be run directly because it is common to create a tests or a demonstration that will run when executed directly. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 24 21:40:07 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 25 Mar 2017 01:40:07 +0000 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: On 24/03/17 21:42, boB Stepp wrote: >> I noticed that you split your class into three methods: Many real world classes have a lot more than 3 methods. >> def __init__(self): >> # initialize instances of class >> >> def make_shopping_list(self): >> # input >> >> def display_shopping_list(self): >> # output >> >> I was wondering what common practices are to structure a class? I'm not sure exactly what you mean and there are no rules but some programmers group related methods (as Bob did albeit with only one method per "group") Some possible categories: - initialization/destruction - input/output - calculations - event handlers (eg in a GUI) - operations (eg __add__, __sub__, __str__ etc) - (internal) helpers. But others prefer to order their methods alphabetically. Or to sort them alphabetically within the groups. There are no hard and fast rules. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Fri Mar 24 23:08:12 2017 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 24 Mar 2017 22:08:12 -0500 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: On Fri, Mar 24, 2017 at 6:51 AM, Rafael Knuth wrote: > Thank you so much for your help. > I have a question: When creating an instance of GroceryListMaker, you are using: > > if __name__ == "__main__": > > What is that specifically for? > I tested your code and both worked, with and without > if __name__ == "__main__": > > a) > > if __name__ == "__main__": > my_shopping_list = GroceryListMaker() > my_shopping_list.make_shopping_list() > my_shopping_list.display_shopping_list() > > b) > > my_shopping_list = GroceryListMaker() > my_shopping_list.make_shopping_list() > my_shopping_list.display_shopping_list() > > Can you explain? Alan in his post pretty much said it all. I do this to cover files that I may want to reuse, that is, import classes, functions, etc. from them in future programs without running the initializer code after the if statement. The main reason that I am doing this construction almost all of the time now, however, is that I have been striving to write unit tests for my code. When I run a test suite I don't want the "if __name__ ..." code to run in the files I am testing. However, in one of my unit test files I will similarly have: if __name__ == '__main__': unittest.main() which will run the tests when the test file is run directly. See https://docs.python.org/3/library/unittest.html for the Python 3 docs on the unittest module. From robertvstepp at gmail.com Fri Mar 24 23:14:46 2017 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 24 Mar 2017 22:14:46 -0500 Subject: [Tutor] Using Class Properly - early beginner question In-Reply-To: References: Message-ID: On Fri, Mar 24, 2017 at 9:05 AM, Rafael Knuth wrote: > I have another question :) > I noticed that you split your class into three methods: > > def __init__(self): > # initialize instances of class > > def make_shopping_list(self): > # input > > def display_shopping_list(self): > # output > > I was wondering what common practices are to structure a class? > Thanks :) Like Alan is his response, I am not totally certain what you are actually asking. If the question is, "Why didn't I write a single method for all of the above instead of three methods?", then it is because each method/function should have (if possible) a single, well-defined purpose to accomplish. And I think you have gotten that by how you replaced my actual code with "#initialize instances of class", "#input" and "#output". This makes things easier for people to understand my code, breaks apart unnecessary interdependencies that would otherwise exist in "big" methods/functions, makes it easier for me to write tests for each function without having to worry about unnecessary dependencies that I will have simulate or mock, etc. -- boB From kevinpeterodoherty at gmail.com Sat Mar 25 06:01:21 2017 From: kevinpeterodoherty at gmail.com (Peter O'Doherty) Date: Sat, 25 Mar 2017 10:01:21 +0000 Subject: [Tutor] Function question Message-ID: <9e8a0cc7-d7bc-f61b-fc8b-a3379ac7c07c@gmail.com> Hi, Apologies for the very basic question but could anyone explain the behaviour of these two functions (in Python3.5)? def myFunc(num): for i in range(num): print(i) print(myFunc(4)) 0 1 2 3 None #why None here? def myFunc(num): for i in range(num): return i print(myFunc(4)) 0 #why just 0? Many thanks, Peter From alan.gauld at yahoo.co.uk Sat Mar 25 07:17:29 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 25 Mar 2017 11:17:29 +0000 Subject: [Tutor] Function question In-Reply-To: <9e8a0cc7-d7bc-f61b-fc8b-a3379ac7c07c@gmail.com> References: <9e8a0cc7-d7bc-f61b-fc8b-a3379ac7c07c@gmail.com> Message-ID: On 25/03/17 10:01, Peter O'Doherty wrote: > def myFunc(num): > for i in range(num): > print(i) > > print(myFunc(4)) > 0 > 1 > 2 > 3 > None #why None here? Because your function does not have an explicit return value so Python returns its default value - None. So the print() inside the function body prints the 0-3 values then the function terminates and returns the (default) None to your top level print. > def myFunc(num): > for i in range(num): > return i > > print(myFunc(4)) > 0 #why just 0? Because return always returns from the function immediately. So you call the function, it enters the loop, sees the return for the first element and exits. The print() then prints that returned value. The preferred method to do what I think you were expecting is to build a list: def anotherFunction(num): result = [] for i in range(num): result.append(i) return result Which is more concisely written using a list comprehension but that would hide the general point - that you should accumulate results in a collection if you want to return more than a single value. To print the result you would typically use the string.join() method: print(' '.join(anotherFunction(4)) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From bzjackson316 at gmail.com Sat Mar 25 00:29:25 2017 From: bzjackson316 at gmail.com (Braxton Jackson) Date: Sat, 25 Mar 2017 00:29:25 -0400 Subject: [Tutor] Retrieving DropDown List Values In-Reply-To: References: Message-ID: Is there a simple command for retrieving the chosen value a user inputs from a dropdown list? I am new to Python and cant seem to find a good tutorials link on retreiving drop down values. From alan.gauld at yahoo.co.uk Sat Mar 25 09:14:25 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 25 Mar 2017 13:14:25 +0000 Subject: [Tutor] Retrieving DropDown List Values In-Reply-To: References: Message-ID: On 25/03/17 04:29, Braxton Jackson wrote: > Is there a simple command for retrieving the chosen value a user inputs > from a dropdown list? I am new to Python and cant seem to find a good > tutorials link on retreiving drop down values. That all depends on which GUI toolkit you are using. The standard Python GUI is Tkinter but it does not have a native drop-down list component, you need to use the ComboBox from the ttk module (or the ComboBox from the Tix module) for that. Alternatively, you can use another third party version such as the one in PMW. But these all work differently. So first you need to tell us which GUI toolkit you are using? And ideally, a bit more about what you are trying to do? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From gvmcmt at gmail.com Sat Mar 25 08:04:57 2017 From: gvmcmt at gmail.com (Sri Kavi) Date: Sat, 25 Mar 2017 17:34:57 +0530 Subject: [Tutor] Function question In-Reply-To: <9e8a0cc7-d7bc-f61b-fc8b-a3379ac7c07c@gmail.com> References: <9e8a0cc7-d7bc-f61b-fc8b-a3379ac7c07c@gmail.com> Message-ID: On Sat, Mar 25, 2017 at 3:31 PM, Peter O'Doherty wrote: > > def myFunc(num): > for i in range(num): > print(i) > > print(myFunc(4)) > 0 > 1 > 2 > 3 > None #why None here? > > Because there are two print() functions, one inside the function and another outside. When a function does not return anything, an implicit ?return None? statement gets added to the end of the function. The inner myFunc(4) is printing out 0, 1, 2, 3 and it also returns None which gets printed by the outer print() function. > > def myFunc(num): > for i in range(num): > return i > > print(myFunc(4)) > 0 #why just 0? The return statement causes the loop to stop and the function to exit and returns 0 to its caller which is the outer print() function. Hope that helps. Sri > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From poojabhalode11 at gmail.com Mon Mar 27 12:22:24 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Mon, 27 Mar 2017 12:22:24 -0400 Subject: [Tutor] Scrollbar Message-ID: Hi, I am going wrong somewhere in the following code. here is given a simplified code of the work that I am trying to do. The scrollbar goes not work in the window. Can someone please let me know what the issue is. Thank you Code: from Tkinter import * root = Tk() root.geometry("500x400") scrollbar = Scrollbar(root, orient = "vertical") scrollbar.grid(column = 5,sticky = W) for i in range(0,20): Label(root, text = i).grid(row = 1+i, column = 1, sticky = W) root.mainloop() From alan.gauld at yahoo.co.uk Mon Mar 27 14:38:57 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 27 Mar 2017 19:38:57 +0100 Subject: [Tutor] Scrollbar In-Reply-To: References: Message-ID: On 27/03/17 17:22, Pooja Bhalode wrote: > The scrollbar goes not work in the window. Define 'not work'? You haven't connected it to anything and it doesn't respond to any events so what kind of work did you expect it to do? I assume it draws itself on screen and the scroll buttons operate OK when you click them? To make it do anything else you need to connect it to a scrollable widget or bind some actions to its events. Which Tkinter tutorial are you using? It should have explained how to do that. > from Tkinter import * > > root = Tk() > root.geometry("500x400") > scrollbar = Scrollbar(root, orient = "vertical") > scrollbar.grid(column = 5,sticky = W) > > for i in range(0,20): > Label(root, text = i).grid(row = 1+i, column = 1, sticky = W) > > root.mainloop() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From rafael.knuth at gmail.com Tue Mar 28 12:45:47 2017 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Tue, 28 Mar 2017 18:45:47 +0200 Subject: [Tutor] FUNCTIONS vs. CLASSES (early beginner questions) Message-ID: Question: When should I use functions? When should I use classes? I wrote my program twice: as a function and as a class (I did so for educational purposes, to better understand both concepts). Both programs do exactly the same, and the work neatly. Can you advise when I should use functions and when it's appropriate to make use of classes? Any feedback rgrd. my code? Anything I can improve? Thanks! # FUNCTION def ManageFood(): shopping_list = [] prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") food = input(prompt) while food != "quit": shopping_list.append(food) food = input(prompt) print("These are your foods on your shopping list: %s." % ", ".join(shopping_list)) eat_food = [] store_food = [] for food in shopping_list: print("You bought: %s. " % (food)) prompt = input("What would you like to do with it?\nEnter 'eat' or 'store'. ") if prompt == "eat": eat_food.append(food) elif prompt == "store": store_food.append(food) print("Food for instant consupmtion: %s." % ", " .join(eat_food)) print("Food for storage: %s." % ", " .join(store_food)) ManageFood() # CLASS class FoodManager: def __init__(self): self.shopping_list = [] self.user_input = ("Which foods would you like to purchase?\nEnter 'quit' to exit? ") self.eat_food = [] self.store_food = [] self.user_choice = ("What would you like to do with it?\nEnter 'eat' or 'store'. ") def purchase_food(self): get_food = input(self.user_input) while get_food != "quit": self.shopping_list.append(get_food) get_food = input(self.user_input) print("These are your foods on your shopping list: %s." % ", ".join(self.shopping_list)) def manage_food(self): for item in self.shopping_list: print("You bought: %s. " % (item)) eat_or_store = input(self.user_choice) if eat_or_store == "eat": self.eat_food.append(item) elif eat_or_store == "store": self.store_food.append(item) print("Food for instant consumption: %s." % ", ".join(self.eat_food)) print("Food for storage: %s." % ", ".join(self.store_food)) if __name__ == "__main__": my_food = FoodManager() my_food.purchase_food() my_food.manage_food() From elo.okonkwo at gmail.com Tue Mar 28 10:56:16 2017 From: elo.okonkwo at gmail.com (Elo Okonkwo) Date: Tue, 28 Mar 2017 15:56:16 +0100 Subject: [Tutor] Merge Sort Algorithm Message-ID: Can someone pls explain this Merge Sort Algorithm, especially the Recursive bit of it. def mergeSort(alist): print("Splitting ",alist) if len(alist)>1: mid = len(alist)//2 lefthalf = alist[:mid] righthalf = alist[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: alist[k]=lefthalf[i] i=i+1 else: alist[k]=righthalf[j] j=j+1 k=k+1 while i < len(lefthalf): alist[k]=lefthalf[i] i=i+1 k=k+1 while j < len(righthalf): alist[k]=righthalf[j] j=j+1 k=k+1 print("Merging ",alist) alist = [54,26,93,17,77,31,44,55,20] mergeSort(alist) print(alist) From elo.okonkwo at gmail.com Tue Mar 28 10:59:49 2017 From: elo.okonkwo at gmail.com (Elo Okonkwo) Date: Tue, 28 Mar 2017 15:59:49 +0100 Subject: [Tutor] Merge Sort Algorithm In-Reply-To: References: Message-ID: This is the Result form that piece of code: Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20] Splitting [54, 26, 93, 17] Splitting [54, 26] Splitting [54] Merging [54] Splitting [26] Merging [26] Merging [26, 54] Splitting [93, 17] Splitting [93] Merging [93] Splitting [17] Merging [17] Merging [17, 93] Merging [17, 26, 54, 93] Splitting [77, 31, 44, 55, 20] Splitting [77, 31] Splitting [77] Merging [77] Splitting [31] Merging [31] Merging [31, 77] Splitting [44, 55, 20] Splitting [44] Merging [44] Splitting [55, 20] Splitting [55] Merging [55] Splitting [20] Merging [20] Merging [20, 55] Merging [20, 44, 55] Merging [20, 31, 44, 55, 77] Merging [17, 20, 26, 31, 44, 54, 55, 77, 93] [17, 20, 26, 31, 44, 54, 55, 77, 93] I have never been more confused!!!! On Tue, Mar 28, 2017 at 3:56 PM, Elo Okonkwo wrote: > Can someone pls explain this Merge Sort Algorithm, especially the > Recursive bit of it. > > def mergeSort(alist): > print("Splitting ",alist) > if len(alist)>1: > mid = len(alist)//2 > lefthalf = alist[:mid] > righthalf = alist[mid:] > > mergeSort(lefthalf) > mergeSort(righthalf) > > i=0 > j=0 > k=0 > while i < len(lefthalf) and j < len(righthalf): > if lefthalf[i] < righthalf[j]: > alist[k]=lefthalf[i] > i=i+1 > else: > alist[k]=righthalf[j] > j=j+1 > k=k+1 > > while i < len(lefthalf): > alist[k]=lefthalf[i] > i=i+1 > k=k+1 > > while j < len(righthalf): > alist[k]=righthalf[j] > j=j+1 > k=k+1 > print("Merging ",alist) > > alist = [54,26,93,17,77,31,44,55,20] > mergeSort(alist) > print(alist) > From elo.okonkwo at gmail.com Tue Mar 28 11:07:07 2017 From: elo.okonkwo at gmail.com (Elo Okonkwo) Date: Tue, 28 Mar 2017 16:07:07 +0100 Subject: [Tutor] Merge Sort Algorithm In-Reply-To: References: Message-ID: This is the Result of that of the Merge Sort Function: I have never been more confused!!, practically spent the whole day on this piece of code: Splitting [54, 26, 93, 17, 77, 31, 44, 55, 20] Splitting [54, 26, 93, 17] Splitting [54, 26] Splitting [54] Merging [54] Splitting [26] Merging [26] Merging [26, 54] Splitting [93, 17] Splitting [93] Merging [93] Splitting [17] Merging [17] Merging [17, 93] Merging [17, 26, 54, 93] Splitting [77, 31, 44, 55, 20] Splitting [77, 31] Splitting [77] Merging [77] Splitting [31] Merging [31] Merging [31, 77] Splitting [44, 55, 20] Splitting [44] Merging [44] Splitting [55, 20] Splitting [55] Merging [55] Splitting [20] Merging [20] Merging [20, 55] Merging [20, 44, 55] Merging [20, 31, 44, 55, 77] Merging [17, 20, 26, 31, 44, 54, 55, 77, 93] [17, 20, 26, 31, 44, 54, 55, 77, 93] On Tue, Mar 28, 2017 at 3:56 PM, Elo Okonkwo wrote: > Can someone pls explain this Merge Sort Algorithm, especially the Recursive > bit of it. > > def mergeSort(alist): > print("Splitting ",alist) > if len(alist)>1: > mid = len(alist)//2 > lefthalf = alist[:mid] > righthalf = alist[mid:] > > mergeSort(lefthalf) > mergeSort(righthalf) > > i=0 > j=0 > k=0 > while i < len(lefthalf) and j < len(righthalf): > if lefthalf[i] < righthalf[j]: > alist[k]=lefthalf[i] > i=i+1 > else: > alist[k]=righthalf[j] > j=j+1 > k=k+1 > > while i < len(lefthalf): > alist[k]=lefthalf[i] > i=i+1 > k=k+1 > > while j < len(righthalf): > alist[k]=righthalf[j] > j=j+1 > k=k+1 > print("Merging ",alist) > > alist = [54,26,93,17,77,31,44,55,20] > mergeSort(alist) > print(alist) From alan.gauld at yahoo.co.uk Tue Mar 28 14:04:14 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 28 Mar 2017 19:04:14 +0100 Subject: [Tutor] FUNCTIONS vs. CLASSES (early beginner questions) In-Reply-To: References: Message-ID: On 28/03/17 17:45, Rafael Knuth wrote: > Question: When should I use functions? > When should I use classes? Thee is no definitive answer but here are some guidelines: 1) Many instances -> class 2) Many methods sharing the same data -> class 3) An algorithm that has no side effects -> a function Very often we start with a function then realize it would be better in a class. In general classes need more code but provide more maintainable and reusable solutions. so on a bigger project classes are likely to be a better option. Pythons module/package mechanism is quite powerful so often we don't need classes where other languages would use them. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Tue Mar 28 14:08:43 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 28 Mar 2017 19:08:43 +0100 Subject: [Tutor] Merge Sort Algorithm In-Reply-To: References: Message-ID: On 28/03/17 15:56, Elo Okonkwo wrote: > Can someone pls explain this Merge Sort Algorithm, You can try reading this generic explanation. It's not Python but the explanation seems fairly clear. http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Sorting/mergeSort.htm HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Tue Mar 28 20:36:37 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 29 Mar 2017 11:36:37 +1100 Subject: [Tutor] Merge Sort Algorithm In-Reply-To: References: Message-ID: <20170329003637.GG27969@ando.pearwood.info> On Tue, Mar 28, 2017 at 03:56:16PM +0100, Elo Okonkwo wrote: > Can someone pls explain this Merge Sort Algorithm, especially the Recursive > bit of it. Take a pack of cards and shuffle them. Now you want to sort the cards. Put the cards down in a pile in front of you and think about sorting it. There are 52 cards in a Western deck of cards, so that's a lot of cards to sort. Let's make the job easier: (1) Split the deck into two piles, half in each pile. Now you only have to sort 26 cards at a time, which is much easier. (2) After you sort the first pile of 26, and then sort the second pile of 26, then you merge the two piles, keeping the same order: Turn the piles upside down, turn over the top card of each pile so you can see it, and start moving cards from the two piles to a third. Pick whichever card is smaller, move it to pile number 3, then turn over the next card so you can see what it is. Repeat until all the cards from the two piles are merged into a single pile, which is sorted. Now comes the recursive step. (3) In step 1, I said that sorting 26 cards is easier than sorting 52 cards. This is true, but sorting 26 cards is still not that much fun. Let's make it easier: split the pile of 26 cards into two halves, and sort each half. Then merge the two halves together, and your pile of 26 cards is sorted. Recursive step: (4) In step 3 I said that sorting 13 cards is easier than sorting 26 cards. This is true, but sorting 13 cards is still not that much fun. Let's make it easier: split the pile of 13 cards into two (nearly) equal halves, and sort each half. Then merge the two halves together, and your pile of 13 cards is sorted. Recursive step: (5) In step 4 I said that sorting 7 cards is easier than sorting 13 cards. This is true, but sorting 7 cards is still not that much fun. Let's make it easier: split the pile of 7 cards into two (nearly) equal halves, and sort each half. Then merge the two halves together, and your pile of 7 cards is sorted. (6) In step 5 I said that sorting 4 cards is easier than sorting 7 cards. This is true, but sorting 4 cards is still not that much fun. Let's make it easier: split the pile of 4 cards into two (nearly) equal halves, and sort each half. Then merge the two halves together, and your pile of 4 cards is sorted. (7) In step 6 I said that sorting 2 cards is easier than sorting 4 cards. This is true, but sorting 2 cards is still not that much fun. Let's make it easier: split the pile of 2 cards into two (nearly) equal halves, and sort each half. Then merge the two halves together, and your pile of 2 cards is sorted. (8) In step 7 I said that sorting 1 card is easier than sorting 2 cards. This is true, because 1 card is automatically sorted, and I don't have to think about it at all. So merge sort takes a big job (sorting 52 cards) and repeatedly splits it into two smaller jobs, until the job is so simple even a computer can do it: sorting 1 card takes no brains at all. Then it merges 1 card and 1 card together, keeping them in order, to get two. Then it goes back to the other pair of 1 card piles, and merges them. Then it merges the two piles of two cards to get a pile of four cards, and so on, until it ends up merging two sorted piles of 26 cards, and then the job is done. You should actually try this as an exercise. Literally get a pile of cards and go through the steps until it makes sense. For a *person*, this is not an efficient way to sort cards, but for computers it is very efficient, especially if you had millions of cards to sort. -- Steve From rafael.knuth at gmail.com Wed Mar 29 10:33:20 2017 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Wed, 29 Mar 2017 16:33:20 +0200 Subject: [Tutor] super constructor usage Message-ID: I am trying to wrap my head around the super constructor. Simple example: class A: def __init__(self): print("world") class B(A): def __init__(self): print("hello") super(B, self).__init__() B() Then I changed the parent class A like this, as I wanted to test how the code would look like if I passed arguments: class A: def __init__(self, message): self.message = message print(message) I then modified the child class B like this: class B(A): def __init__(self, message): print("This is the message from your parent class A:") super(B, self).__init__(message) B("BlaBla") That works, however I am not sure about what exactly happens inside the code. What I am concerned about is whether the argument is being actually inherited from the parent class A or does B overwrite the argument. Can anyone advise what the correct solution would be (in case mine is wrong). Thank you. From alan.gauld at yahoo.co.uk Wed Mar 29 17:32:52 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 29 Mar 2017 22:32:52 +0100 Subject: [Tutor] super constructor usage In-Reply-To: References: Message-ID: On 29/03/17 15:33, Rafael Knuth wrote: > I am trying to wrap my head around the super constructor. This is one of these cases where it matters whether you are using Python v2 or v3. Use of super in v3 is much easier. It looks from your examples like you are using v2 but it would be good to confirm that. > class A: > def __init__(self): > print("world") > > class B(A): > def __init__(self): > print("hello") > super(B, self).__init__() > > B() > > Then I changed the parent class A like this, as I wanted to test how > the code would look like if I passed arguments: > > class A: > def __init__(self, message): > self.message = message > print(message) > > I then modified the child class B like this: > > class B(A): > def __init__(self, message): > print("This is the message from your parent class A:") > super(B, self).__init__(message) > > B("BlaBla") > > That works, however I am not sure about what exactly happens inside the code. Yes, you have the mechanism right. As to what exactly happens inside the interpreter I'll leave that for those who care about such things :-) > What I am concerned about is whether the argument is being actually > inherited from the parent class A or does B overwrite the argument. The argument is just a parameter of the init() method like any other argument. It is effectively a local variable. The self.message attribute however is instantiated in A and inherited by B. (At least conceptually. I'll let the interpreter gurus answer how it work in the implementation) Thus in B you could access self.message directly - and in a normal method that might be the right thing to do. But in a constructor/initializer you should leave the initializing to super() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Wed Mar 29 21:13:38 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 30 Mar 2017 12:13:38 +1100 Subject: [Tutor] super constructor usage In-Reply-To: References: Message-ID: <20170330011337.GI27969@ando.pearwood.info> On Wed, Mar 29, 2017 at 04:33:20PM +0200, Rafael Knuth wrote: > I am trying to wrap my head around the super constructor. Simple example: > > class A: > def __init__(self): > print("world") > > class B(A): > def __init__(self): > print("hello") > super(B, self).__init__() If you are using Python 2, this cannot work. You cannot use super() inside "classic classes" in Python 2, it will fail with TypeError. To make this work in Python 2, the class A needs to inherit from object: class A(object): ... So I think you are using Python 3. In Python 3 super() is much easier to use, as there is a special shortcut: # like super(B, self).__init__() super().__init__() > B() > > Then I changed the parent class A like this, as I wanted to test how > the code would look like if I passed arguments: > > class A: > def __init__(self, message): > self.message = message > print(message) > > I then modified the child class B like this: > > class B(A): > def __init__(self, message): > print("This is the message from your parent class A:") > super(B, self).__init__(message) > > B("BlaBla") > > That works, however I am not sure about what exactly happens inside the code. > What I am concerned about is whether the argument is being actually > inherited from the parent class A or does B overwrite the argument. *Arguments* are not inherited. You are confusing two distinct, and different, parts of programming. Inheritance is that if you call a method on a child class, say B.method(), but it doesn't exist, it will call the parent class instead, say A.method(). When you pass an argument to a method or function, you pass whatever you pass, and the method or function receives what you pass. In your example, you call B("BlaBla"), so B's __init__ method receives the same argument "BlaBla" as the argument "message". Inside B, it then passes on message unchanged: B.__init__ receives message="BlaBla" B.__init__ calls super().__init__(message) A.__init__ receives message="BlaBla" If you want to change the message, of course you can do so: class C(A): def __init__(self, message): print("This is the message from your parent class A:") super().__init__(message.upper() + "!!!") C("BlaBla") And now we have: C.__init__ receives message="BlaBla" C.__init__ calls super().__init__(modified message) A.__init__ receives message="BLABLA!!!" That is exactly the same process as if we had this instead: def a_print(message): print(message) def b_print(message): print("This is output from a_print:") a_print(message) def c_print(message): print("This is output from a_print:") a_print(message.upper() + "!!!") > Can anyone advise what the correct solution would be (in case mine is wrong). > Thank you. You have the right idea. When you call your superclass method: super().__init__() # or any other method you need to decide what the *purpose of your overridden method is*. If B.__init__() does exactly the same as A.__init__(), there is no point in writing B.__init__ at all! Just leave it out, and Python will automatically do the right thing. So when you write B.__init__(), you have to decide what you want: - ignore the superclass method, and just provide your own method: class B(A): def __init__(self, message): self.message = message (but if you do this for **everything**, then why are you inheriting from A? just write B as an independent class). - call the superclass method, then do post-processing: class B(A): def __init__(self, message): super().__init__(message) self.message += "?" - pre-process the argument, then call the superclass method: class B(A): def __init__(self, message): if message == "hello?": print("There's nobody here right now.") message = "hello" super().__init__(message) - or any combination of the above. -- Steve From steve at pearwood.info Wed Mar 29 21:29:00 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 30 Mar 2017 12:29:00 +1100 Subject: [Tutor] super constructor usage In-Reply-To: References: Message-ID: <20170330012859.GJ27969@ando.pearwood.info> On Wed, Mar 29, 2017 at 10:32:52PM +0100, Alan Gauld via Tutor wrote: > On 29/03/17 15:33, Rafael Knuth wrote: > > I am trying to wrap my head around the super constructor. > > This is one of these cases where it matters whether you > are using Python v2 or v3. Use of super in v3 is much > easier. It looks from your examples like you are using > v2 but it would be good to confirm that. It can't be Python 2, because A doesn't inherit from object. In that case, B's attempt to call super() would fail. [...] > > That works, however I am not sure about what exactly happens inside the code. > > Yes, you have the mechanism right. > As to what exactly happens inside the interpreter I'll leave > that for those who care about such things :-) The only real magic here is in super(). Everything else is just normal calling methods with arguments. What super() does is return a special object, let's call it S. When you call S.__init__, S is smart enough to ignore it's own __init__ method, and instead search B's inheritance chain (called the MRO, or Method Resolution Order), returning the first __init__ it finds. For B, the MRO is really short: first it looks at class A, then it looks at A's parent, namely `object`, which is the ultimate top of all inheritance chains in Python 3. But in general, the MRO might be very long, it might contain branches, and the same class might be included multiple times. By using super(), Python will ensure that each superclass method is called at most *one* time, in the right order, no matter how many superclasses are involved. -- Steve From elo.okonkwo at gmail.com Thu Mar 30 01:18:34 2017 From: elo.okonkwo at gmail.com (Elo Okonkwo) Date: Thu, 30 Mar 2017 06:18:34 +0100 Subject: [Tutor] Merge Sort Algorithm In-Reply-To: <20170329003637.GG27969@ando.pearwood.info> References: <20170329003637.GG27969@ando.pearwood.info> Message-ID: Thanks so much everyone. I've figured it out. It was the recursive bit that got me confused, its a bit difficult debugging recursive functions. On Wed, Mar 29, 2017 at 1:36 AM, Steven D'Aprano wrote: > On Tue, Mar 28, 2017 at 03:56:16PM +0100, Elo Okonkwo wrote: > > Can someone pls explain this Merge Sort Algorithm, especially the > Recursive > > bit of it. > > Take a pack of cards and shuffle them. Now you want to sort the cards. > > Put the cards down in a pile in front of you and think about sorting it. > There are 52 cards in a Western deck of cards, so that's a lot of cards > to sort. Let's make the job easier: > > (1) Split the deck into two piles, half in each pile. Now you only > have to sort 26 cards at a time, which is much easier. > > (2) After you sort the first pile of 26, and then sort the second pile > of 26, then you merge the two piles, keeping the same order: Turn the > piles upside down, turn over the top card of each pile so you can see > it, and start moving cards from the two piles to a third. Pick whichever > card is smaller, move it to pile number 3, then turn over the next card > so you can see what it is. Repeat until all the cards from the two piles > are merged into a single pile, which is sorted. > > Now comes the recursive step. > > (3) In step 1, I said that sorting 26 cards is easier than sorting 52 > cards. This is true, but sorting 26 cards is still not that much fun. > Let's make it easier: split the pile of 26 cards into two halves, and > sort each half. Then merge the two halves together, and your pile of 26 > cards is sorted. > > Recursive step: > > (4) In step 3 I said that sorting 13 cards is easier than sorting 26 > cards. This is true, but sorting 13 cards is still not that much fun. > Let's make it easier: split the pile of 13 cards into two (nearly) equal > halves, and sort each half. Then merge the two halves together, and your > pile of 13 cards is sorted. > > Recursive step: > > (5) In step 4 I said that sorting 7 cards is easier than sorting 13 > cards. This is true, but sorting 7 cards is still not that much fun. > Let's make it easier: split the pile of 7 cards into two (nearly) equal > halves, and sort each half. Then merge the two halves together, and your > pile of 7 cards is sorted. > > (6) In step 5 I said that sorting 4 cards is easier than sorting 7 > cards. This is true, but sorting 4 cards is still not that much fun. > Let's make it easier: split the pile of 4 cards into two (nearly) equal > halves, and sort each half. Then merge the two halves together, and your > pile of 4 cards is sorted. > > (7) In step 6 I said that sorting 2 cards is easier than sorting 4 > cards. This is true, but sorting 2 cards is still not that much fun. > Let's make it easier: split the pile of 2 cards into two (nearly) equal > halves, and sort each half. Then merge the two halves together, and your > pile of 2 cards is sorted. > > (8) In step 7 I said that sorting 1 card is easier than sorting 2 > cards. This is true, because 1 card is automatically sorted, and I > don't have to think about it at all. > > > So merge sort takes a big job (sorting 52 cards) and repeatedly splits > it into two smaller jobs, until the job is so simple even a computer can > do it: sorting 1 card takes no brains at all. Then it merges 1 card and > 1 card together, keeping them in order, to get two. Then it goes back to > the other pair of 1 card piles, and merges them. Then it merges the two > piles of two cards to get a pile of four cards, and so on, until it ends > up merging two sorted piles of 26 cards, and then the job is done. > > You should actually try this as an exercise. Literally get a pile of > cards and go through the steps until it makes sense. > > For a *person*, this is not an efficient way to sort cards, but for > computers it is very efficient, especially if you had millions of cards > to sort. > > > -- > Steve > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From mats at wichmann.us Wed Mar 29 18:02:16 2017 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 29 Mar 2017 16:02:16 -0600 Subject: [Tutor] super constructor usage In-Reply-To: References: Message-ID: <496f7430-df99-8ce6-c8eb-001538d60372@wichmann.us> On 03/29/2017 08:33 AM, Rafael Knuth wrote: > class A: > def __init__(self, message): > self.message = message > print(message) > > I then modified the child class B like this: > > class B(A): > def __init__(self, message): > print("This is the message from your parent class A:") > super(B, self).__init__(message) > > B("BlaBla") > > That works, however I am not sure about what exactly happens inside the code. > What I am concerned about is whether the argument is being actually > inherited from the parent class A or does B overwrite the argument. > Can anyone advise what the correct solution would be (in case mine is wrong). > Thank you. Alan (as usual) already sorted this. Just to try to fill in some of these questions - what's inherited, overridden, etc., I'm pasting a bit of code I wrote for somewhere else to demonstrate what's going on. Hope it provides some enlightenment (it's written for Python3, you'd have to change the super() call if you're using Python2). Note that your print(message) in A's initializer doesn't really tell you much, it just tells you what argument was passed to the initializer. That would be the same for any function/method, and tells you nothing about inheritance. class A(object): print('Setting class variables in A') aa_cls = 'class A data' def __init__(self): print('A: Initializing instance of', self.__class__.__name__) self.aa = 'instance of class A' def ameth(self): return "A method from class A" class B(A): print('Setting class variables in B') bb_cls = 'class B data' def __init__(self): print('B: Initializing instance of', self.__class__.__name__) super().__init__() self.bb = 'instance of class B' print("Begin examination...") print("Data from classes:") print("A.aa_cls:", A.aa_cls) print("B.aa_cls:", B.aa_cls) print("Instantiating A as a:") a = A() print("Instantiating B as b:") b = B() print("Data from instance a:") print("a.aa_cls:", a.aa_cls) print("a.aa:", a.aa) print("call ameth directly from a:", a.ameth()) print("Dict a:", a.__dict__) print("Data from instance b:") print("b.bb_cls:", b.bb_cls) print("b.bb:", b.bb) print("b.aa_cls:", b.aa_cls) print("call ameth from b:", b.ameth()) print("b.aa:", b.aa) print("Dict b:", b.__dict__) From mats at wichmann.us Wed Mar 29 19:01:17 2017 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 29 Mar 2017 17:01:17 -0600 Subject: [Tutor] super constructor usage In-Reply-To: <496f7430-df99-8ce6-c8eb-001538d60372@wichmann.us> References: <496f7430-df99-8ce6-c8eb-001538d60372@wichmann.us> Message-ID: On 03/29/2017 04:02 PM, Mats Wichmann wrote: > On 03/29/2017 08:33 AM, Rafael Knuth wrote: > >> class A: >> def __init__(self, message): >> self.message = message >> print(message) >> >> I then modified the child class B like this: >> >> class B(A): >> def __init__(self, message): >> print("This is the message from your parent class A:") >> super(B, self).__init__(message) >> >> B("BlaBla") >> >> That works, however I am not sure about what exactly happens inside the code. >> What I am concerned about is whether the argument is being actually >> inherited from the parent class A or does B overwrite the argument. >> Can anyone advise what the correct solution would be (in case mine is wrong). >> Thank you. > > Alan (as usual) already sorted this. > > Just to try to fill in some of these questions - what's inherited, > overridden, etc., I'm pasting a bit of code I wrote for somewhere else > to demonstrate what's going on. etc. To make sure there's an even simpler answer than poring through all those cases (which I think is useful), also try this minimal rewrite of your example: class A(object): def __init__(self, message): self.message = message + " (decorated by superclass)" class B(A): def __init__(self, message): print("Class B initializer called with %s argument" % message) super().__init__(message) b = B("BlaBla") print("instance message =", b.message) From unee0x at gmail.com Wed Mar 29 17:23:33 2017 From: unee0x at gmail.com (kay Cee) Date: Wed, 29 Mar 2017 17:23:33 -0400 Subject: [Tutor] list of functions Message-ID: Greetings all, I would like to use a list of functions for an automation project, and this is the prototype I came up with ########################### def func1(): print('func1') def func2(): print('func2') def func3(): print('func3') func_list = ('func1', 'func2', 'func3') for f in func_list: eval(f)() ############################# The output shows as intended, but I'd like to know if there are any safety or performance issues using this prototype or if there is a better way to acheive a list of functions. Thanks in advance From yosi.levy99 at gmail.com Thu Mar 30 02:14:44 2017 From: yosi.levy99 at gmail.com (Yosef Levy) Date: Thu, 30 Mar 2017 09:14:44 +0300 Subject: [Tutor] how to redirect input from pipe In-Reply-To: References: Message-ID: Thank you, it was very helpful. ?????? 23 ???? 2017 02:39,? "Peter Otten" <__peter__ at web.de> ???: > Yosef Levy wrote: > > > Hello All, > > > > I am running with Python 2.7 > > I have to run script that could have get arguments in two ways: > > 1. argument + file name. > > 2. argument + input from pipe. > > > > example for 1: > > ./my_script.py -t 1,2,3 file_name.txt > > > > example for 2: > > grep snd file_name.txt | ./my_script.py -t 1,2,3 > > > > I am using "parse_known_args" to parse the rest of args when pipe exists. > > and capture with: "fileinput". > > > > My problem is that this does not run always, for second option. > > Any idea how could I get standard input with additional flag? > > for example, running with pipe option will be like this: > > grep snd file_name.txt | ./my_script.py -t 1,2,3 - > > where the additional "-" at the end will indicate script to get standard > > input. > > It's not clear to me why you use parse_known_args(). The examples you give > above seem to be covered by > > $ cat tmp.py > #!/usr/bin/env python > import argparse > import fileinput > > parser = argparse.ArgumentParser() > parser.add_argument("--tags", "-t") > parser.add_argument("files", metavar="file", nargs="*") > args = parser.parse_args() > > print args.tags > for line in fileinput.input(args.files): > print line.strip() > $ cat greek.txt > alpha > beta > gamma > delta > $ cat numbers.txt > ONE > TWO > > Reading from a file: > > $ ./tmp.py -t 1,2,3 numbers.txt > 1,2,3 > ONE > TWO > > Reading from two files: > > $ ./tmp.py -t 1,2,3 numbers.txt greek.txt > 1,2,3 > ONE > TWO > alpha > beta > gamma > delta > > Reading from stdin: > > $ grep ^[ab] greek.txt | ./tmp.py -t 1,2,3 > 1,2,3 > alpha > beta > > Reading from a file, then stdin, then another file: > > $ grep ^[ab] greek.txt | ./tmp.py -t 1,2,3 numbers.txt - numbers.txt > 1,2,3 > ONE > TWO > alpha > beta > ONE > TWO > $ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at yahoo.co.uk Thu Mar 30 03:29:28 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 30 Mar 2017 08:29:28 +0100 Subject: [Tutor] list of functions In-Reply-To: References: Message-ID: On 29/03/17 22:23, kay Cee wrote: > func_list = ('func1', 'func2', 'func3') > > for f in func_list: > eval(f)() Instead of using strings just use the functions directly: func_list = (func1, func2, func3) for f in func_list: f() That avoids the potentially insecure eval and will be faster too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From neilc at norwich.edu Thu Mar 30 10:49:08 2017 From: neilc at norwich.edu (Neil Cerutti) Date: Thu, 30 Mar 2017 14:49:08 +0000 (UTC) Subject: [Tutor] Merge Sort Algorithm References: <20170329003637.GG27969@ando.pearwood.info> Message-ID: On 2017-03-30, Elo Okonkwo wrote: > Thanks so much everyone. > > I've figured it out. It was the recursive bit that got me > confused, its a bit difficult debugging recursive functions. It doesn't have to be! I recommend debugging recursive functions with small, easy-to-think-about test cases, and slowly build them up. Do not try to debug by starting with a typical case. -- Neil Cerutti From badouglas at gmail.com Thu Mar 30 13:51:04 2017 From: badouglas at gmail.com (bruce) Date: Thu, 30 Mar 2017 13:51:04 -0400 Subject: [Tutor] subprocess.Popen / proc.communicate issue Message-ID: Trying to understand the "correct" way to run a sys command ("curl") and to get the potential stderr. Checking Stackoverflow (SO), implies that I should be able to use a raw/text cmd, with "shell=true". If I leave the stderr out, and just use s=proc.communicate() the test works... Any pointers on what I might inspect to figure out why this hangs on the proc.communicate process/line?? I'm showing a very small chunk of the test, but its the relevant piece. Thanks . . . cmd='[r" curl -sS ' #cmd=cmd+'-A "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0"' cmd=cmd+"-A '"+user_agent+"'" ##cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' cmd=cmd+' --cookie-jar '+ff+' --cookie '+ff+' ' #cmd=cmd+'-e "'+referer+'" -d "'+tt+'" ' #cmd=cmd+'-e "'+referer+'" ' cmd=cmd+"-L '"+url1+"'"+'"]' #cmd=cmd+'-L "'+xx+'" ' try_=1 while(try_): proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) s,err=proc.communicate() s=s.strip() err=err.strip() if(err==0): try_='' . . . the cmd is generated to be: cmd=[r" curl -sS -A 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; yie8)' --cookie-jar /crawl_tmp/fetchContentDir/12f5e67c_156e_11e7_9c09_3a9e85f3c88e.lwp --cookie /crawl_tmp/fetchContentDir/12f5e67c_156e_11e7_9c09_3a9e85f3c88e.lwp -L 'http://www6.austincc.edu/schedule/index.php?op=browse&opclass=ViewSched&term=216F000&disciplineid=PCACC&yr=2016&ct=CC'"] test code hangs, ctrl-C generates the following: ^CTraceback (most recent call last): File "/crawl_tmp/austinccFetch_cloud_test.py", line 3363, in ret=fetchClassSectionFacultyPage(a) File "/crawl_tmp/austinccFetch_cloud_test.py", line 978, in fetchClassSectionFacultyPage (s,err)=proc.communicate() File "/usr/lib64/python2.6/subprocess.py", line 732, in communicate stdout, stderr = self._communicate(input, endtime) File "/usr/lib64/python2.6/subprocess.py", line 1328, in _communicate stdout, stderr = self._communicate_with_poll(input, endtime) File "/usr/lib64/python2.6/subprocess.py", line 1400, in _communicate_with_poll ready = poller.poll(self._remaining_time(endtime)) KeyboardInterrupt This works from the cmdline: curl -sS -A 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; yie8)' --cookie-jar /crawl_tmp/fetchContentDir/12f5e67c_156e_11e7_9c09_3a9e85f3c88e.lwp --cookie /crawl_tmp/fetchContentDir/12f5e67c_156e_11e7_9c09_3a9e85f3c88e.lwp -L 'http://www6.austincc.edu/schedule/index.php?op=browse&opclass=ViewSched&term=216F000&disciplineid=PCACC&yr=2016&ct=CC' From achim_alexandru at yahoo.com Thu Mar 30 08:40:41 2017 From: achim_alexandru at yahoo.com (Alexandru Achim) Date: Thu, 30 Mar 2017 12:40:41 +0000 (UTC) Subject: [Tutor] python gtk serial loop thread readind data close References: <1451978270.277856.1490877641049.ref@mail.yahoo.com> Message-ID: <1451978270.277856.1490877641049@mail.yahoo.com> Dear users, I had a problem regarding Threads in python and Gtk3. I want to stop a while loop in Gtk , a loop starded with a thread. I want to control a delay timer laser board with give me ,when I send a command by serial connection, give back continuous status values ; but I want to stop this loop , to modify parameters and start the loop again. A part of my code is here : import serial import threading import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import GObject,Pango, GLib from threading import Thread GObject.threads_init()............. #START BUTTON ??? def start(self,button_start): ?????? Thread(target=self.start_on,args=(self.button_start)) ???? ?????? ??? ??? def start_on(self,widget,data=None): ??? if ser.isOpen(): ??? ??? cmd = 's'??? ??? ??? ser.write(cmd.encode('ascii')+'\r\n') ??? ??? while True: ??? ??? ??? try: ????? ??? ?????? values = ser.readline() ??? ??? ??? ???? self.label_result.set_text(values) ??? ??? ??? except: ????? ??? ??? ??? ??? pass ??? ??? #STOP BUTTON??? ???? ??? def stop(self,button_stop): ???? Thread(target=self.stops,args=(button_stop)).start() ??? ??? ??? def stops(self,widget,data=None): ??? if ser.isOpen(): ??? ??? try:?? ??? ??? ??? cmd = 'f'??? ??? ??? ??? ser.write(cmd.encode('ascii')+'\r\n') ??? ??? ??? status = ser.readline() ??? ??? ??? self.label_result.set_text(status) ??? ??? except: ??? ??? ??? pass ...........win=sincrolaser() win.show_all() Gtk.main() But the problem is when I send STOP button program freeze , probably the loop from the start is looping forever. How do I stop the start thread? Is there a posibility to give a thread flag or identity to find him and close? Thank you,Alex? --------- Eng.ALEXANDRU ACHIM National Institute for Lasers, Plasma and Radiation Physics? Center for Advance Laser Technologies - PW Laser Facility? From rafael.knuth at gmail.com Thu Mar 30 07:39:08 2017 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Thu, 30 Mar 2017 13:39:08 +0200 Subject: [Tutor] super constructor usage In-Reply-To: <20170330012859.GJ27969@ando.pearwood.info> References: <20170330012859.GJ27969@ando.pearwood.info> Message-ID: >> > I am trying to wrap my head around the super constructor. Is it possible to embed a super constructor into an if / elif statement within the child class? if message == "string A": return X elif: return Y How should I modify my code below? (I couldn't solve that by myself) class A: def __init__(self, message): self.message = message print(message) class B(A): def __init__(self, message): print("This is the message from your parent class A:") super(B, self).__init__(message) B("BlaBla") From rafael.knuth at gmail.com Thu Mar 30 13:02:13 2017 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Thu, 30 Mar 2017 19:02:13 +0200 Subject: [Tutor] reading files in Python 3 Message-ID: I can read files like this (relative path): with open("Testfile_B.txt") as file_object: contents = file_object.read() print(contents) But how do I read files if I want to specify the location (absolute path): file_path = "C:\Users\Rafael\Testfile.txt" with open(file_path) as file_object: contents = file_object.read() print(contents) The above does not work ... From alan.gauld at yahoo.co.uk Thu Mar 30 16:08:13 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 30 Mar 2017 21:08:13 +0100 Subject: [Tutor] super constructor usage In-Reply-To: References: <20170330012859.GJ27969@ando.pearwood.info> Message-ID: On 30/03/17 12:39, Rafael Knuth wrote: >>>> I am trying to wrap my head around the super constructor. > > Is it possible to embed a super constructor into an if / elif > statement within the child class? Of course, the __init__ methods are special in any way the normal coding mechanisms all work. If for some reason you only want to call super some of the time then by all means put it inside an if clause. But remember that not calling super potentially leaves some attributes of your superclass uninitialized. By not calling super you assume full responsibility for initializing both your sub class and the superclass. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From zachary.ware+pytut at gmail.com Thu Mar 30 16:47:45 2017 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Thu, 30 Mar 2017 15:47:45 -0500 Subject: [Tutor] reading files in Python 3 In-Reply-To: References: Message-ID: On Mar 30, 2017 15:07, "Rafael Knuth" wrote: I can read files like this (relative path): with open("Testfile_B.txt") as file_object: contents = file_object.read() print(contents) But how do I read files if I want to specify the location (absolute path): file_path = "C:\Users\Rafael\Testfile.txt" with open(file_path) as file_object: contents = file_object.read() print(contents) The above does not work ... "The above does not work" is not descriptive. How does it not work? Is there a traceback? Does the program stop responding? Does the computer catch fire? In this case, the problem is the bogus Unicode escape that you inadvertently included in your path: `\Us...`. To fix it, either use a 'raw' string (`r"C:\Users\..."`) or use forward slashes rather than backslashes, which Windows is happy to accept. Regards, -- Zach (On a phone) From badouglas at gmail.com Thu Mar 30 17:11:28 2017 From: badouglas at gmail.com (bruce) Date: Thu, 30 Mar 2017 17:11:28 -0400 Subject: [Tutor] test Message-ID: sent a question earlier.. and got a reply saying it was in the moderation process??? From cs at zip.com.au Thu Mar 30 18:43:06 2017 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 31 Mar 2017 09:43:06 +1100 Subject: [Tutor] subprocess.Popen / proc.communicate issue In-Reply-To: References: Message-ID: <20170330224306.GA15024@cskk.homeip.net> On 30Mar2017 13:51, bruce wrote: >Trying to understand the "correct" way to run a sys command ("curl") >and to get the potential stderr. Checking Stackoverflow (SO), implies >that I should be able to use a raw/text cmd, with "shell=true". I strongly recommend avoiding shell=True if you can. It has many problems. All stackoverflow advice needs to be considered with caution. However, that is not the source of your deadlock. >If I leave the stderr out, and just use > s=proc.communicate() >the test works... > >Any pointers on what I might inspect to figure out why this hangs on >the proc.communicate process/line?? When it is hung, run "lsof" on the processes from another terminal i.e. lsof the python process and also lsof the curl process. That will make clear the connections between them, particularly which file descriptors ("fd"s) are associated with what. The run "strace" on the processes. That shoud show you what system calls are in progress in each process. My expectation is that you will see Python reading from one file descriptor and curl writing to a different one, and neither progressing. Personally I avoid .communicate and do more work myself, largerly to know precisely what is going on with my subprocesses. The difficulty with .communicate is that Python must read both stderr and stdout separately, but it will be doing that sequentially: read one, then read the other. That is just great if the command is "short" and writes a small enough amount of data to each. The command runs, writes, and exits. Python reads one and sees EOF after the data, because the command has exited. Then Python reads the other and collects the data and sees EOF because the command has exited. However, if the output of the command is large on whatever stream Python reads _second_, the command will stall writing to that stream. This is because Python is not reading the data, and therefore the buffers fill (stdio in curl plus the buffer in the pipe). So the command ("curl") stalls waiting for data to be consumed from the buffers. And because it has stalled, the command does not exit, and therefore Python does not see EOF on the _first_ stream. So it sits waiting for more data, never reading from the second stream. [...snip...] > cmd='[r" curl -sS ' > #cmd=cmd+'-A "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) >Gecko/20100101 Firefox/38.0"' > cmd=cmd+"-A '"+user_agent+"'" > ##cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' > cmd=cmd+' --cookie-jar '+ff+' --cookie '+ff+' ' > #cmd=cmd+'-e "'+referer+'" -d "'+tt+'" ' > #cmd=cmd+'-e "'+referer+'" ' > cmd=cmd+"-L '"+url1+"'"+'"]' > #cmd=cmd+'-L "'+xx+'" ' Might I recommand something like this: cmd_args = [ 'curl', '-sS' ] cmd_args.extend( [ '-A', user_agent ] ) cmd_args.extend( [ '--cookie-jar', ff, '--cookie', ff ] ) cmd_args.extend( [ '-L', url ] and using shell=False. This totally avoids any need to "quote" strings in the command, because the shell is not parsing the string - you're invoking "curl" directly instead of asking the shell to read a string and invoke "curl" for you. Constructing shell commands is tedious and fiddly; avoid it when you don't need to. > try_=1 It is preferable to say: try_ = true > while(try_): You don't need and brackets here: while try_: More readable, because less punctuation. > proc=subprocess.Popen(cmd, >shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) proc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) > s,err=proc.communicate() > s=s.strip() > err=err.strip() > if(err==0): > try_='' It is preferable to say: try_ = False Also, you should be looking at proc.returncode, _not_ err. Many programs write informative messages to stderr, and a nonempty stderr does not imply failure. instead, all programs set their exit status to 0 for success and to various nonzero values for failure. So check: if proc.returncode == 0: try_ = False Or you could bypass try_ altogether and go: while True: ... subprocess ... if proc.returncode == 0: break That may not fit your larger scheme. Cheers, Cameron Simpson From cs at zip.com.au Thu Mar 30 18:51:44 2017 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 31 Mar 2017 09:51:44 +1100 Subject: [Tutor] subprocess.Popen / proc.communicate issue In-Reply-To: <20170330224306.GA15024@cskk.homeip.net> References: <20170330224306.GA15024@cskk.homeip.net> Message-ID: <20170330225144.GA20296@cskk.homeip.net> I wrote a long description of how .communicate can deadlock. Then I read the doco more carefully and saw this: Warning: Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process. This suggests that .communicate uses Threads to send and to gather data independently, and that therefore the deadlock situation may not arise. See what lsof and strace tell you; all my other advice stands regardless, and the deadlock description may or may not be relevant. Still worth reading and understanding it when looking at this kind of problem. Cheers, Cameron Simpson On 31Mar2017 09:43, Cameron Simpson wrote: >On 30Mar2017 13:51, bruce wrote: >>Trying to understand the "correct" way to run a sys command ("curl") >>and to get the potential stderr. Checking Stackoverflow (SO), implies >>that I should be able to use a raw/text cmd, with "shell=true". > >I strongly recommend avoiding shell=True if you can. It has many >problems. All stackoverflow advice needs to be considered with >caution. However, that is not the source of your deadlock. > >>If I leave the stderr out, and just use >> s=proc.communicate() >>the test works... >> >>Any pointers on what I might inspect to figure out why this hangs on >>the proc.communicate process/line?? > >When it is hung, run "lsof" on the processes from another terminal >i.e. lsof the python process and also lsof the curl process. That will >make clear the connections between them, particularly which file >descriptors ("fd"s) are associated with what. > >The run "strace" on the processes. That shoud show you what system >calls are in progress in each process. > >My expectation is that you will see Python reading from one file >descriptor and curl writing to a different one, and neither >progressing. > >Personally I avoid .communicate and do more work myself, largerly to >know precisely what is going on with my subprocesses. > >The difficulty with .communicate is that Python must read both stderr >and stdout separately, but it will be doing that sequentially: read >one, then read the other. That is just great if the command is "short" >and writes a small enough amount of data to each. The command runs, >writes, and exits. Python reads one and sees EOF after the data, >because the command has exited. Then Python reads the other and >collects the data and sees EOF because the command has exited. > >However, if the output of the command is large on whatever stream >Python reads _second_, the command will stall writing to that stream. >This is because Python is not reading the data, and therefore the >buffers fill (stdio in curl plus the buffer in the pipe). So the >command ("curl") stalls waiting for data to be consumed from the >buffers. And because it has stalled, the command does not exit, and >therefore Python does not see EOF on the _first_ stream. So it sits >waiting for more data, never reading from the second stream. > >[...snip...] >> cmd='[r" curl -sS ' >> #cmd=cmd+'-A "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) >>Gecko/20100101 Firefox/38.0"' >> cmd=cmd+"-A '"+user_agent+"'" >> ##cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' >> cmd=cmd+' --cookie-jar '+ff+' --cookie '+ff+' ' >> #cmd=cmd+'-e "'+referer+'" -d "'+tt+'" ' >> #cmd=cmd+'-e "'+referer+'" ' >> cmd=cmd+"-L '"+url1+"'"+'"]' >> #cmd=cmd+'-L "'+xx+'" ' > >Might I recommand something like this: > > cmd_args = [ 'curl', '-sS' ] > cmd_args.extend( [ '-A', user_agent ] ) > cmd_args.extend( [ '--cookie-jar', ff, '--cookie', ff ] ) > cmd_args.extend( [ '-L', url ] > >and using shell=False. This totally avoids any need to "quote" strings >in the command, because the shell is not parsing the string - you're >invoking "curl" directly instead of asking the shell to read a string >and invoke "curl" for you. > >Constructing shell commands is tedious and fiddly; avoid it when you >don't need to. > >> try_=1 > >It is preferable to say: > > try_ = true > >> while(try_): > >You don't need and brackets here: > > while try_: > >More readable, because less punctuation. > >> proc=subprocess.Popen(cmd, >>shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) > > proc = subprocess.Popen(cmd_args, > stdout=subprocess.PIPE, > stderr=subprocess.PIPE) > >> s,err=proc.communicate() >> s=s.strip() >> err=err.strip() >> if(err==0): >> try_='' > >It is preferable to say: > > try_ = False > >Also, you should be looking at proc.returncode, _not_ err. Many >programs write informative messages to stderr, and a nonempty stderr >does not imply failure. > >instead, all programs set their exit status to 0 for success and to >various nonzero values for failure. So check: > > if proc.returncode == 0: > try_ = False > >Or you could bypass try_ altogether and go: > > while True: > ... subprocess ... > if proc.returncode == 0: > break > >That may not fit your larger scheme. > >Cheers, >Cameron Simpson >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor From robertvstepp at gmail.com Thu Mar 30 22:34:13 2017 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 30 Mar 2017 21:34:13 -0500 Subject: [Tutor] test In-Reply-To: References: Message-ID: On Thu, Mar 30, 2017 at 4:11 PM, bruce wrote: > sent a question earlier.. and got a reply saying it was in the > moderation process??? You've made it through the process. See the bottom of https://mail.python.org/pipermail/tutor/2017-March/thread.html to see your original question and the answers. -- boB From eryksun at gmail.com Fri Mar 31 02:13:44 2017 From: eryksun at gmail.com (eryk sun) Date: Fri, 31 Mar 2017 06:13:44 +0000 Subject: [Tutor] subprocess.Popen / proc.communicate issue In-Reply-To: <20170330225144.GA20296@cskk.homeip.net> References: <20170330224306.GA15024@cskk.homeip.net> <20170330225144.GA20296@cskk.homeip.net> Message-ID: On Thu, Mar 30, 2017 at 10:51 PM, Cameron Simpson wrote: > This suggests that .communicate uses Threads to send and to gather data > independently, and that therefore the deadlock situation may not arise. For Unix, communicate() uses select or poll. It uses threads on Windows. Either way it avoids deadlocking. From eryksun at gmail.com Fri Mar 31 02:42:32 2017 From: eryksun at gmail.com (eryk sun) Date: Fri, 31 Mar 2017 06:42:32 +0000 Subject: [Tutor] reading files in Python 3 In-Reply-To: References: Message-ID: On Thu, Mar 30, 2017 at 8:47 PM, Zachary Ware wrote: > In this case, the problem is the bogus Unicode escape that you > inadvertently included in your path: `\Us...`. To fix it, either use a > 'raw' string (`r"C:\Users\..."`) or use forward slashes rather than > backslashes, which Windows is happy to accept. Forward slash is acceptable when all you need to support is DOS-style paths that are limited to DOS semantics and MAX_PATH. A raw string works, except not for paths ending in backslash and not for unicode strings in Python 2. A generic solution is to use a pathlib.Path() in 3.x, which normalizes the path to use backslash, or os.path.normpath() in 2.x. From mats at wichmann.us Thu Mar 30 16:45:39 2017 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 30 Mar 2017 14:45:39 -0600 Subject: [Tutor] reading files in Python 3 In-Reply-To: References: Message-ID: <0736889e-d8ea-3c14-aa73-4dc8a31a2906@wichmann.us> On 03/30/2017 11:02 AM, Rafael Knuth wrote: > I can read files like this (relative path): > > with open("Testfile_B.txt") as file_object: > contents = file_object.read() > print(contents) > > But how do I read files if I want to specify the location (absolute path): > > file_path = "C:\Users\Rafael\Testfile.txt" > with open(file_path) as file_object: > contents = file_object.read() > print(contents) > > The above does not work ... Yeah, fun. You need to escape the \ that the idiot MS-DOS people chose for the file path separator. Because \ is treated as an escape character. Get familiar with the path function in the os module, it will let you do examinations of file paths, by the way, including constructing them in ways https://docs.python.org/2/library/os.path.html simple workaround: use a r letter in front of the string (r for raw): file_path = r"C:\Users\Rafael\Testfile.txt" os.path.exists(file_path) ugly workaround: escape the backslashes so they aren't treated specially: file_path = "C:\\Users\\Rafael\\Testfile.txt" os.path.exists(file_path) you can use os.path.join() to build up a path string in a more independent way, although it doesn't work quite as expected. To get what you're asking for, though: file_path = os.path.join(os.path.expanduser('~Rafael'), 'Testfile.txt') print(file_path) From mats at wichmann.us Thu Mar 30 18:57:41 2017 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 30 Mar 2017 16:57:41 -0600 Subject: [Tutor] super constructor usage In-Reply-To: References: <20170330012859.GJ27969@ando.pearwood.info> Message-ID: <490a5607-cb41-c204-0ab9-78792dad0118@wichmann.us> On 03/30/2017 05:39 AM, Rafael Knuth wrote: >>>> I am trying to wrap my head around the super constructor. > > Is it possible to embed a super constructor into an if / elif > statement within the child class? > > if message == "string A": return X > elif: return Y > > How should I modify my code below? > (I couldn't solve that by myself) > > class A: > def __init__(self, message): > self.message = message > print(message) > > class B(A): > def __init__(self, message): > print("This is the message from your parent class A:") > super(B, self).__init__(message) > > B("BlaBla") For grins, try this (decorated with prints). There's an additional argument allowed to the class B initializer, but set as a default argument so that if you omit it it defaults to True. === class A(object): def __init__(self, msg): print('A: Initializing instance of', self.__class__.__name__) self.message = msg class B(A): def __init__(self, msg, doinit=True): print('B: Initializing instance of', self.__class__.__name__) if doinit: super().__init__(msg) print("Instantiating an A:") a = A("some message") print(a.message) print("Instantiating a B:") b = B("some message") print(b.message) print("Instantiating a B without calling superclass __init__:") c = B("some message", False) print(c.message) === When you run it: Instantiating an A: A: Initializing instance of A some message Instantiating a B: B: Initializing instance of B A: Initializing instance of B some message Instantiating a B without calling superclass __init__: B: Initializing instance of B Traceback (most recent call last): File "constr-tutor.py", line 22, in print(c.message) AttributeError: 'B' object has no attribute 'message' === So note that: the instance attribute "message" is set in the class A initializer, as in all your postings in this thread. Just like Alan pointed out, there are implications if you don't call up to the superclass, and it shows up pretty clearly here: in the third case, where we decide not to call the parent's __init__, this initialization doesn't happen and the attribute is missing, so accessing it blows up with an AttributeError exception. From niihung at gmail.com Thu Mar 30 23:20:38 2017 From: niihung at gmail.com (=?UTF-8?B?4Kiq4Kmw4Kic4Ki+4KisIOCoquCpsOConOCovuCorOCpgA==?=) Date: Thu, 30 Mar 2017 20:20:38 -0700 Subject: [Tutor] HTML module for Python In-Reply-To: References: Message-ID: Thank you Alan. I needed to generate a report using a python script (will become part of a web service) and send it as an email. For now I put the required HTML tags wherever they were needed. Thanks Sri Kavi. I'll check out your suggestion. On Wed, Mar 22, 2017 at 12:29 AM, Alan Gauld via Tutor wrote: > On 20/03/17 22:09, ????? ?????? wrote: > > > Looking for recommendations on Python module to use to generate HTML > > pages/tables, other HTML content. Kindly help. > > While thee are some modules that help with this most Python > programs I've seen just generate the HTML directly as strings. > There is no direct equivalent of, say, Perl's CGI module. > > However, if you are using a web framework, it will > generally provide a templating mechanism which will > separate out the HTML code (the view) from your > Python code (the model and controller). > > So if you give is more information about what the > HTML is being used for, we might be able to provide > more help. Is it part of a web application or just > a data file that you make available to some third > party? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > 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 > From poojabhalode11 at gmail.com Thu Mar 30 16:35:42 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Thu, 30 Mar 2017 16:35:42 -0400 Subject: [Tutor] All Entry Boxes taking the same value Message-ID: Hi, I am working on a GUI application where I have a multiple number of entry boxes and I created a loop for the label and entry boxes depending upon the number of times it needs to be shown. However, I tried assigning different values to each label and entry boxes in the for loop using lists, so that I can save different values obtained from the entry boxes in the entry lists and use them later. *However, when I execute it, and type something in one entrybox, it shows in all the entry boxes using multi-cursor option. * Can someone please tell me how I can avoid this error? I am trying to put a for loop since I need to create the gui such that the number of times it needs to be done would be unknown. Hence, the way I went about this was to take an upper limit of 3 and thus, reacoriginal = [" ", " ", " "]. This can be used as an upper limit and the required number can thus fit in as needed. Here, for example, I have taken the required number as two. this would be later modified. Code: from Tkinter import * root = Tk() root.geometry("500x350") # Variables: reacoriginal = [" ", " ", " "] conca = [1,0,0] print conca[0] concunit = [" ", " ", " "] concunit11 = StringVar() concunit21 = StringVar() concunit31 = StringVar() conca1 = IntVar() conca1.set(1) concb1 = IntVar() concc1 = IntVar() average = [" ", " ", " "] lowest = [" ", " ", " "] highest = [" ", " ", " "] averageformulation = [" ", " ", " "] lowestformulation = [" ", " ", " "] highestformulation = [" ", " ", " "] print average reactants = ["A", "B", "C"] for i in range(len(reactants)): Label(root, text = "Experimental Range").grid(row = 0, column = 0, sticky = W) labeldown = Label(root, text = "For Parameter Estimation") labeldown.grid(row = 1, column = 0, sticky = W) labeldown.config(state='disable') Label(root, text = "Average ").grid(row = 2, column = 1, sticky = W) Label(root, text = "Lowest ").grid(row = 2, column = 2, sticky = W) Label(root, text = "Highest").grid(row = 2, column = 3, sticky = W) Label(root, text = "Units").grid(row = 2, column = 4, sticky = W) Checkbutton(root, text = reactants[i], variable = conca[i]).grid(row = 3+i, column = 0, sticky = W) optionlist2 = [u'\u03bcmol/L', 'mmol/L','mol/L'] concunitdrop = OptionMenu(root, concunit[i], *optionlist2) concunitdrop.config(width = 8) concunitdrop.grid(row = 3+i, column = 4, sticky = W) for i in range(len(reactants)): *Entry*(root, textvariable =* average[i]*, width = 15, state=DISABLED).grid(row = 3+i, column = 1, sticky = W) *Entry*(root, textvariable = *lowest[i]*, width = 15).grid(row = 3+i, column = 2, sticky = W) *Entry*(root, textvariable = *highest[i]*, width = 15).grid(row = 3+i, column = 3, sticky = W) root.mainloop() From alan.gauld at yahoo.co.uk Fri Mar 31 05:29:12 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 31 Mar 2017 10:29:12 +0100 Subject: [Tutor] super constructor usage In-Reply-To: References: <20170330012859.GJ27969@ando.pearwood.info> Message-ID: On 30/03/17 21:08, Alan Gauld via Tutor wrote: > Of course, the __init__ methods are special in any way Should have said *not special* in any way... > But remember that not calling super potentially leaves > some attributes of your superclass uninitialized. By not > calling super you assume full responsibility for > initializing both your sub class and the superclass. And it's worth reminding ourselves that there could be several superclasses not just the one we immediately inherit from. Finally, this discussion has been in the context of constructors but super() applies to all methods. There is nothing unique about construction, it's just like any other method call where you want to include the superclass functionality. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 31 05:30:55 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 31 Mar 2017 10:30:55 +0100 Subject: [Tutor] python gtk serial loop thread readind data close In-Reply-To: <1451978270.277856.1490877641049@mail.yahoo.com> References: <1451978270.277856.1490877641049.ref@mail.yahoo.com> <1451978270.277856.1490877641049@mail.yahoo.com> Message-ID: On 30/03/17 13:40, Alexandru Achim via Tutor wrote: > Dear users, > I had a problem regarding Threads in python and Gtk3. This list is really for the core language and library, I suspect you might get a better response by asking on the PyGTK forum where there are more likely to be people who have come across the same issues. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Fri Mar 31 06:20:52 2017 From: __peter__ at web.de (Peter Otten) Date: Fri, 31 Mar 2017 12:20:52 +0200 Subject: [Tutor] All Entry Boxes taking the same value References: Message-ID: Pooja Bhalode wrote: > average = [" ", " ", " "] > for i in range(len(reactants)): > Entry(root, textvariable = average[i], width = 15, > state=DISABLED).grid(row = 3+i, column = 1, sticky = W) Hint: What is passed as textvariable? What should be? Unfortunately the Entry accepts both StringVar instances and names of StringVar instances which automagically spring into existence -- and " " is a valid name... Pooja, I have been watching your efforts to write one or more python/tkinter scripts mostly via try and error for a while now. It is obvious that it doesn't work as there are so many more ways to go wrong than right. I recommend that you see if you can find a tutorial for both Python and Tkinter, and work through that for a few weeks, say. Once you have a general understanding of programming your progress will be faster, and you won't destroy the result of the previous step with the changes you make in the next. From alan.gauld at yahoo.co.uk Fri Mar 31 06:28:36 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 31 Mar 2017 11:28:36 +0100 Subject: [Tutor] All Entry Boxes taking the same value In-Reply-To: References: Message-ID: On 30/03/17 21:35, Pooja Bhalode wrote: > *However, when I execute it, and type something in one entrybox, it shows > in all the entry boxes using multi-cursor option. * I'm not sure whats going on and don;t habe tome to experiment but one thing I noticed: > average = [" ", " ", " "] > lowest = [" ", " ", " "] > highest = [" ", " ", " "] ... > for i in range(len(reactants)): > *Entry*(root, textvariable =* average[i]*, width = 15, > state=DISABLED).grid(row = 3+i, column = 1, sticky = W) You are setting textvariable to a string but it should be a StrinVar object. You could probably fix that by changing your data definitions to StringVars: average = [StringVar(), StringVar(), StringVar()] I don't know if that will fix the problem but its probably a good thing to do anyhow... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From igorafm at gmail.com Fri Mar 31 07:23:40 2017 From: igorafm at gmail.com (Igor Alexandre) Date: Fri, 31 Mar 2017 08:23:40 -0300 Subject: [Tutor] Using an XML file for web crawling Message-ID: <3AC3A983-A252-4515-B54A-B208051F903A@gmail.com> Hi! I'm a newbie in the Python/Web crawling world. I've been trying to find an answer to the following question since last week, but I couldn't so far, so I decided to ask it myself here: I have a sitemap in XML and I want to use it to save as text the various pages of the site. Do you guys know how can I do it? I'm looking for some code on the web where I can just type the xml address and wait for the crawler to do it's job, saving all the pages indicated in the sitemap as a text file in my computer. Thank you! Best, Igor Alexandre From s.molnar at sbcglobal.net Fri Mar 31 08:19:37 2017 From: s.molnar at sbcglobal.net (Stephen P. Molnar) Date: Fri, 31 Mar 2017 08:19:37 -0400 Subject: [Tutor] Extract Block of Data from a 2D Array Message-ID: <58DE4959.2070605@sbcglobal.net> I have a block of data extracted from a quantum mechanical calculation: CARTESIAN COORDINATES (A.U.) ---------------------------- NO LB ZA FRAG MASS X Y Z 0 C 6.0000 0 12.011 -3.265636 0.198894 0.090858 1 C 6.0000 0 12.011 -1.307161 1.522212 1.003463 2 C 6.0000 0 12.011 1.213336 0.948208 -0.033373 3 N 7.0000 0 14.007 3.238650 1.041523 1.301322 4 C 6.0000 0 12.011 -5.954489 0.650878 0.803379 5 C 6.0000 0 12.011 5.654476 0.480066 0.013757 where the number of lines depends upon the molecule being considered. I want to extract the block of data starting on line 4 and column 4. Unfortunately, the only programming language in which I used to be competent in is Fortran. I have attempted researching this problem, but have only succeeded in increasing my mental entropy. Help will be much appreciated. Thanks in advance. -- Stephen P. Molnar, Ph.D. Life is a fuzzy set www.molecular-modeling.net Stochastic and multivariate (614)312-7528 (c) Skype: smolnar1 From alan.gauld at yahoo.co.uk Fri Mar 31 10:11:11 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 31 Mar 2017 15:11:11 +0100 Subject: [Tutor] Using an XML file for web crawling In-Reply-To: <3AC3A983-A252-4515-B54A-B208051F903A@gmail.com> References: <3AC3A983-A252-4515-B54A-B208051F903A@gmail.com> Message-ID: On 31/03/17 12:23, Igor Alexandre wrote: > I have a sitemap in XML and I want to use it to save as text the various pages What about non-text pages such as images and media files? > I'm looking for some code on the web where I can just type the xml address > and wait for the crawler to do it's job, saving all the pages > indicated in the sitemap as a text file in my computer. I assume you mean multiple text files? And I assume you want to recreate the site structure too - with folders etc? There are tools around to do that but I don't know of any Python code that you can just pick up and use, you will need to do a bit of work. But I'm not an expert in web crawling so I could be wrong! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Fri Mar 31 10:29:12 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 31 Mar 2017 15:29:12 +0100 Subject: [Tutor] Extract Block of Data from a 2D Array In-Reply-To: <58DE4959.2070605@sbcglobal.net> References: <58DE4959.2070605@sbcglobal.net> Message-ID: On 31/03/17 13:19, Stephen P. Molnar wrote: > I have a block of data extracted from a quantum mechanical calculation: How is this data stored? On paper? In a database? In XML? A CSV file? Plain text? The answer to that will go a long way to pointing you in the right direction for a solution. > CARTESIAN COORDINATES (A.U.) > ---------------------------- > NO LB ZA FRAG MASS X Y Z > 0 C 6.0000 0 12.011 -3.265636 0.198894 0.090858 > 1 C 6.0000 0 12.011 -1.307161 1.522212 1.003463 > 2 C 6.0000 0 12.011 1.213336 0.948208 -0.033373 > 3 N 7.0000 0 14.007 3.238650 1.041523 1.301322 > 4 C 6.0000 0 12.011 -5.954489 0.650878 0.803379 > 5 C 6.0000 0 12.011 5.654476 0.480066 0.013757 > > where the number of lines depends upon the molecule being considered. > > I want to extract the block of data starting on line 4 and column 4. A block of data needs a start and end. Where is the end? Also which of the above lines is line 4? I'd read it as the one starting the actual raw data values. But it could be the 4th line of values that you want? It might help to know the OS you are using too because Unix in particular has some OS level tools that might simplify preparing the data. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From kliateni at gmail.com Fri Mar 31 10:34:09 2017 From: kliateni at gmail.com (Karim) Date: Fri, 31 Mar 2017 16:34:09 +0200 Subject: [Tutor] Extract Block of Data from a 2D Array In-Reply-To: <58DE4959.2070605@sbcglobal.net> References: <58DE4959.2070605@sbcglobal.net> Message-ID: <9eac696f-2310-fb6e-c290-54d559e977bb@gmail.com> On 31/03/2017 14:19, Stephen P. Molnar wrote: > I have a block of data extracted from a quantum mechanical calculation: > > CARTESIAN COORDINATES (A.U.) > ---------------------------- > NO LB ZA FRAG MASS X Y Z > 0 C 6.0000 0 12.011 -3.265636 0.198894 0.090858 > 1 C 6.0000 0 12.011 -1.307161 1.522212 1.003463 > 2 C 6.0000 0 12.011 1.213336 0.948208 -0.033373 > 3 N 7.0000 0 14.007 3.238650 1.041523 1.301322 > 4 C 6.0000 0 12.011 -5.954489 0.650878 0.803379 > 5 C 6.0000 0 12.011 5.654476 0.480066 0.013757 > > where the number of lines depends upon the molecule being considered. > > I want to extract the block of data starting on line 4 and column 4. > Unfortunately, the only programming language in which I used to be > competent in is Fortran. I have attempted researching this problem, > but have only succeeded in increasing my mental entropy. > > Help will be much appreciated. Thanks in advance. starting on line 4 > and column 4. Unfortunately, the only programming language in which I > used to be competent in is Fortran. I have attempted researching this > problem, but have only succeeded Hello, If your delimiter is a tabulation in your data tab you can use the CSV module in this way using python 2.7 (code not tested): ----------------------------------------------------------------- $ python Python 2.7.6 (default, Oct 26 2016, 20:30:19) [GCC 4.8.4] on linux2 >>> >>> import csv >>> my_data_file = open( "my_tab_file") >>> reader = csv.DictReader(my_data_file, delimiter='\t') >>> for line_number, row in enumerate(reader, start=1): if line_number >= 4: print row['MASS'], and in a file called extract_data.py: #-------------------------------------------------------------------- import csv my_data_file = open( "my_tab_file") reader = csv.DictReader(my_data_file, delimiter='\t') for line_number, row in enumerate(reader, start=1): if line_number >= 4: print row['MASS'], #---------------------------------------------------------------------- Just execute: $ python extract_data.py Just be aware that the first line of you data file is recognized as the header of all columns. The csv module allows you to to easily reference the element of each column with its column name (given by the header == the first line of the file) Cheers Karim From badouglas at gmail.com Fri Mar 31 10:49:06 2017 From: badouglas at gmail.com (bruce) Date: Fri, 31 Mar 2017 10:49:06 -0400 Subject: [Tutor] subprocess.Popen / proc.communicate issue In-Reply-To: <20170330225144.GA20296@cskk.homeip.net> References: <20170330224306.GA15024@cskk.homeip.net> <20170330225144.GA20296@cskk.homeip.net> Message-ID: Cameron!!! You are 'da man!! Read your exaplanation.. good stuff to recheck/test and investigate over time.... In the short term, I'll implement some tests!! thanks! On Thu, Mar 30, 2017 at 6:51 PM, Cameron Simpson wrote: > I wrote a long description of how .communicate can deadlock. > > Then I read the doco more carefully and saw this: > > Warning: Use communicate() rather than .stdin.write, .stdout.read > or .stderr.read to avoid deadlocks due to any of the other OS > pipe buffers filling up and blocking the child process. > > This suggests that .communicate uses Threads to send and to gather data > independently, and that therefore the deadlock situation may not arise. > > See what lsof and strace tell you; all my other advice stands regardless, > and > the deadlock description may or may not be relevant. Still worth reading and > understanding it when looking at this kind of problem. > > Cheers, > Cameron Simpson > > > On 31Mar2017 09:43, Cameron Simpson wrote: >> >> On 30Mar2017 13:51, bruce wrote: >>> >>> Trying to understand the "correct" way to run a sys command ("curl") >>> and to get the potential stderr. Checking Stackoverflow (SO), implies >>> that I should be able to use a raw/text cmd, with "shell=true". >> >> >> I strongly recommend avoiding shell=True if you can. It has many problems. >> All stackoverflow advice needs to be considered with caution. However, that >> is not the source of your deadlock. >> >>> If I leave the stderr out, and just use >>> s=proc.communicate() >>> the test works... >>> >>> Any pointers on what I might inspect to figure out why this hangs on >>> the proc.communicate process/line?? >> >> >> When it is hung, run "lsof" on the processes from another terminal i.e. >> lsof the python process and also lsof the curl process. That will make clear >> the connections between them, particularly which file descriptors ("fd"s) >> are associated with what. >> >> The run "strace" on the processes. That shoud show you what system calls >> are in progress in each process. >> >> My expectation is that you will see Python reading from one file >> descriptor and curl writing to a different one, and neither progressing. >> >> Personally I avoid .communicate and do more work myself, largerly to know >> precisely what is going on with my subprocesses. >> >> The difficulty with .communicate is that Python must read both stderr and >> stdout separately, but it will be doing that sequentially: read one, then >> read the other. That is just great if the command is "short" and writes a >> small enough amount of data to each. The command runs, writes, and exits. >> Python reads one and sees EOF after the data, because the command has >> exited. Then Python reads the other and collects the data and sees EOF >> because the command has exited. >> >> However, if the output of the command is large on whatever stream Python >> reads _second_, the command will stall writing to that stream. This is >> because Python is not reading the data, and therefore the buffers fill >> (stdio in curl plus the buffer in the pipe). So the command ("curl") stalls >> waiting for data to be consumed from the buffers. And because it has >> stalled, the command does not exit, and therefore Python does not see EOF on >> the _first_ stream. So it sits waiting for more data, never reading from the >> second stream. >> >> [...snip...] >>> >>> cmd='[r" curl -sS ' >>> #cmd=cmd+'-A "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) >>> Gecko/20100101 Firefox/38.0"' >>> cmd=cmd+"-A '"+user_agent+"'" >>> ##cmd=cmd+' --cookie-jar '+cname+' --cookie '+cname+' ' >>> cmd=cmd+' --cookie-jar '+ff+' --cookie '+ff+' ' >>> #cmd=cmd+'-e "'+referer+'" -d "'+tt+'" ' >>> #cmd=cmd+'-e "'+referer+'" ' >>> cmd=cmd+"-L '"+url1+"'"+'"]' >>> #cmd=cmd+'-L "'+xx+'" ' >> >> >> Might I recommand something like this: >> >> cmd_args = [ 'curl', '-sS' ] >> cmd_args.extend( [ '-A', user_agent ] ) >> cmd_args.extend( [ '--cookie-jar', ff, '--cookie', ff ] ) >> cmd_args.extend( [ '-L', url ] >> >> and using shell=False. This totally avoids any need to "quote" strings in >> the command, because the shell is not parsing the string - you're invoking >> "curl" directly instead of asking the shell to read a string and invoke >> "curl" for you. >> >> Constructing shell commands is tedious and fiddly; avoid it when you don't >> need to. >> >>> try_=1 >> >> >> It is preferable to say: >> >> try_ = true >> >>> while(try_): >> >> >> You don't need and brackets here: >> >> while try_: >> >> More readable, because less punctuation. >> >>> proc=subprocess.Popen(cmd, >>> shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >> >> >> proc = subprocess.Popen(cmd_args, >> stdout=subprocess.PIPE, >> stderr=subprocess.PIPE) >> >>> s,err=proc.communicate() >>> s=s.strip() >>> err=err.strip() >>> if(err==0): >>> try_='' >> >> >> It is preferable to say: >> >> try_ = False >> >> Also, you should be looking at proc.returncode, _not_ err. Many programs >> write informative messages to stderr, and a nonempty stderr does not imply >> failure. >> >> instead, all programs set their exit status to 0 for success and to >> various nonzero values for failure. So check: >> >> if proc.returncode == 0: >> try_ = False >> >> Or you could bypass try_ altogether and go: >> >> while True: >> ... subprocess ... >> if proc.returncode == 0: >> break >> >> That may not fit your larger scheme. >> >> Cheers, >> Cameron Simpson >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Fri Mar 31 10:50:43 2017 From: __peter__ at web.de (Peter Otten) Date: Fri, 31 Mar 2017 16:50:43 +0200 Subject: [Tutor] Extract Block of Data from a 2D Array References: <58DE4959.2070605@sbcglobal.net> Message-ID: Stephen P. Molnar wrote: > I have a block of data extracted from a quantum mechanical calculation: > > CARTESIAN COORDINATES (A.U.) > ---------------------------- > NO LB ZA FRAG MASS X Y Z > 0 C 6.0000 0 12.011 -3.265636 0.198894 0.090858 > 1 C 6.0000 0 12.011 -1.307161 1.522212 1.003463 > 2 C 6.0000 0 12.011 1.213336 0.948208 -0.033373 > 3 N 7.0000 0 14.007 3.238650 1.041523 1.301322 > 4 C 6.0000 0 12.011 -5.954489 0.650878 0.803379 > 5 C 6.0000 0 12.011 5.654476 0.480066 0.013757 > > where the number of lines depends upon the molecule being considered. > > I want to extract the block of data starting on line 4 and column 4. > Unfortunately, the only programming language in which I used to be > competent in is Fortran. I have attempted researching this problem, but > have only succeeded in increasing my mental entropy. > > Help will be much appreciated. Thanks in advance. > pandas is the swiss army knife of data manipulation in Python -- albeit with a non-negligable learning curve. Some examples (from an amateur): $ cat data.txt CARTESIAN COORDINATES (A.U.) ---------------------------- NO LB ZA FRAG MASS X Y Z 0 C 6.0000 0 12.011 -3.265636 0.198894 0.090858 1 C 6.0000 0 12.011 -1.307161 1.522212 1.003463 2 C 6.0000 0 12.011 1.213336 0.948208 -0.033373 3 N 7.0000 0 14.007 3.238650 1.041523 1.301322 4 C 6.0000 0 12.011 -5.954489 0.650878 0.803379 5 C 6.0000 0 12.011 5.654476 0.480066 0.013757 $ python3 Python 3.4.3 (default, Nov 17 2016, 01:08:31) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pandas >>> table = pandas.read_table("data.txt", skiprows=2, delimiter=" ", skipinitialspace=True) >>> table NO LB ZA FRAG MASS X Y Z 0 0 C 6 0 12.011 -3.265636 0.198894 0.090858 1 1 C 6 0 12.011 -1.307161 1.522212 1.003463 2 2 C 6 0 12.011 1.213336 0.948208 -0.033373 3 3 N 7 0 14.007 3.238650 1.041523 1.301322 4 4 C 6 0 12.011 -5.954489 0.650878 0.803379 5 5 C 6 0 12.011 5.654476 0.480066 0.013757 [6 rows x 8 columns] >>> table[3:] NO LB ZA FRAG MASS X Y Z 3 3 N 7 0 14.007 3.238650 1.041523 1.301322 4 4 C 6 0 12.011 -5.954489 0.650878 0.803379 5 5 C 6 0 12.011 5.654476 0.480066 0.013757 [3 rows x 8 columns] >>> table[["X", "Y", "Z"]] X Y Z 0 -3.265636 0.198894 0.090858 1 -1.307161 1.522212 1.003463 2 1.213336 0.948208 -0.033373 3 3.238650 1.041523 1.301322 4 -5.954489 0.650878 0.803379 5 5.654476 0.480066 0.013757 [6 rows x 3 columns] >>> table.MASS.mean() 12.343666666666666 From akleider at sonic.net Fri Mar 31 11:44:43 2017 From: akleider at sonic.net (Alex Kleider) Date: Fri, 31 Mar 2017 08:44:43 -0700 Subject: [Tutor] reading files in Python 3 In-Reply-To: <0736889e-d8ea-3c14-aa73-4dc8a31a2906@wichmann.us> References: <0736889e-d8ea-3c14-aa73-4dc8a31a2906@wichmann.us> Message-ID: <7daa65b1dd87e012ece4240396ef0b2c@sonic.net> On 2017-03-30 13:45, Mats Wichmann wrote: > > Yeah, fun. You need to escape the \ that the idiot MS-DOS people chose > for the file path separator. I also believe that the "MS-DOS people" are making a poor choice but to call them idiots is perhaps a bit strong. Remember that for many the use of MicroSoft's OS is not a choice but an edict handed down by superiors, or a requirement caused by other factors. Perhaps "idiot" was meant to apply to the OS, not to it's users? From mats at wichmann.us Fri Mar 31 10:52:58 2017 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 31 Mar 2017 08:52:58 -0600 Subject: [Tutor] Using an XML file for web crawling In-Reply-To: <3AC3A983-A252-4515-B54A-B208051F903A@gmail.com> References: <3AC3A983-A252-4515-B54A-B208051F903A@gmail.com> Message-ID: On 03/31/2017 05:23 AM, Igor Alexandre wrote: > Hi! > I'm a newbie in the Python/Web crawling world. I've been trying to find an answer to the following question since last week, but I couldn't so far, so I decided to ask it myself here: I have a sitemap in XML and I want to use it to save as text the various pages of the site. Do you guys know how can I do it? I'm looking for some code on the web where I can just type the xml address and wait for the crawler to do it's job, saving all the pages indicated in the sitemap as a text file in my computer. > Thank you! > Best, > Igor Alexandre There's a surprisingly active community doing web crawling / scraping stuff... I've gotten the impression that the scrapy project is a "big dog" in this space, but I'm not involved in it so not sure. A couple of links for you to play with: http://docs.python-guide.org/en/latest/scenarios/scrape/ the first part of this might be enough for you - lxml + Requests I just had occasion to look over that page a few days ago, but I'm sure a web search would turn that up easily https://scrapy.org/ there are plenty of other resources, someone is bound to have what you're looking for. From mats at wichmann.us Fri Mar 31 11:51:46 2017 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 31 Mar 2017 09:51:46 -0600 Subject: [Tutor] reading files in Python 3 In-Reply-To: <7daa65b1dd87e012ece4240396ef0b2c@sonic.net> References: <0736889e-d8ea-3c14-aa73-4dc8a31a2906@wichmann.us> <7daa65b1dd87e012ece4240396ef0b2c@sonic.net> Message-ID: <01f7fbda-3512-b500-11fb-746f5cb3b337@wichmann.us> On 03/31/2017 09:44 AM, Alex Kleider wrote: > On 2017-03-30 13:45, Mats Wichmann wrote: > >> >> Yeah, fun. You need to escape the \ that the idiot MS-DOS people chose >> for the file path separator. > > I also believe that the "MS-DOS people" are making a poor choice > but to call them idiots is perhaps a bit strong. > Remember that for many the use of MicroSoft's OS is not a choice but an > edict handed down by superiors, or a requirement caused by other factors. > Perhaps "idiot" was meant to apply to the OS, not to it's users? I'm not sure it's even necessary to clarify, but yes, absolutely - it was referring to the design choice. From poojabhalode11 at gmail.com Fri Mar 31 11:01:48 2017 From: poojabhalode11 at gmail.com (Pooja Bhalode) Date: Fri, 31 Mar 2017 11:01:48 -0400 Subject: [Tutor] All Entry Boxes taking the same value In-Reply-To: References: Message-ID: Hi Peter and Alan, Yes, thank you for your suggestions. I really appreciate it. I would look into a proper tutorial and try to follow it up. The suggestion regarding this piece of code worked when I tried StringVar instead of " ". Thank you once again. Yours truly, Pooja On Fri, Mar 31, 2017 at 6:28 AM, Alan Gauld via Tutor wrote: > On 30/03/17 21:35, Pooja Bhalode wrote: > > > *However, when I execute it, and type something in one entrybox, it shows > > in all the entry boxes using multi-cursor option. * > > I'm not sure whats going on and don;t habe tome to experiment but one > thing I noticed: > > > average = [" ", " ", " "] > > lowest = [" ", " ", " "] > > highest = [" ", " ", " "] > ... > > for i in range(len(reactants)): > > *Entry*(root, textvariable =* average[i]*, width = 15, > > state=DISABLED).grid(row = 3+i, column = 1, sticky = W) > > You are setting textvariable to a string but it should be > a StrinVar object. You could probably fix that by changing > your data definitions to StringVars: > > average = [StringVar(), StringVar(), StringVar()] > > I don't know if that will fix the problem but its probably > a good thing to do anyhow... > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > 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 > From s.molnar at sbcglobal.net Fri Mar 31 10:39:10 2017 From: s.molnar at sbcglobal.net (Stephen P. Molnar) Date: Fri, 31 Mar 2017 10:39:10 -0400 Subject: [Tutor] Extract Block of Data from a 2D Array In-Reply-To: References: <58DE4959.2070605@sbcglobal.net> Message-ID: <58DE6A0E.4050003@sbcglobal.net> On 03/31/2017 10:29 AM, Alan Gauld via Tutor wrote: > On 31/03/17 13:19, Stephen P. Molnar wrote: >> I have a block of data extracted from a quantum mechanical calculation: > > How is this data stored? On paper? In a database? In XML? A CSV file? > Plain text? The answer to that will go a long way to pointing you in the > right direction for a solution. > >> CARTESIAN COORDINATES (A.U.) >> ---------------------------- >> NO LB ZA FRAG MASS X Y Z >> 0 C 6.0000 0 12.011 -3.265636 0.198894 0.090858 >> 1 C 6.0000 0 12.011 -1.307161 1.522212 1.003463 >> 2 C 6.0000 0 12.011 1.213336 0.948208 -0.033373 >> 3 N 7.0000 0 14.007 3.238650 1.041523 1.301322 >> 4 C 6.0000 0 12.011 -5.954489 0.650878 0.803379 >> 5 C 6.0000 0 12.011 5.654476 0.480066 0.013757 >> >> where the number of lines depends upon the molecule being considered. >> >> I want to extract the block of data starting on line 4 and column 4. > > A block of data needs a start and end. Where is the end? > Also which of the above lines is line 4? > I'd read it as the one starting the actual raw data values. > But it could be the 4th line of values that you want? > > It might help to know the OS you are using too because Unix > in particular has some OS level tools that might simplify > preparing the data. > Sorry about the omission. The data is in a tab separated file. -- Stephen P. Molnar, Ph.D. Life is a fuzzy set www.molecular-modeling.net Stochastic and multivariate (614)312-7528 (c) Skype: smolnar1 From s.molnar at sbcglobal.net Fri Mar 31 11:58:28 2017 From: s.molnar at sbcglobal.net (Stephen P. Molnar) Date: Fri, 31 Mar 2017 11:58:28 -0400 Subject: [Tutor] Extract Block of Data from a 2D Array In-Reply-To: References: <58DE4959.2070605@sbcglobal.net> Message-ID: <58DE7CA4.6050600@sbcglobal.net> On 03/31/2017 10:50 AM, Peter Otten wrote: > Stephen P. Molnar wrote: > >> I have a block of data extracted from a quantum mechanical calculation: >> >> CARTESIAN COORDINATES (A.U.) >> ---------------------------- >> NO LB ZA FRAG MASS X Y Z >> 0 C 6.0000 0 12.011 -3.265636 0.198894 0.090858 >> 1 C 6.0000 0 12.011 -1.307161 1.522212 1.003463 >> 2 C 6.0000 0 12.011 1.213336 0.948208 -0.033373 >> 3 N 7.0000 0 14.007 3.238650 1.041523 1.301322 >> 4 C 6.0000 0 12.011 -5.954489 0.650878 0.803379 >> 5 C 6.0000 0 12.011 5.654476 0.480066 0.013757 >> >> where the number of lines depends upon the molecule being considered. >> >> I want to extract the block of data starting on line 4 and column 4. >> Unfortunately, the only programming language in which I used to be >> competent in is Fortran. I have attempted researching this problem, but >> have only succeeded in increasing my mental entropy. >> >> Help will be much appreciated. Thanks in advance. >> > > pandas is the swiss army knife of data manipulation in Python -- albeit with > a non-negligable learning curve. Some examples (from an amateur): > > $ cat data.txt > CARTESIAN COORDINATES (A.U.) > ---------------------------- > NO LB ZA FRAG MASS X Y Z > 0 C 6.0000 0 12.011 -3.265636 0.198894 0.090858 > 1 C 6.0000 0 12.011 -1.307161 1.522212 1.003463 > 2 C 6.0000 0 12.011 1.213336 0.948208 -0.033373 > 3 N 7.0000 0 14.007 3.238650 1.041523 1.301322 > 4 C 6.0000 0 12.011 -5.954489 0.650878 0.803379 > 5 C 6.0000 0 12.011 5.654476 0.480066 0.013757 > $ python3 > Python 3.4.3 (default, Nov 17 2016, 01:08:31) > [GCC 4.8.4] on linux > Type "help", "copyright", "credits" or "license" for more information. >>>> import pandas >>>> table = pandas.read_table("data.txt", skiprows=2, delimiter=" ", > skipinitialspace=True) >>>> table > NO LB ZA FRAG MASS X Y Z > 0 0 C 6 0 12.011 -3.265636 0.198894 0.090858 > 1 1 C 6 0 12.011 -1.307161 1.522212 1.003463 > 2 2 C 6 0 12.011 1.213336 0.948208 -0.033373 > 3 3 N 7 0 14.007 3.238650 1.041523 1.301322 > 4 4 C 6 0 12.011 -5.954489 0.650878 0.803379 > 5 5 C 6 0 12.011 5.654476 0.480066 0.013757 > > [6 rows x 8 columns] >>>> table[3:] > NO LB ZA FRAG MASS X Y Z > 3 3 N 7 0 14.007 3.238650 1.041523 1.301322 > 4 4 C 6 0 12.011 -5.954489 0.650878 0.803379 > 5 5 C 6 0 12.011 5.654476 0.480066 0.013757 > > [3 rows x 8 columns] >>>> table[["X", "Y", "Z"]] > X Y Z > 0 -3.265636 0.198894 0.090858 > 1 -1.307161 1.522212 1.003463 > 2 1.213336 0.948208 -0.033373 > 3 3.238650 1.041523 1.301322 > 4 -5.954489 0.650878 0.803379 > 5 5.654476 0.480066 0.013757 > > [6 rows x 3 columns] >>>> table.MASS.mean() > 12.343666666666666 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Problem solved! Many thanks. -- Stephen P. Molnar, Ph.D. Life is a fuzzy set www.molecular-modeling.net Stochastic and multivariate (614)312-7528 (c) Skype: smolnar1 From eryksun at gmail.com Fri Mar 31 16:42:06 2017 From: eryksun at gmail.com (eryk sun) Date: Fri, 31 Mar 2017 20:42:06 +0000 Subject: [Tutor] reading files in Python 3 In-Reply-To: <0736889e-d8ea-3c14-aa73-4dc8a31a2906@wichmann.us> References: <0736889e-d8ea-3c14-aa73-4dc8a31a2906@wichmann.us> Message-ID: On Thu, Mar 30, 2017 at 8:45 PM, Mats Wichmann wrote: > Yeah, fun. You need to escape the \ that the idiot MS-DOS people chose > for the file path separator. Because \ is treated as an escape character. The COMMAND.COM shell inherited command-line switches (options) that use slash from TOPS-10 by way of CP/M, so using backslash in paths was less ambiguous for the shell (e.g. dir/w could be intended to run "w" in the "dir" subdirectory, or it could mean to run "dir" with the option "/w"). The DOS kernel did support both slash and backslash in file-system paths. Also, C wasn't a common language on the PC back then. BASIC was. Instead of using escapes in string literals, BASIC used addition at runtime with the CHR$ function or predefined constants. Support for hierarchical paths (DOS 2.0) came around at about the same time that C was rising in popularity, so the pain came on slowly like boiling a lobster. The system designers who really have no excuse are the NT kernel developers circa 1988-93. They were working in C on a system that already required converting paths from the DOS namespace to a native object namespace. They could have easily implemented the native object system to use slash instead of backslash. From cs at zip.com.au Fri Mar 31 18:38:24 2017 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 1 Apr 2017 09:38:24 +1100 Subject: [Tutor] subprocess.Popen / proc.communicate issue In-Reply-To: References: Message-ID: <20170331223824.GA43954@cskk.homeip.net> On 31Mar2017 06:13, eryk sun wrote: >On Thu, Mar 30, 2017 at 10:51 PM, Cameron Simpson wrote: >> This suggests that .communicate uses Threads to send and to gather data >> independently, and that therefore the deadlock situation may not arise. > >For Unix, communicate() uses select or poll. It uses threads on >Windows. Either way it avoids deadlocking. Good to know. Thanks! Cheers, Cameron Simpson From ejmmanning at gmail.com Fri Mar 31 19:35:48 2017 From: ejmmanning at gmail.com (Ed Manning) Date: Fri, 31 Mar 2017 19:35:48 -0400 Subject: [Tutor] Validating String contains IP address Message-ID: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com> What's the best way to validate a string contains a IP address Sent from my iPad From alan.gauld at yahoo.co.uk Fri Mar 31 19:52:34 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 1 Apr 2017 00:52:34 +0100 Subject: [Tutor] Validating String contains IP address In-Reply-To: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com> References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com> Message-ID: On 01/04/17 00:35, Ed Manning wrote: > > What's the best way to validate a string contains a IP address It depends on how thorough you want to be. You can define a regex to check that its 4 groups of numbers separated by periods. Or you can split the string into fields and validate that the values are each less than 255 Or you could try connecting to it and see if you get a response... How sure do you need to be? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From martin at linux-ip.net Fri Mar 31 20:04:49 2017 From: martin at linux-ip.net (Martin A. Brown) Date: Fri, 31 Mar 2017 17:04:49 -0700 Subject: [Tutor] Validating String contains IP address In-Reply-To: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com> References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com> Message-ID: Hello there, >What's the best way to validate a string contains a IP address If you are only talking about validating that something is an IP address, then I can even give you a little Python2 / Python3 snippet that can do that. I like the EAFP [0] approach for this sort of thing. There are slight differences between the python2 third-party module ipaddr [1] and the python3 standard ipaddress module [2]. The latter is (I think) name-changed from the former, although I'm not utterly sure of the history here. These two modules both parse IPs (and have tools to allow you to parse IPv6 and IPv4 IPs and prefixes). So, rather than try to build your own, why not grab something convenient from the (batteries-included) shelf? Note, if you actually want to do something with the IP address (convert to use for socket operations, store in a binary format somewhere, use in network bitmath operations), then you'll want to study these libraries and possibly also the socket [3] library. But, if all you want to know is whether somebody provided a string that is a valid IP (whether network address, host address or broadcast address), you can use this little snippet: from __future__ import print_function import sys try: from ipaddress import ip_address as ipo except ImportError: from ipaddr import IPAddress as ipo for arg in sys.argv[1:]: try: ipo(arg) print("%s is an IP." % (arg,)) except ValueError: print("%s is not an IP." % (arg,)) When I save and run this (works the same in Python2 or Python3): $ python isarganip.py 192.168.7.0 192.168.7.256 192.v.12.7 text fe80::a64e:31ff:fe94:a160 255.255.255.255 0.0.0.0 192.168.7.0 is an IP. 192.168.7.256 is not an IP. 192.v.12.7 is not an IP. text is not an IP. fe80::a64e:31ff:fe94:a160 is an IP. 255.255.255.255 is an IP. 0.0.0.0 is an IP. Basically, I'm lazy. I let somebody else do the hard work of validation! Good luck and happy IParsing! -Martin [0] http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-try-except-example [1] https://pypi.python.org/pypi/ipaddr [2] https://docs.python.org/3/library/ipaddress.html [3] https://docs.python.org/2/library/socket.html https://docs.python.org/3/library/socket.html -- Martin A. Brown http://linux-ip.net/ From akleider at sonic.net Fri Mar 31 20:44:22 2017 From: akleider at sonic.net (Alex Kleider) Date: Fri, 31 Mar 2017 17:44:22 -0700 Subject: [Tutor] Validating String contains IP address In-Reply-To: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com> References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com> Message-ID: <1ed449a7f8df0961bdcc3fc2bd652281@sonic.net> On 2017-03-31 16:35, Ed Manning wrote: > What's the best way to validate a string contains a IP address > Sent from my iPad > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor The re module perhaps? How about: import re ip_regex = r""" [12]?\d?\d[.] [12]?\d?\d[.] [12]?\d?\d[.] [12]?\d?\d """ ip_pattern = re.compile(ip_regex, re.VERBOSE) # then test for ip_pattern.search(source).group(): res = ip_pattern.search(source).group() if res: print("IP is {}".format(res)) else: print("Source doesn't contain an IP address") # This assumes that an address would never be written as follows: 076.191.211.205 From mats at wichmann.us Fri Mar 31 21:01:24 2017 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 31 Mar 2017 19:01:24 -0600 Subject: [Tutor] Validating String contains IP address In-Reply-To: <1ed449a7f8df0961bdcc3fc2bd652281@sonic.net> References: <24D5C14C-A283-4EFF-BA61-5B6EA90C1195@gmail.com> <1ed449a7f8df0961bdcc3fc2bd652281@sonic.net> Message-ID: <626b369a-337c-e9f5-aa77-77dc90f56082@wichmann.us> On 03/31/2017 06:44 PM, Alex Kleider wrote: > On 2017-03-31 16:35, Ed Manning wrote: >> What's the best way to validate a string contains a IP address >> Sent from my iPad >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > > The re module perhaps? > > How about: > > import re > > ip_regex = r""" > [12]?\d?\d[.] > [12]?\d?\d[.] > [12]?\d?\d[.] > [12]?\d?\d > """ > > ip_pattern = re.compile(ip_regex, re.VERBOSE) > > # then test for ip_pattern.search(source).group(): > res = ip_pattern.search(source).group() > if res: > print("IP is {}".format(res)) > else: > print("Source doesn't contain an IP address") > > # This assumes that an address would never be written as follows: > 076.191.211.205 This assumes "an IP address" is the four dotted numbers characteristic of IPv4. These days that's a bad assumption unless you're absolutely sure an IPv6 address can never appear. Can you?