From alan.gauld at yahoo.co.uk Thu Oct 1 04:49:35 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 1 Oct 2020 09:49:35 +0100 Subject: [Tutor] How to work with a later version of Python In-Reply-To: References: Message-ID: On 30/09/2020 23:58, Neveills, Sarah wrote: > I have version 3.8.3 of Python installed on my MAC OS. > > The homework I need to do will only work with version 3.6 (and no later or > earlier). That's very unlikely. Python versions are intended to be backwardly compatible so any 3.6 code should work on 3.8. It would need to be deliberately written to prevent forward compatibility which would be very odd, or it would need to use some very specialized libraries. Have you tried it? > I have downloaded Python 3.6, but how do I work in version 3.6 > instead of 3.8.3? At the simplest level you can simply call the python3.6 interpreter explicitly. The best solution would be to create a virtual environment. If you do a search for python virtual environment you should find a wealth of material. > I need to figure out how to switch between editions...please advise. I'd check first that your code really won't work in 3.8. -- 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 Oct 1 04:57:27 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 1 Oct 2020 09:57:27 +0100 Subject: [Tutor] Install In-Reply-To: References: Message-ID: On 01/10/2020 04:15, Manprit Singh wrote: > I would suggest, to go for a linux distribution, specially i found Fedora - > 32 very good for Python system. While I agree that Linux is a good solution for programming in general and python in particular I don't think its a realistic solution for a Windows user with one single program that doesn't run. This would be especially true in a work environment where IT support, network connectivity, and other bespoke programs may need to be used. However, if this is a personal PC then a switch of OS (or dual boot) might be viable. Or as a half way house install cygwin which provides most of Linux advantages inside Windows. (You might have succcess with the Linux Subsystem for Windows(LSW?) but I don't think it has the same app-store support as cygwin yet) But the simplest option is simply install a new version 3.7. Mats has suggested trying the windows store version, which is a very good idea. Alan G. > On Wed, Sep 30, 2020 at 9:34 PM dj brace wrote: > >> Hello for some reason I'm having trouble installing python 3.7 on Windows >> 10 it needs to be under 3.8 for this program I'm using was working before >> and now it says that it's just not showing up I tried to add it to the path >> any help would be really appreciated I'm kind of a novice but I had it >> working yesterday I'm really not sure what changed please I have a >> presentation today and it would be really helpful if you could advise again >> when I try to run the application it tells me that Python 3 is not >> installed >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- 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 1611kjb at gmail.com Thu Oct 1 05:36:47 2020 From: 1611kjb at gmail.com (Michael Deslippe) Date: Thu, 1 Oct 2020 09:36:47 +0000 Subject: [Tutor] How to work with a later version of Python In-Reply-To: References: , Message-ID: The actual runtimes each have a unique name and neither has version dependencies in general distributions. What that means python 3.8.3 will run by starting application python383 and python 3.6 will run on python36. You?ll find both if you search with application launcher. I run the latest stable version and the latest beta version at the same time and it works fine. If you are certain there?s a reason to only run 3.6, which subversion do you require for 3.6? There are actually 12 subversions from 3.6.0 to 3.6.12. They are all 3.6, but different subversions moving towards the next release. Which can you se? ?-Mike ---Mike ________________________________ From: Tutor on behalf of Alan Gauld via Tutor Sent: Thursday, October 1, 2020 4:49:35 AM To: tutor at python.org Subject: Re: [Tutor] How to work with a later version of Python On 30/09/2020 23:58, Neveills, Sarah wrote: > I have version 3.8.3 of Python installed on my MAC OS. > > The homework I need to do will only work with version 3.6 (and no later or > earlier). That's very unlikely. Python versions are intended to be backwardly compatible so any 3.6 code should work on 3.8. It would need to be deliberately written to prevent forward compatibility which would be very odd, or it would need to use some very specialized libraries. Have you tried it? > I have downloaded Python 3.6, but how do I work in version 3.6 > instead of 3.8.3? At the simplest level you can simply call the python3.6 interpreter explicitly. The best solution would be to create a virtual environment. If you do a search for python virtual environment you should find a wealth of material. > I need to figure out how to switch between editions...please advise. I'd check first that your code really won't work in 3.8. -- 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 manpritsinghece at gmail.com Fri Oct 2 13:07:53 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 2 Oct 2020 22:37:53 +0530 Subject: [Tutor] float.is_integer() Message-ID: Dear Sir, Kindly look at the below experiment done on python IDLE Shell : >>> (2.0).is_integer() True >>> (2.4).is_integer() False >>> (234.77777777777777).is_integer() False >>> (23444444444444444.7777).is_integer() True >>> (234444444444444.73).is_integer() False >>> (23444444444444444444444.73).is_integer() True Just need to know why the 4th and 6th lines return True, It should be False. Is there any limitation on using this float.is_integer() method ? Regards Manprit singh From sarah.neveills at usuhs.edu Fri Oct 2 12:21:28 2020 From: sarah.neveills at usuhs.edu (Neveills, Sarah) Date: Fri, 2 Oct 2020 10:21:28 -0600 Subject: [Tutor] How to work with a later version of Python In-Reply-To: References: Message-ID: All, My teacher said we would encounter issues completing our homework if we are running a version past 3.6. Apparently the files, functions, and the commands listed in our Project book were written for 3.6 and they throw errors on a newer version. I am a novice and this is my first class regarding machine learning. Is there a website to easily get the new functions and files? I will email back the errors I get and hopefully someone can guide me in the right direction for trouble-shooting. Sarah On Thu, Oct 1, 2020 at 4:37 AM Michael Deslippe <1611kjb at gmail.com> wrote: > The actual runtimes each have a unique name and neither has version > dependencies in general distributions. What that means python 3.8.3 will > run by starting application python383 and python 3.6 will run on python36. > You?ll find both if you search with application launcher. I run the latest > stable version and the latest beta version at the same time and it works > fine. If you are certain there?s a reason to only run 3.6, which subversion > do you require for 3.6? There are actually 12 subversions from 3.6.0 to > 3.6.12. They are all 3.6, but different subversions moving towards the next > release. Which can you se? > > > > ?-Mike > > > > ---Mike > > ________________________________ > > From: Tutor on behalf of > Alan Gauld via Tutor > > Sent: Thursday, October 1, 2020 4:49:35 AM > > To: tutor at python.org > > Subject: Re: [Tutor] How to work with a later version of Python > > > > On 30/09/2020 23:58, Neveills, Sarah wrote: > > > > > I have version 3.8.3 of Python installed on my MAC OS. > > > > > > The homework I need to do will only work with version 3.6 (and no later > or > > > earlier). > > > > That's very unlikely. Python versions are intended to be backwardly > > compatible so any 3.6 code should work on 3.8. It would need to be > > deliberately written to prevent forward compatibility which would be > > very odd, or it would need to use some very specialized libraries. > > > > Have you tried it? > > > > > I have downloaded Python 3.6, but how do I work in version 3.6 > > > instead of 3.8.3? > > > > At the simplest level you can simply call the python3.6 > > interpreter explicitly. > > > > The best solution would be to create a virtual environment. > > If you do a search for python virtual environment you should > > find a wealth of material. > > > > > I need to figure out how to switch between editions...please advise. > > > > I'd check first that your code really won't work in 3.8. > > > > -- > > 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 > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > From sarah.neveills at usuhs.edu Fri Oct 2 14:15:04 2020 From: sarah.neveills at usuhs.edu (Neveills, Sarah) Date: Fri, 2 Oct 2020 12:15:04 -0600 Subject: [Tutor] How to work with a later version of Python In-Reply-To: References: Message-ID: All, I cannot import the keras package in version 3.8.3. It states no module named ?keras? Any suggestions? Sarah On Fri, Oct 2, 2020 at 10:21 AM Neveills, Sarah wrote: > All, > > My teacher said we would encounter issues completing our homework if we > are running a version past 3.6. > > Apparently the files, functions, and the commands listed in our Project > book were written for 3.6 and they throw errors on a newer version. > > I am a novice and this is my first class regarding machine learning. > > Is there a website to easily get the new functions and files? > > I will email back the errors I get and hopefully someone can guide me in > the right direction for trouble-shooting. > > Sarah > > On Thu, Oct 1, 2020 at 4:37 AM Michael Deslippe <1611kjb at gmail.com> wrote: > >> The actual runtimes each have a unique name and neither has version >> dependencies in general distributions. What that means python 3.8.3 will >> run by starting application python383 and python 3.6 will run on python36. >> You?ll find both if you search with application launcher. I run the latest >> stable version and the latest beta version at the same time and it works >> fine. If you are certain there?s a reason to only run 3.6, which subversion >> do you require for 3.6? There are actually 12 subversions from 3.6.0 to >> 3.6.12. They are all 3.6, but different subversions moving towards the next >> release. Which can you se? >> >> >> >> ?-Mike >> >> >> >> ---Mike >> >> ________________________________ >> >> From: Tutor on behalf of >> Alan Gauld via Tutor >> >> Sent: Thursday, October 1, 2020 4:49:35 AM >> >> To: tutor at python.org >> >> Subject: Re: [Tutor] How to work with a later version of Python >> >> >> >> On 30/09/2020 23:58, Neveills, Sarah wrote: >> >> >> >> > I have version 3.8.3 of Python installed on my MAC OS. >> >> > >> >> > The homework I need to do will only work with version 3.6 (and no later >> or >> >> > earlier). >> >> >> >> That's very unlikely. Python versions are intended to be backwardly >> >> compatible so any 3.6 code should work on 3.8. It would need to be >> >> deliberately written to prevent forward compatibility which would be >> >> very odd, or it would need to use some very specialized libraries. >> >> >> >> Have you tried it? >> >> >> >> > I have downloaded Python 3.6, but how do I work in version 3.6 >> >> > instead of 3.8.3? >> >> >> >> At the simplest level you can simply call the python3.6 >> >> interpreter explicitly. >> >> >> >> The best solution would be to create a virtual environment. >> >> If you do a search for python virtual environment you should >> >> find a wealth of material. >> >> >> >> > I need to figure out how to switch between editions...please advise. >> >> >> >> I'd check first that your code really won't work in 3.8. >> >> >> >> -- >> >> 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 >> >> _______________________________________________ >> >> 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 Fri Oct 2 19:13:14 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 3 Oct 2020 00:13:14 +0100 Subject: [Tutor] How to work with a later version of Python In-Reply-To: References: Message-ID: On 02/10/2020 17:21, Neveills, Sarah wrote: > My teacher said we would encounter issues completing our homework if we are > running a version past 3.6. > > Apparently the files, functions, and the commands listed in our Project > book were written for 3.6 and they throw errors on a newer version. I'm intrigued about what errors they are getting and what kind of code they wrote to produce them! But its not completely unheard of in non standard libraries so it may be that you need 3.6 after all... > Is there a website to easily get the new functions and files? No idea, sorry. I've never heard of keras... > I will email back the errors I get and hopefully someone can guide me in > the right direction for trouble-shooting. Please do. Although initially it may just be path settings etc. -- 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 Oct 2 19:17:33 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 3 Oct 2020 00:17:33 +0100 Subject: [Tutor] float.is_integer() In-Reply-To: References: Message-ID: On 02/10/2020 18:07, Manprit Singh wrote: >>>> (23444444444444444.7777).is_integer() > True How weird. I get the same result and the documentation is so sparse that it's of no real help. Hopefully somebody else can shed some light on it. Or maybe you've actually found a bug! But I suspect the answer will lie in one of those odd binary level features of floats... But too subtle for me! -- 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 chris_roysmith at internode.on.net Fri Oct 2 19:27:03 2020 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Sat, 3 Oct 2020 09:27:03 +1000 Subject: [Tutor] How to work with a later version of Python In-Reply-To: References: Message-ID: <6d12c90b-d00d-de72-cd1e-31cc9f59b079@internode.on.net> On 3/10/20 9:13 am, Alan Gauld via Tutor wrote: > On 02/10/2020 17:21, Neveills, Sarah wrote: > >> My teacher said we would encounter issues completing our homework if we are >> running a version past 3.6. according to https://pypi.org/project/Keras/, keras requires 3.6+, so doesn't that mean that versions later than 3.6 are also supported? >> >> Apparently the files, functions, and the commands listed in our Project >> book were written for 3.6 and they throw errors on a newer version. > > I'm intrigued about what errors they are getting and what kind of > code they wrote to produce them! But its not completely unheard > of in non standard libraries so it may be that you need 3.6 > after all... > >> Is there a website to easily get the new functions and files? > > No idea, sorry. I've never heard of keras... > >> I will email back the errors I get and hopefully someone can guide me in >> the right direction for trouble-shooting. > > Please do. Although initially it may just be path settings etc. > From mats at wichmann.us Fri Oct 2 19:40:04 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 2 Oct 2020 17:40:04 -0600 Subject: [Tutor] How to work with a later version of Python In-Reply-To: References: Message-ID: On 10/2/20 12:15 PM, Neveills, Sarah wrote: > All, > > I cannot import the keras package in version 3.8.3. > > It states no module named ?keras? > > Any suggestions? > > Sarah Probably, it's not installed. Each version of Python gets its own installation area, so a package installed for a different Python version would not get picked up. Keras itself, it looks like, has no version issues. You can check these things by going to PyPI: https://pypi.org/project/Keras/#files The naming of the installable suggests it's very flexible: Keras-2.4.3-py2.py3-none-any.whl that is, there's no Python version dependency, there's no operating system dependency, and there's no processor architecture dependency. So with the Python you intend to use, try: python -m pip install keras That has a good chance of taking care of the import problem. From zachary.ware+pytut at gmail.com Fri Oct 2 20:08:16 2020 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Fri, 2 Oct 2020 19:08:16 -0500 Subject: [Tutor] float.is_integer() In-Reply-To: References: Message-ID: Have a look at the repr of 23444444444444444.7777; a 64 bit floating point number cannot represent that number exactly. -- Zach (On a phone) On Fri, Oct 2, 2020, 18:20 Alan Gauld via Tutor wrote: > On 02/10/2020 18:07, Manprit Singh wrote: > > >>>> (23444444444444444.7777).is_integer() > > True > > How weird. I get the same result and the documentation is so > sparse that it's of no real help. > > Hopefully somebody else can shed some light on it. > Or maybe you've actually found a bug! But I suspect the answer > will lie in one of those odd binary level features of floats... > But too subtle for me! > > -- > 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 Richard at Damon-Family.org Fri Oct 2 20:14:59 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Fri, 2 Oct 2020 20:14:59 -0400 Subject: [Tutor] float.is_integer() In-Reply-To: References: Message-ID: <3a0ab6e4-afc6-5371-41d9-fcd7a27256a7@Damon-Family.org> On 10/2/20 1:07 PM, Manprit Singh wrote: > Dear Sir, > > Kindly look at the below experiment done on python IDLE Shell : > > (2.0).is_integer() > True > (2.4).is_integer() > False > (234.77777777777777).is_integer() > False > (23444444444444444.7777).is_integer() > True > (234444444444444.73).is_integer() > False > (23444444444444444444444.73).is_integer() > True > > Just need to know why the 4th and 6th lines return True, It should be > False. Is > there any limitation on using this float.is_integer() method ? > > Regards > Manprit singh The basic answer is that floating point numbers have only finite precision, so numbers of large enough magnitude will no longer have any fractional bits. The number 23444444444444444.7777 is big enough that the 0.777 can't be represented, so the number you actually get is just 23444444444444444.0 which is of course is the value of an integer. -- Richard Damon From alan.gauld at yahoo.co.uk Sat Oct 3 05:51:34 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 3 Oct 2020 10:51:34 +0100 Subject: [Tutor] float.is_integer() In-Reply-To: References: Message-ID: On 03/10/2020 01:08, Zachary Ware wrote: > Have a look at the repr of 23444444444444444.7777; a 64 bit floating point > number cannot represent that number exactly. So basically the float is just too big to include the fractional part. Hmm, I wonder where the break off point is? Time to do some math... Or play with the interpreter! :-) -- 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 breamoreboy at gmail.com Fri Oct 2 19:05:09 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sat, 3 Oct 2020 00:05:09 +0100 Subject: [Tutor] How to work with a later version of Python In-Reply-To: References: Message-ID: On 02/10/2020 19:15, Neveills, Sarah wrote: > All, > > I cannot import the keras package in version 3.8.3. > > It states no module named ?keras? > > Any suggestions? > > Sarah > 'keras' isn't part of the standard library so you'll need to install it from a command prompt:- python -m pip install keras Also please trim your responses as I've done here and don't top post, it drives me nuts :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From Richard at Damon-Family.org Sat Oct 3 08:53:49 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Sat, 3 Oct 2020 08:53:49 -0400 Subject: [Tutor] float.is_integer() In-Reply-To: References: Message-ID: On 10/3/20 5:51 AM, Alan Gauld via Tutor wrote: > On 03/10/2020 01:08, Zachary Ware wrote: >> Have a look at the repr of 23444444444444444.7777; a 64 bit floating point >> number cannot represent that number exactly. > So basically the float is just too big to include the fractional part. > Hmm, I wonder where the break off point is? Time to do some math... > Or play with the interpreter! :-) > Python floating point numbers have 52 significant bits + implied leading 1 + sign bit. Numbers less than 2^52 have fractional bits, 2^52 and bigger can not. -- Richard Damon From gskeerthanaa22 at gmail.com Sat Oct 3 07:25:53 2020 From: gskeerthanaa22 at gmail.com (Keerthanaa GS) Date: Sat, 3 Oct 2020 16:55:53 +0530 Subject: [Tutor] Project help Message-ID: hello sir/madam I have to do a project on timetable management.i am half way through it . i have actually done the coding in such a way that it asks for the input of every subject for given timeslots from monday to friday and the input given by the user is automatically saved in the csv file.So my doubt is how to get the input from the user about the teachers name for each subject . And it should also ask if the teacher is present or not.So if the teacher is not present then it should do a substitution of teacher who is free for that slot The coding is attached below Kindly help me with this project. Regards Keerthanaa From breamoreboy at gmail.com Sat Oct 3 11:00:20 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sat, 3 Oct 2020 16:00:20 +0100 Subject: [Tutor] Project help In-Reply-To: References: Message-ID: On 03/10/2020 12:25, Keerthanaa GS wrote: > hello sir/madam > I have to do a project on timetable management.i am half way through it . > i have actually done the coding in such a way that it asks for the input of > every subject for given timeslots from monday to friday and the input given > by the user is automatically saved in the csv file.So my doubt is how to > get the input from the user about the teachers name for each subject . And > it should also ask if the teacher is present or not.So if the teacher is > not present then it should do a substitution of teacher who is free for > that slot > The coding is attached below This is a text only emailing list in which attachments get stripped off so please cut and paste your code. > Kindly help me with this project. > > Regards > Keerthanaa > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From manpritsinghece at gmail.com Sat Oct 3 15:18:25 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 4 Oct 2020 00:48:25 +0530 Subject: [Tutor] Using built-in divmod( ) function Message-ID: Dear sir , Consider a problem , where i have to write a program which converts an integer to its binary equivalent. I have seen so many books following this approach: x = int(input("Enter a number")) b, i = 0, 0 while x != 0: r = x % 2 b = b + (r * (10**i)) x = x // 2 i = i + 1 print(b) Upon a user input =10, the value b (or the desired output ) becomes 1010 which is the right answer . Now m y question is why we are not using a divmod operator in this case ? I would prefer writing the above program in the following way, using divmod( ) : x = int(input("Enter a number")) b, i = 0, 0 while x != 0: x, r = divmod(x, 2) b = b + (r * (10**i)) i = i + 1 print(b) What way should i prefer ? need your suggestions . Regards Manprit Singh From cs at cskk.id.au Sat Oct 3 17:11:22 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 4 Oct 2020 08:11:22 +1100 Subject: [Tutor] Using built-in divmod( ) function In-Reply-To: References: Message-ID: <20201003211122.GA26678@cskk.homeip.net> On 04Oct2020 00:48, Manprit Singh wrote: >Consider a problem , where i have to write a program which converts an >integer to its binary equivalent. I have seen so many books following this >approach: > >x = int(input("Enter a number")) >b, i = 0, 0 >while x != 0: > r = x % 2 > b = b + (r * (10**i)) > x = x // 2 > i = i + 1 >print(b) > >Upon a user input =10, the value b (or the desired output ) becomes 1010 >which is the right answer . Now m y question is why we are not using a >divmod operator in this case ? I would prefer writing the above program in >the following way, using divmod( ) : > >x = int(input("Enter a number")) >b, i = 0, 0 >while x != 0: > x, r = divmod(x, 2) > b = b + (r * (10**i)) > i = i + 1 >print(b) > >What way should i prefer ? need your suggestions . I would prefer your way - it is shorter and probably faster. And once the reader has looked up divmod(), it is clearer because the divmod() encapsulates the relationship of the formerly separate % and // lines. The former method has the advantage that it spells our each operation, which is useful from a teaching perspective. All that said, they are both bad. Why? Because they produce an integer which is not the original value, it just _happens_ to be printed out _like_ the binary representation of the original value when rendered in base 10. If I were decomposing a value into its binary form I would want to get an array of bits, not a (much larger) value which happened to "print right". If I want something _printed_ in base 2 I've usualy reach for the bin() function, which produces a _string_. Cheers, Cameron Simpson From aklein85 at yahoo.com Sat Oct 3 17:14:14 2020 From: aklein85 at yahoo.com (Aaron Klein) Date: Sat, 3 Oct 2020 21:14:14 +0000 (UTC) Subject: [Tutor] Question References: <1609987192.1617949.1601759654303.ref@mail.yahoo.com> Message-ID: <1609987192.1617949.1601759654303@mail.yahoo.com> Hi, I'm learning Python and am confused by nesting 'while' loops. My program should ask the user if they'd like to play again after guessing the number correctly. I'm not sure what variables to use in the outer loop. Do I create new ones? Thankd in advance for any suggestions! import random #seed random numberrandom.seed() #prime loopcount = 1 while():? ? #prime nested loop? ? guess = int(input('Guess a number between 1 and 10\n'))? ? num = random.randint(1, 10)? ? while(guess != num):? ? ? ? guess = int(input('Guess a number between 1 and 10\n'))? ? ? ? count+=1? ??print('It took', count, 'guesses to guess correctly.')playAgain = str(input('Would you like to play again?\n')) From breamoreboy at gmail.com Sat Oct 3 19:26:42 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 4 Oct 2020 00:26:42 +0100 Subject: [Tutor] Question In-Reply-To: <1609987192.1617949.1601759654303@mail.yahoo.com> References: <1609987192.1617949.1601759654303.ref@mail.yahoo.com> <1609987192.1617949.1601759654303@mail.yahoo.com> Message-ID: On 03/10/2020 22:14, Aaron Klein via Tutor wrote: > Hi, > I'm learning Python and am confused by nesting 'while' loops. My program should ask the user if they'd like to play again after guessing the number correctly. I'm not sure what variables to use in the outer loop. Do I create new ones? Thankd in advance for any suggestions! > > > import random > #seed random numberrandom.seed() > #prime loopcount = 1 > > while():? ? #prime nested loop? ? guess = int(input('Guess a number between 1 and 10\n'))? ? num = random.randint(1, 10)? ? while(guess != num):? ? ? ? guess = int(input('Guess a number between 1 and 10\n'))? ? ? ? count+=1? ??print('It took', count, 'guesses to guess correctly.')playAgain = str(input('Would you like to play again?\n')) > Let's see if we can correct that formatting. while(): #prime nested loop The while() will never run as the () is actually an empty tuple which always tests as false. guess = int(input('Guess a number between 1 and 10\n')) num = random.randint(1, 10) while guess != num: # we'll remove the unwanted brackets, no idea why people like typing them. guess = int(input('Guess a number between 1 and 10\n')) count+=1 The above will fail as 'count' doesn't yet exist, you'll need to initialise it outside the inner loop. print('It took', count, 'guesses to guess correctly.') playAgain = str(input('Would you like to play again?\n')) 'playAgain' should be tested at the outer loop instead of the empty tuple. 'input' always returns a string so no need for the call to 'str'. I think as I'm knackered, chronic fatigue syndrome is a bummer :-( -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at yahoo.co.uk Sat Oct 3 19:38:26 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 4 Oct 2020 00:38:26 +0100 Subject: [Tutor] Using built-in divmod( ) function In-Reply-To: References: Message-ID: On 03/10/2020 20:18, Manprit Singh wrote: > Consider a problem , where i have to write a program which converts an > integer to its binary equivalent. integers are stored in binary on the computer, there is no need to convert it to binary. It is already there. You may be thinking of its binary representation, which is a string that appears when we print it. That can be achieved using the built in bin() function. > I have seen so many books following this > approach: > > x = int(input("Enter a number")) > b, i = 0, 0 > while x != 0: > r = x % 2 > b = b + (r * (10**i)) > x = x // 2 > i = i + 1 > print(b) This is a variant of the classic "find the binary representation of a decimal number" algorithm we all learnt in high school. Except this one produces a decimal number that looks like a binary number, which is plain wrong! Now we have two different integers both stored in binary and printing differently. > .... Now m y question is why we are not using a > divmod operator in this case ? Most languages do not have a single divmod() function. So basic algorithm classes won;t use it. But if you are doing a divmod operation, as here, it makes sense to use it if available. But it makes even more sense to use a function that does what was asked in the first place, namely bin() -- 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 Sat Oct 3 19:49:23 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 4 Oct 2020 00:49:23 +0100 Subject: [Tutor] Question In-Reply-To: <1609987192.1617949.1601759654303@mail.yahoo.com> References: <1609987192.1617949.1601759654303.ref@mail.yahoo.com> <1609987192.1617949.1601759654303@mail.yahoo.com> Message-ID: On 03/10/2020 22:14, Aaron Klein via Tutor wrote: > ... I'm not sure what variables to use in the outer loop. > Do I create new ones? Don't be afraid of creating variables. It's usually a good thing and adds to the clarity of the program, if you name them sensibly and they actually have a purpose. > while():? ? #prime nested loop? ? guess = int(input('Guess a number between 1 and 10\n'))? ? num = random.randint(1, 10)? ? while(guess != num):? ? ? ? guess = int(input('Guess a number between 1 and 10\n'))? ? ? ? count+=1? ??print('It took', count, 'guesses to guess correctly.')playAgain = str(input('Would you like to play again?\n')) Unfortunately the list requires plain text format for code otherwise we lose all the indentation and structure, as you can see here. Taking a stab at reformatting it I get: while(): #prime nested loop guess = int(input('Guess a number between 1 and 10\n')) num = random.randint(1, 10) while(guess != num): guess = int(input('Guess a number between 1 and 10\n')) count+=1 print('It took', count, 'guesses to guess correctly.') playAgain = str(input('Would you like to play again?\n')) If I got it right then you want to loop while playAgain == 'y'? So that might be a good thing to put in the outer while? You might need to do some data processing on the input from the user to make sure it returns 'y' though.... And you need to assign a value to it ('y'?) before the loop test. BTW In Python we don't need parentheses around the test, its not C. Also if you set guess = 0 in the first assignment you don't need to repeat the user input line. You only need it in the inner loop. -- 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 aliyan.navaid at gmail.com Sun Oct 4 03:47:46 2020 From: aliyan.navaid at gmail.com (Aliyan Navaid) Date: Sun, 4 Oct 2020 12:47:46 +0500 Subject: [Tutor] Learning Python By Doing Message-ID: Is there any free course or book that doesn?t spends a lot of time on the basics itself but teach us via doing projects ? ? From alan.gauld at yahoo.co.uk Sun Oct 4 07:02:12 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 4 Oct 2020 12:02:12 +0100 Subject: [Tutor] float.is_integer() In-Reply-To: References: Message-ID: On 03/10/2020 13:53, Richard Damon wrote: > On 10/3/20 5:51 AM, Alan Gauld via Tutor wrote: >> On 03/10/2020 01:08, Zachary Ware wrote: >>> Have a look at the repr of 23444444444444444.7777; a 64 bit floating point >>> number cannot represent that number exactly. >> So basically the float is just too big to include the fractional part. >> Hmm, I wonder where the break off point is? Time to do some math... >> Or play with the interpreter! :-) >> > Python floating point numbers have 52 significant bits + implied leading > 1 + sign bit. Numbers less than 2^52 have fractional bits, 2^52 and > bigger can not. And just to prove it: >>> 2**52 4503599627370496 >>> 4503599627370496.7.is_integer() True >>> 4503599627370495.7.is_integer() False >>> -- 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 Sun Oct 4 07:07:37 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 4 Oct 2020 12:07:37 +0100 Subject: [Tutor] Learning Python By Doing In-Reply-To: References: Message-ID: On 04/10/2020 08:47, Aliyan Navaid wrote: > Is there any free course or book that doesn?t spends a lot of time on the > basics itself but teach us via doing projects ? It's very difficult to teach good programming(*) practice via projects but the place you are most likely to find that approach is in the maker community, especially around the Raspberry Pi SBC. Try following some of the Pi tutorials, although many of them will require a Pi to get the most out of them... (*)But its very easy to teach bad programming practice that way! A "good enough" approach is very tempting... The problem is that "good enough" works for typical small projects but comes badly unstuck when the projects (and teams) get bigger. -- 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 john at johnweller.co.uk Sun Oct 4 06:00:27 2020 From: john at johnweller.co.uk (John Weller) Date: Sun, 4 Oct 2020 11:00:27 +0100 Subject: [Tutor] Learning Python By Doing In-Reply-To: References: Message-ID: <000e01d69a35$30b48750$921d95f0$@johnweller.co.uk> > > Is there any free course or book that doesn?t spends a lot of time on the > basics itself but teach us via doing projects ? > You might like to look at FutureLearn.com. They have a series of free courses on Python; the courses are aimed at teachers learning Python in order to teach it but are none the worse for that. I have taught myself Python over lockdown and found them very useful. They are supposedly a couple of hours per week for several weeks but there is no reason why you cannot just keep going - I did 3 of them in a week. I am now dabbling with C++ and found the Easy Steps book very good, they have one on Python which will probably be equally good. Other free resources I have found helpful are Socratica and Corey Schafer on YouTube. John Weller From george at fischhof.hu Sun Oct 4 07:50:06 2020 From: george at fischhof.hu (George Fischhof) Date: Sun, 4 Oct 2020 13:50:06 +0200 Subject: [Tutor] Learning Python By Doing In-Reply-To: <000e01d69a35$30b48750$921d95f0$@johnweller.co.uk> References: <000e01d69a35$30b48750$921d95f0$@johnweller.co.uk> Message-ID: John Weller ezt ?rta (id?pont: 2020. okt. 4., V, 13:11): > > > > Is there any free course or book that doesn?t spends a lot of time on > the > > basics itself but teach us via doing projects ? > > > You might like to look at FutureLearn.com. They have a series of free > courses on Python; the courses are aimed at teachers learning Python in > order to teach it but are none the worse for that. I have taught myself > Python over lockdown and found them very useful. They are supposedly a > couple of hours per week for several weeks but there is no reason why you > cannot just keep going - I did 3 of them in a week. > > I am now dabbling with C++ and found the Easy Steps book very good, they > have one on Python which will probably be equally good. Other free > resources I have found helpful are Socratica and Corey Schafer on YouTube. > > > John Weller > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Hi, Socratica is really very good, and here is another youtube stuff, where the lecturer starts with "basics are boring" and some small project is solved: https://www.youtube.com/watch?v=eXBD2bB9-RA&list=PLQVvvaa0QuDeAams7fkdcwOGBpGdHpXln BR, George From sccdzt at foxmail.com Mon Oct 5 02:28:40 2020 From: sccdzt at foxmail.com (=?gb18030?B?U2FpbG9ybW9vbg==?=) Date: Mon, 5 Oct 2020 09:28:40 +0300 Subject: [Tutor] help for the code debug Message-ID: Dear sir : When I run The code as below it showed error that SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers,The excel data is like this as below screenshot .Is there anyone could help ,thanks a lot.  #???? #!/usr/bin/env python # -*- coding: utf-8 -*- #???? import os import shutil import xlrd #?????? path_file=r'G:\????\Before 2018.12.22' #???????????????ls??????file ls = os.listdir(path_file) print(len(ls)) data = xlrd.open_workbook(r'C:\Users\Administrator\Desktop\searching.xls') # ??xls?? table = data.sheets()[0] # ?????? nrows = table.nrows # ?????? #datalist?????? datalist_NAME=[] #?table?????????????data_list? str(datalist_NAME.extend(table.col_values(0))) print(eval(datalist_NAME[1]) )#eval????????[1]???????? for num in range(1,nrows): #num?1?nrows?? for i in ls: #??????find??????? if i.find(eval(datalist_NAME[num])+"_Boundary_Line")!=-1: shutil.copyfile(path_file+'/'+i,"F:/budyko_ds/"+i) #shutil.move(path_file+'/'+i,"F:/budyko_ds/"+i) #????????? print( datalist_NAME[num]) print( num) print ("ALL DONE")   From alan.gauld at yahoo.co.uk Mon Oct 5 04:04:35 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 5 Oct 2020 09:04:35 +0100 Subject: [Tutor] help for the code debug In-Reply-To: References: Message-ID: On 05/10/2020 07:28, Sailormoon wrote: > Dear sir : > When I run The code as below it showed error that SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers Please always post the entire error message, never try to summarize it. It contains lots of useful details. However, in this case I suspect the problem is your use of eval() It is a dangerous tool to use since it executes your data as if it were code and can lead to serious security problems. It is rarely necessary, and a conversion function is probably more appropriate here. > path_file=r'G:\????\Before 2018.12.22' > > ls = os.listdir(path_file) > print(len(ls)) > > data = xlrd.open_workbook(r'C:\Users\Administrator\Desktop\searching.xls') # ??xls?? > table = data.sheets()[0] # ?????? > nrows = table.nrows # ?????? > datalist_NAME=[] > str(datalist_NAME.extend(table.col_values(0))) In the above line str() does nothing since you don't store the string value. Also the return value from extend() is None so you are just converting None to "None". But the above would be more directly written as: datalist_NAME = list(table.col_values(0)) > print(eval(datalist_NAME[1]) ) If the data contains invalid code Python will give a SyntaxError, which may be what you are seeing. But we can't tell because we can't see the data. That's where the full error message would help. > for num in range(1,nrows): #num?1?nrows?? > for i in ls: > if i.find(eval(datalist_NAME[num])+"_Boundary_Line")!=-1: Again this use of eval is potentially dangerous. I suspect a simple str() call would suffice? But without seeing what kind of data you have we can't be sure. Similarly the find() call could be clarified by using 'in' instead: for file_name in ls: if str(datalist_NAME(num)+"Boundary_Line" not in file_name: > shutil.copyfile(path_file+'/'+i,"F:/budyko_ds/"+i) > #shutil.move(path_file+'/'+i,"F:/budyko_ds/"+i) #????????? > print( datalist_NAME[num]) Notice you are printing the raw data here but you have eval()'d it earlier. > print( num) > print ("ALL DONE") -- 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 Mon Oct 5 05:09:20 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 5 Oct 2020 10:09:20 +0100 Subject: [Tutor] =?utf-8?b?5Zue5aSN77yaICBoZWxwIGZvciB0aGUgY29kZSBkZWJ1?= =?utf-8?q?g?= In-Reply-To: References: Message-ID: <9efb3500-b5e2-6aa4-a9c8-cea5f631f5ad@yahoo.co.uk> On 05/10/2020 09:23, Sailormoon wrote: > Dear? Mr Alan : > I changed The data format of The excel ,as attached , As I suspected your problem is that you are using eval() You pass eval() a value from your spreadsheet which looks like 'HFY3-3720-STR-RFI-0032' And python sees that as a line of code and tries to subtract 0032 from something called RFI. But 0032 is not a valid number literal in python, so you get an error. Until you fix the data formatting problem the rest of your code has no chance of working as you expect. If it does it will be a lucky accident! Incidentally the tutor list does not accept binary attachments like screenshots or excel files,? I only see it because you CC'd me directly. But if you had included the full error message we would have seen something like: >>> eval('HFY3-3720-STR-RFI-0032') Traceback (most recent call last): ? File "", line 1, in ??? eval('HFY3-3720-STR-RFI-0032') ? File "", line 1 ??? HFY3-3720-STR-RFI-0032 ???????????????????????? ^ SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers Which would have shown us exactly what the data error was. That's why it is important to include the complete error message. -- 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 sccdzt at foxmail.com Mon Oct 5 04:23:55 2020 From: sccdzt at foxmail.com (=?gb18030?B?U2FpbG9ybW9vbg==?=) Date: Mon, 5 Oct 2020 11:23:55 +0300 Subject: [Tutor] =?gb18030?q?=BB=D8=B8=B4=A3=BA__help_for_the_code_debug?= In-Reply-To: References: Message-ID: Dear  Mr Alan : I changed The data format of The excel ,as attached ,and I changed The  source path ,The directory as below screenshot ,The named file is in one of The below folder ,it can run ,but didn't copy The relative file to The nominated F disk ,Could You help  tell why is that . #???? #!/usr/bin/env python # -*- coding: utf-8 -*- #???? import os import shutil import xlrd #?????? path_file=r'G:\????\WATER INJECTION 3720' #???????????????ls??????file ls = os.listdir(path_file) print(len(ls)) data = xlrd.open_workbook(r'C:\Users\Administrator\Desktop\searching.xls') # ??xls?? table = data.sheets()[0] # ?????? nrows = table.nrows # ?????? #datalist?????? datalist_NAME=[] #?table?????????????data_list? datalist_NAME.extend(table.col_values(0)) print(eval(datalist_NAME[1]) )#eval????????[1]???????? for num in range(1,nrows): #num?1?nrows?? for i in ls: #??????find??????? if i.find(eval(datalist_NAME[num])+"_Boundary_Line")!=-1: shutil.copyfile(path_file+'\\'+i,"F:\\budyko_ds"+i) #shutil.move(path_file+'/'+i,"F:/budyko_ds/"+i) #????????? print( datalist_NAME[num]) print( num) print ("ALL DONE")   ------------------ ???? ------------------ ???: "Alan Gauld" number1 = input('Number1: ') number2 = input('Number2: ') number3 = input('Number3: ') ? if number3 > number2 and number3 > number1: ??? print('Number 3') ? elif number2 > number1 and number2 > number3: ??? print("Number 2") ? else: ??? print('Number 1') ? ? When given values Number1 = 423, Number 2 = 23 and Number 3 = 43 the program outputs ?Number3? even though the correct answer should?ve been Number 1. Can somebody please explain why is this program not functioning properly ? From fabi.lunell at gmail.com Tue Oct 6 12:10:31 2020 From: fabi.lunell at gmail.com (Fabian Lunell) Date: Tue, 6 Oct 2020 18:10:31 +0200 Subject: [Tutor] python calculate number in a text file Message-ID: You can here download two files each containing 10000 integer values. The main difference between the two files is how the integers are formatted in the file. Write a program read_numbers.py that reads the two files (one after each other) and for each file computes and presents the average (mean) value and the standard deviation. We expect two separate functions mean(lst) and std(lst) that computes the mean and standard deviation for a given list of integers lst. Here you can find more information about the standard deviation . From manpritsinghece at gmail.com Tue Oct 6 13:32:45 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Tue, 6 Oct 2020 23:02:45 +0530 Subject: [Tutor] Discussion about Chaining in comparison operators Message-ID: Dear sir , Let's start with a problem: I have 3 variables a,b, c and all three are assigned some integer values . a = 5 b = 7 c = 6 now if i have to check that if all three are equal or not, what should i prefer from the below given choices : 1) a == b and a == c or it chained version b == a == c 2) a == b and b == c or its chained version a == b == c Since a == b == c seems more readable than b == a == c, I will prefer this . Regards Manprit Singh From adameyring at gmail.com Tue Oct 6 19:31:04 2020 From: adameyring at gmail.com (Adam Eyring) Date: Tue, 6 Oct 2020 19:31:04 -0400 Subject: [Tutor] Find the Greatest number out of 3 (Python 3.7.0) In-Reply-To: <7796C42D-8AA9-4600-807E-814986603027@hxcore.ol> References: <7796C42D-8AA9-4600-807E-814986603027@hxcore.ol> Message-ID: What's happening is that the print statements output strings. Change them to variables like number1, number2, and number3 (no quotation marks) and it should work. On Tue, Oct 6, 2020, 7:24 PM Aliyan Navaid wrote: > number1 = input('Number1: ') > > number2 = input('Number2: ') > > number3 = input('Number3: ') > > > > if number3 > number2 and number3 > number1: > > print('Number 3') > > > > elif number2 > number1 and number2 > number3: > > print("Number 2") > > > > else: > > print('Number 1') > > > > > > When given values Number1 = 423, Number 2 = 23 and Number 3 = 43 the > program outputs ?Number3? even though the correct answer should?ve been > Number 1. Can somebody please explain why is this program not > functioning > properly ? > _______________________________________________ > 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 Tue Oct 6 19:41:46 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 00:41:46 +0100 Subject: [Tutor] Find the Greatest number out of 3 (Python 3.7.0) In-Reply-To: References: <7796C42D-8AA9-4600-807E-814986603027@hxcore.ol> Message-ID: On 07/10/2020 00:31, Adam Eyring wrote: > What's happening is that the print statements output strings. That should be the *input* functions, not print... >> number1 = input('Number1: ') >> number2 = input('Number2: ') >> number3 = input('Number3: ') So these are all strings: "423", "23", "43" And the greater/less than comparisons on strings are different to numbers! >> if number3 > number2 and number3 > number1: >> print('Number 3') You could rewrite the above to the arguable more readable: if number 2 < number3 > number1: print.... -- 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 Oct 6 19:50:18 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 00:50:18 +0100 Subject: [Tutor] python calculate number in a text file In-Reply-To: References: Message-ID: On 06/10/2020 17:10, Fabian Lunell wrote: > You can here download > two > files each containing 10000 integer values. The main difference between the > two files is how the integers are formatted in the file. > > Write a program read_numbers.py that reads the two files (one after each > other) and for each file computes and presents the average (mean) value and > the standard deviation. We expect two separate functions mean(lst) and > std(lst) that computes the mean and standard deviation for a given list of > integers lst. Here you can find more information about the standard > deviation Thats an interesting exercise which most of us here already know how to do it and don't have much motivation to do it. I assume its a homework and you would like some help? But you don't ask any questions... or show us any code. We won't do your homework for you but we will offer assistance if you show us your work, and we can suggest ways to progress. For example, there is a statistics module in the python standard library. In the meantime do you know how to read data from a file? Do you know anything about the different data formats? How to read them into a consistent data format in your program? I'd expect your code to be structured like this: def mean(lst):.... def std(lst):.... for file in numlist = read data from file print(file, "mean: ", mean(numlist)) print(file, "SD: ", std(numlist) If you have specific questions get back to us, include any error messages in full please. -- 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 Oct 6 19:57:28 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 00:57:28 +0100 Subject: [Tutor] Discussion about Chaining in comparison operators In-Reply-To: References: Message-ID: On 06/10/2020 18:32, Manprit Singh wrote: > now if i have to check that if all three are equal or not, what should i > prefer from the below given choices : > > 1) a == b and a == c > or it chained version > b == a == c > > 2) a == b and b == c > or its chained version > a == b == c > > Since a == b == c seems more readable than b == a == c, I will prefer > this . Our objective should *always* be to write the most readable(*) code we can. So yes, a==b==c wins. (*) The reason for this is that in any serious code, maintenance accounts for 80% of the total project cost. Therefore anything which improves the maintainability of the code is a big win - and readability makes code much more maintainable. For example, if a bit of code increases coding time by 10% but reduces maintenance costs by 10% the net effect is +2% in development but -8% in maintenance = an overall 6% reduction in cost! Software engineering, like any other kind of engineering, is all about building solutions at lowest cost. The rare exception to this rule is where performance is critical and maintainability may need to be compromised, but that hardly ever happens in the real world because there are usually better solutions to fixing performance. -- 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 joel.goldstick at gmail.com Tue Oct 6 20:09:52 2020 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 6 Oct 2020 20:09:52 -0400 Subject: [Tutor] Discussion about Chaining in comparison operators In-Reply-To: References: Message-ID: On Tue, Oct 6, 2020 at 7:58 PM Alan Gauld via Tutor wrote: > > On 06/10/2020 18:32, Manprit Singh wrote: > > > now if i have to check that if all three are equal or not, what should i > > prefer from the below given choices : > > > > 1) a == b and a == c > > or it chained version > > b == a == c > > > > 2) a == b and b == c > > or its chained version > > a == b == c > > > > Since a == b == c seems more readable than b == a == c, I will prefer > > this . > > Our objective should *always* be to write the most readable(*) > code we can. > > So yes, a==b==c wins. > > (*) The reason for this is that in any serious code, maintenance > accounts for 80% of the total project cost. Therefore anything > which improves the maintainability of the code is a big win > - and readability makes code much more maintainable. > > For example, if a bit of code increases coding time by 10% but > reduces maintenance costs by 10% the net effect is +2% in > development but -8% in maintenance = an overall 6% reduction > in cost! Software engineering, like any other kind of engineering, > is all about building solutions at lowest cost. > The rare exception to this rule is where performance is critical > and maintainability may need to be compromised, but that hardly ever > happens in the real world because there are usually better solutions > to fixing performance. > > -- > 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 another way is: >>> a=3 >>> b=4 >>> c=3 >>> len(set((a,b,c))) 2 >>> b = 3 >>> len(set((a,b,c))) 1 >>> if they are all the same the set will be of length 1. -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From chris_roysmith at internode.on.net Tue Oct 6 20:22:42 2020 From: chris_roysmith at internode.on.net (Chris Roy-Smith) Date: Wed, 7 Oct 2020 11:22:42 +1100 Subject: [Tutor] Find the Greatest number out of 3 (Python 3.7.0) In-Reply-To: References: <7796C42D-8AA9-4600-807E-814986603027@hxcore.ol> Message-ID: <2188de5f-70d4-ff14-be04-ac58ae7d8a89@internode.on.net> On 7/10/20 10:41 am, Alan Gauld via Tutor wrote: > On 07/10/2020 00:31, Adam Eyring wrote: >> What's happening is that the print statements output strings. > > That should be the *input* functions, not print... > >>> number1 = input('Number1: ') >>> number2 = input('Number2: ') >>> number3 = input('Number3: ') > > So these are all strings: "423", "23", "43" > forgive me Alan, should the inputs be converted to numbers e.g. number1=int(input('Number1: ') number2=int(input('Number2: ') number3=int(input('Number3: ') > And the greater/less than comparisons on strings > are different to numbers! > > >>> if number3 > number2 and number3 > number1: >>> print('Number 3') > > You could rewrite the above to the arguable more readable: > > if number 2 < number3 > number1: > print.... > > regards, ChrisRoy-Smith From alan.gauld at yahoo.co.uk Tue Oct 6 20:41:37 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 01:41:37 +0100 Subject: [Tutor] Find the Greatest number out of 3 (Python 3.7.0) In-Reply-To: <2188de5f-70d4-ff14-be04-ac58ae7d8a89@internode.on.net> References: <7796C42D-8AA9-4600-807E-814986603027@hxcore.ol> <2188de5f-70d4-ff14-be04-ac58ae7d8a89@internode.on.net> Message-ID: On 07/10/2020 01:22, Chris Roy-Smith wrote: >> So these are all strings: "423", "23", "43" >> > forgive me Alan, > should the inputs be converted to numbers e.g. > > number1=int(input('Number1: ') > number2=int(input('Number2: ') > number3=int(input('Number3: ') Assuming you want to compare them as numbers then yes. -- 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 Oct 6 20:45:28 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 01:45:28 +0100 Subject: [Tutor] Discussion about Chaining in comparison operators In-Reply-To: References: Message-ID: On 07/10/2020 01:09, Joel Goldstick wrote: >> Our objective should *always* be to write the most readable(*) >> code we can. >> >> So yes, a==b==c wins. > another way is: > >>>> a=3 >>>> b=4 >>>> c=3 >>>> len(set((a,b,c))) > if they are all the same the set will be of length 1. That's true but it is neither readable nor performant. It requires an act of thought to recognize that 3 items into a set of length 1 means they are all the same. That's much less readable than a direct equality test. And much slower since you have to construct a set. a==b==c still wins -- 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 joel.goldstick at gmail.com Tue Oct 6 21:00:35 2020 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 6 Oct 2020 21:00:35 -0400 Subject: [Tutor] Discussion about Chaining in comparison operators In-Reply-To: References: Message-ID: On Tue, Oct 6, 2020 at 8:50 PM Alan Gauld via Tutor wrote: > > On 07/10/2020 01:09, Joel Goldstick wrote: > > >> Our objective should *always* be to write the most readable(*) > >> code we can. > >> > >> So yes, a==b==c wins. > > > another way is: > > > >>>> a=3 > >>>> b=4 > >>>> c=3 > >>>> len(set((a,b,c))) > > > if they are all the same the set will be of length 1. > > > That's true but it is neither readable nor performant. > It requires an act of thought to recognize that 3 items > into a set of length 1 means they are all the same. > That's much less readable than a direct equality test. > And much slower since you have to construct a set. > > a==b==c > > still wins > I think you win the argument, but I've noticed sets to be underappreciated at times. > -- > 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 -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays From donovanfitch3 at gmail.com Wed Oct 7 03:01:59 2020 From: donovanfitch3 at gmail.com (Donovan Fitch) Date: Wed, 7 Oct 2020 00:01:59 -0700 Subject: [Tutor] Help Message-ID: Hi, So the problem that I am facing is with finding the average of a list of inputs that the user has provided. Here is my code: max = 0 min = 100 totalNum = int(input("Please enter the total number of students: ")) student = 1 print("Grades should be between 0 and 100.") while student <= totalNum: grade = int(input("Student {} grade: ".format(student))) student += 1 for i in range(1, totalNum, 1): if grade > max: max = grade if grade < min: min = grade print("Maximum grade: ", max) print("Minimum grade: ", min) It works perfectly with finding the max and min, however, I need to know how to find the average of the grades. From dsougoumarane1969 at gmail.com Wed Oct 7 02:29:03 2020 From: dsougoumarane1969 at gmail.com (sougoumarane dashnamoorthy) Date: Wed, 7 Oct 2020 11:59:03 +0530 Subject: [Tutor] How to execute python file( python program) by variables from another python program Message-ID: <0ED63D4B-6C2B-4B0F-86A5-F0916CA31ECB@hxcore.ol> ? ? How to execute python file( python program) by variables from another python program I had tried ? path=__import__('try_main_program_RBModel', globals(), locals(), ['fname'], 0) ? ? From manpritsinghece at gmail.com Tue Oct 6 23:03:46 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 7 Oct 2020 08:33:46 +0530 Subject: [Tutor] Finding biggest of three numbers Message-ID: Dear sir , consider the problem of finding the biggest of three numbers . The most clean and clear solution to this problem is using max( ) function. But my question is about the basic program for this problem that is taught in schools, to make the students learn about if statement, the program is given below : a = int(input("Input first number")) b = int(input("Input second number")) c = int(input("Input second number")) if a > b and a > c: x = a elif b > c: x = b else: x = c print("The greatest number is", x) Now , i am going to make changes in the above written program : a = int(input("Input first number")) b = int(input("Input second number")) c = int(input("Input second number")) if b < a > c: x = a elif b > c: x = b else: x = c print("The greatest number is", x) Here in the second version, I have used chaining in the condition written with if . So what are your views about this second version, which one must be preferred ? - second or first version of the solution to the problem . Just need to know in which circumstances I should prefer chaining, and in which circumstances I should avoid it . Regards Manprit Singh From alan.gauld at yahoo.co.uk Wed Oct 7 04:16:17 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 09:16:17 +0100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: On 07/10/2020 08:01, Donovan Fitch wrote: > totalNum = int(input("Please enter the total number of students: ")) > student = 1 > print("Grades should be between 0 and 100.") > while student <= totalNum: > grade = int(input("Student {} grade: ".format(student))) > student += 1 > > for i in range(1, totalNum, 1): > if grade > max: > max = grade > if grade < min: > min = grade > > print("Maximum grade: ", max) > print("Minimum grade: ", min) > > It works perfectly with finding the max and min, however, I need to know > how to find the average of the grades. So how would you work out any average? Find the total and divide by the number of items. So you need to either a) store all the grades in a list and sum() them at the end. Then divide by the len() of the list. or b) keep a running total and count and do the math at the end. BTW Your for loop is completely unnecessary. It just performs the exact same operation many times. grade never changes so max/min get set to the same value each time. -- 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 Oct 7 04:24:33 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 09:24:33 +0100 Subject: [Tutor] How to execute python file( python program) by variables from another python program In-Reply-To: <0ED63D4B-6C2B-4B0F-86A5-F0916CA31ECB@hxcore.ol> References: <0ED63D4B-6C2B-4B0F-86A5-F0916CA31ECB@hxcore.ol> Message-ID: On 07/10/2020 07:29, sougoumarane dashnamoorthy wrote: > How to execute python file( python program) by variables from another > python program Don't, its nearly always the wrong thing to do! The best way to execute code in another file is to put the code in a function then import the file and call the function. If you don't have control of the file to put the code in a function then execute it using subprocess, just as you would a shell script or other executable.. > I had tried > > path=__import__('try_main_program_RBModel', globals(), locals(), > ['fname'], 0) There needs to be a very good reason(*) for trying to do this. It's very easy to get wrong and also easy to break in the future. And since you know the file you can just use import or one of its variants - but that brings its own issues(namespace pollution etc). (*)One such scenario would be a server process that generates python code files on the fly and you need to catch these files and import them into your code - but then you need to know in advance what that code is going to contain - what variables and functions it will have etc. There is nearly always a better solution. -- 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 Oct 7 04:31:39 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 09:31:39 +0100 Subject: [Tutor] Finding biggest of three numbers In-Reply-To: References: Message-ID: On 07/10/2020 04:03, Manprit Singh wrote: > clean and clear solution to this problem is using max( ) function. Correct so that is the correct solution. But for the sake of debate, let's assume max didn't exist.... > if a > b and a > c: > x = a > elif b > c: > x = b > else: > x = c > if b < a > c: > x = a > elif b > c: > x = b > else: > x = c > Here in the second version, I have used chaining in the condition written > with if . The two versions are identical except the initial if. > So what are your views about this second version, which one must > be preferred ? - second or first version of the solution to the problem . Which is the most readable. The second version explicitly states the requirement and eliminates unneeded logic operations. It's both clearer and more performant. It is therefore preferable. > Just need to know in which circumstances I should prefer chaining, and in > which circumstances I should avoid it . Use it when it is more readable. There are no absolutes and sometimes it is a subjective choice. But, as I previously stated, our goal is always to write code that is clean, readable and reliable, and therefore maintainable. -- 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.Flynn at capita.com Wed Oct 7 04:16:25 2020 From: Steve.Flynn at capita.com (Flynn, Stephen (Life & Pensions)) Date: Wed, 7 Oct 2020 08:16:25 +0000 Subject: [Tutor] Finding biggest of three numbers In-Reply-To: References: Message-ID: I probably doesn't make any difference. If you had the comparisons in a hot loop and you had performance constraints then you could look as the IL for the code and compare and contrast that instructions used by the interpreter but my guess is that it'll probably result in the same instruction sequence. Use whichever version you prefer - they are functionally equivalent. S. -----Original Message----- From: Tutor On Behalf Of Manprit Singh Sent: 07 October 2020 04:04 To: tutor at python.org Subject: [Tutor] Finding biggest of three numbers **EXTERNAL** Dear sir , consider the problem of finding the biggest of three numbers . The most clean and clear solution to this problem is using max( ) function. But my question is about the basic program for this problem that is taught in schools, to make the students learn about if statement, the program is given below : a = int(input("Input first number")) b = int(input("Input second number")) c = int(input("Input second number")) if a > b and a > c: x = a elif b > c: x = b else: x = c print("The greatest number is", x) Now , i am going to make changes in the above written program : a = int(input("Input first number")) b = int(input("Input second number")) c = int(input("Input second number")) if b < a > c: x = a elif b > c: x = b else: x = c print("The greatest number is", x) Here in the second version, I have used chaining in the condition written with if . So what are your views about this second version, which one must be preferred ? - second or first version of the solution to the problem . Just need to know in which circumstances I should prefer chaining, and in which circumstances I should avoid it . Regards Manprit Singh _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor This message has been scanned by Capita systems, but if you believe it to be spam, please send it to spam at forcepoint.com. Messages sent to spam at forcepoint.com are queued for email analysis by Forcepoint Threat Lab. This email originates from outside of Capita. Keep this in mind before responding, opening attachments or clicking any links. Unless you recognise the sender and know the content is safe. If in any doubt, the grammar and spelling are poor, or the name doesn't match the email address then please contact the sender via an alternate known method. This email is security checked and subject to the disclaimer on web-page: https://www.capita.com/email-disclaimer.aspx From nulla.epistola at web.de Wed Oct 7 10:26:23 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Wed, 7 Oct 2020 16:26:23 +0200 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <1d3ac6b7-9802-d056-57d8-d31d4fd33130@web.de> Am 07.10.2020 um 10:16 schrieb Alan Gauld via Tutor: > On 07/10/2020 08:01, Donovan Fitch wrote: >> totalNum = int(input("Please enter the total number of students: ")) >> student = 1 >> print("Grades should be between 0 and 100.") >> while student <= totalNum: >> grade = int(input("Student {} grade: ".format(student))) >> student += 1 >> >> for i in range(1, totalNum, 1): >> if grade > max: >> max = grade >> if grade < min: >> min = grade >> >> print("Maximum grade: ", max) >> print("Minimum grade: ", min) >> > > BTW Your for loop is completely unnecessary. It just > performs the exact same operation many times. > grade never changes so max/min get set to the > same value each time. > While the while loop is the classical case for for. Sibylle From nulla.epistola at web.de Wed Oct 7 10:26:23 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Wed, 7 Oct 2020 16:26:23 +0200 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <1d3ac6b7-9802-d056-57d8-d31d4fd33130@web.de> Am 07.10.2020 um 10:16 schrieb Alan Gauld via Tutor: > On 07/10/2020 08:01, Donovan Fitch wrote: >> totalNum = int(input("Please enter the total number of students: ")) >> student = 1 >> print("Grades should be between 0 and 100.") >> while student <= totalNum: >> grade = int(input("Student {} grade: ".format(student))) >> student += 1 >> >> for i in range(1, totalNum, 1): >> if grade > max: >> max = grade >> if grade < min: >> min = grade >> >> print("Maximum grade: ", max) >> print("Minimum grade: ", min) >> > > BTW Your for loop is completely unnecessary. It just > performs the exact same operation many times. > grade never changes so max/min get set to the > same value each time. > While the while loop is the classical case for for. Sibylle From nathan-tech at hotmail.com Wed Oct 7 12:41:21 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Wed, 7 Oct 2020 17:41:21 +0100 Subject: [Tutor] creating a server Message-ID: hi folks, I'm not sure if this is the write mailing list to ask this question, as it's not really exactly a newbie question. Well, I guess it is but... Anyway. I'm going to build server in python and wondered if someone would be willing to spend just a second to answer these questions so I can understand: I see my server having somewhat of this structure: connections=[] shutdown=False while shutdown != True: check_for_connections() # this would handle any connections that were received on socket and if some were found, append them to the connections variable for x in connections: data=x.recv(1024) if(data): # act upon this data # server is shutting down, so send a goodbye message to the connections and then close. My questions are simple really: 1. Is this a basic good starting point? 2. Is there some sort of way of saying: if(sock.still_connected())? 3. Is recv(1024) the right way to go here, or is there a better way of ensuring all the relevant data gets through/ 4. I'd like to have it event based, what I mean is it would be pretty awesome if for instance the client sent an object like this one: class evt: def __init__(self, type): self.type=type self.message=None Then something like: e=evt("new_message") e.message="Hi! I'm sending you a very cool message!" sock.send(e) I've experimented a little bit with something like: data=sock.recv(1024) if(data and data[:-3]=="|||"): # all data received data=data.strip("|||") data=data.split("|") type=data[0] message=data[1] But this is obviously easily broken because of just throwing a | in there to break it all. Finally, I am going to be doing some research on this so please feel free to skip this final, but what is the advantage of twist over the standard socket library? Thanks in advance and, if this is truly the wrong place, I can only ask for direction. nathan From alan.gauld at yahoo.co.uk Wed Oct 7 14:01:52 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 19:01:52 +0100 Subject: [Tutor] creating a server In-Reply-To: References: Message-ID: On 07/10/2020 17:41, nathan tech wrote: > I see my server having somewhat of this structure: Have you looked at the socketserver module? It will do a lot of the basics for you. -- 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 nathan-tech at hotmail.com Wed Oct 7 14:13:08 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Wed, 7 Oct 2020 19:13:08 +0100 Subject: [Tutor] creating a server In-Reply-To: References: Message-ID: Hi Alan, I certainly have and was going to base my code around it but was unsure if sockets could handle the passing of objects? Will check it out again. Nathan On 07/10/2020 19:01, Alan Gauld via Tutor wrote: > On 07/10/2020 17:41, nathan tech wrote: > >> I see my server having somewhat of this structure: > Have you looked at the socketserver module? > It will do a lot of the basics for you. > > From alan.gauld at yahoo.co.uk Wed Oct 7 14:29:39 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 19:29:39 +0100 Subject: [Tutor] creating a server In-Reply-To: References: Message-ID: On 07/10/2020 19:13, nathan tech wrote: > I certainly have and was going to base my code around it but was unsure > if sockets could handle the passing of objects? sockets only care about bytes, they know nothing about data types. That's up to you! You will need to choose a format to encode your data in the message - JSON or YAML or XML or ASN.1 etc. Then use a parser to pack/unpack the high level into and out of the data stream. But your own suggested server was still using sockets and reading bytes. You had a recv(1024) call. That reads 1024 bytes. What would happen if your "object" was 1500 bytes long? You'd only have part of it to process. -- 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 PyTutor at DancesWithMice.info Wed Oct 7 15:09:32 2020 From: PyTutor at DancesWithMice.info (dn) Date: Thu, 8 Oct 2020 08:09:32 +1300 Subject: [Tutor] creating a server In-Reply-To: References: Message-ID: On 08/10/2020 07:29, Alan Gauld via Tutor wrote: > On 07/10/2020 19:13, nathan tech wrote: >> I certainly have and was going to base my code around it but was unsure >> if sockets could handle the passing of objects? > > sockets only care about bytes, they know nothing about data types. > That's up to you! You will need to choose a format to encode > your data in the message - JSON or YAML or XML or ASN.1 etc. > Then use a parser to pack/unpack the high level into and out > of the data stream. > > But your own suggested server was still using sockets and reading bytes. > > You had a recv(1024) call. That reads 1024 bytes. What would happen > if your "object" was 1500 bytes long? You'd only have part of it to process. One of the oldest and most popular (client-)servers on the Internet is Apache's httpd. It implements the httpd protocol (yes, well...). The client first sends a "header", and later a "body" payload. The header 'declares' the business of the body, including its length - per @Alan's comment. The early web and email servers used plain-text as their universal communication medium (and very handy for debugging). In some respects this can be inefficient, eg transmission volume, security. Many 'modern' approaches try for a more 'binary' approach. Recommendation: design the protocol(s), ie the 'conversation' between client and server, before worrying about the code (which will implement same). Your server, your rules! (but what are "the rules"?) The code specified (earlier) is a classic "Event Loop". These days, looking-up such key-words will likely land you in the world of computer-games, but the techniques as you (originally) noted, still apply. Adding to the study/reading @Alan recommended: - RFCs or similar, for Internet infrastructure servers. - YAML, JSON, etc, file formats and processing libraries. - more 'modern' protocols, eg MongoDB. - Python3's (default) use of Unicode characters, cf bytes, ASCII characters, etc. -- Regards =dn From gmakgopa at gmail.com Wed Oct 7 16:16:37 2020 From: gmakgopa at gmail.com (Gilbert Makgopa) Date: Wed, 7 Oct 2020 22:16:37 +0200 Subject: [Tutor] Help Message-ID: Kindly assist with the function below. The task is to write a function so that it returns the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder. def sum_divisors(n): sum = 0 div =0 # Return the sum of all divisors of n, not including n while (div > 0 and div!=n): sum = sum + div return sum print(sum_divisors(0)) # 0 print(sum_divisors(3)) # Should sum of 1 # 1 print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 # 55 print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 # 114 From gmakgopa at gmail.com Wed Oct 7 16:22:19 2020 From: gmakgopa at gmail.com (Gilbert Makgopa) Date: Wed, 7 Oct 2020 22:22:19 +0200 Subject: [Tutor] Help Message-ID: The function below prints "None" in between the output lines. Please assist. Here is the results: Name: Hemingway Ernest None Name: Madonna None Name: Voltaire None Function: def format_name(first_name, last_name): # code goes here if (first_name != "" and last_name != ""): string = print("Name: " + last_name , first_name) elif (first_name == "" and last_name != ""): string = print("Name: " + last_name) elif (first_name != "" and last_name == ""): string = print("Name: " + first_name) elif (first_name == "" and last_name == ""): string = " " return string print(format_name("Ernest", "Hemingway")) # Should return the string "Name: Hemingway, Ernest" print(format_name("", "Madonna")) # Should return the string "Name: Madonna" print(format_name("Voltaire", "")) # Should return the string "Name: Voltaire" print(format_name("", "")) # Should return an empty string From nathan-tech at hotmail.com Wed Oct 7 15:13:03 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Wed, 7 Oct 2020 20:13:03 +0100 Subject: [Tutor] creating a server In-Reply-To: References: Message-ID: Exactly! that's what part of my question was, really :) how does one go about verifying all data was received? recv(2000000) seems a bit ludicrous to me and besides, what you don't want to do is receive an object and then half of the next one, too! Thanks On 07/10/2020 19:29, Alan Gauld via Tutor wrote: > On 07/10/2020 19:13, nathan tech wrote: >> I certainly have and was going to base my code around it but was unsure >> if sockets could handle the passing of objects? > sockets only care about bytes, they know nothing about data types. > That's up to you! You will need to choose a format to encode > your data in the message - JSON or YAML or XML or ASN.1 etc. > Then use a parser to pack/unpack the high level into and out > of the data stream. > > But your own suggested server was still using sockets and reading bytes. > > You had a recv(1024) call. That reads 1024 bytes. What would happen > if your "object" was 1500 bytes long? You'd only have part of it to process. > From nathan-tech at hotmail.com Wed Oct 7 15:33:37 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Wed, 7 Oct 2020 20:33:37 +0100 Subject: [Tutor] creating a server In-Reply-To: References: Message-ID: Please ignore the last message. There's a delay due to moderator approval (is that because I am new/) and the question has been answered :) On 07/10/2020 20:09, dn via Tutor wrote: > On 08/10/2020 07:29, Alan Gauld via Tutor wrote: >> On 07/10/2020 19:13, nathan tech wrote: >>> I certainly have and was going to base my code around it but was unsure >>> if sockets could handle the passing of objects? >> >> sockets only care about bytes, they know nothing about data types. >> That's up to you! You will need to choose a format to encode >> your data in the message - JSON or YAML or XML or ASN.1 etc. >> Then use a parser to pack/unpack the high level into and out >> of the data stream. >> >> But your own suggested server was still using sockets and reading bytes. >> >> You had a recv(1024) call. That reads 1024 bytes. What would happen >> if your "object" was 1500 bytes long? You'd only have part of it to >> process. > > > One of the oldest and most popular (client-)servers on the Internet is > Apache's httpd. It implements the httpd protocol (yes, well...). The > client first sends a "header", and later a "body" payload. The header > 'declares' the business of the body, including its length - per > @Alan's comment. > > The early web and email servers used plain-text as their universal > communication medium (and very handy for debugging). In some respects > this can be inefficient, eg transmission volume, security. Many > 'modern' approaches try for a more 'binary' approach. > > Recommendation: design the protocol(s), ie the 'conversation' between > client and server, before worrying about the code (which will > implement same). Your server, your rules! (but what are "the rules"?) > > The code specified (earlier) is a classic "Event Loop". These days, > looking-up such key-words will likely land you in the world of > computer-games, but the techniques as you (originally) noted, still > apply. > > > Adding to the study/reading @Alan recommended: > - RFCs or similar, for Internet infrastructure servers. > - YAML, JSON, etc, file formats and processing libraries. > - more 'modern' protocols, eg MongoDB. > - Python3's (default) use of Unicode characters, cf bytes, ASCII > characters, etc. From alan.gauld at yahoo.co.uk Wed Oct 7 17:15:36 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 22:15:36 +0100 Subject: [Tutor] creating a server In-Reply-To: References: Message-ID: On 07/10/2020 20:33, nathan tech wrote: > There's a delay due to moderator approval (is that because I am new/) > and the question has been answered :) If you are new then you will be automatically put on full moderation until I get around to removing you. I've just done that so newer messages should go straight through. Alan g. From alan.gauld at yahoo.co.uk Wed Oct 7 17:20:07 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 22:20:07 +0100 Subject: [Tutor] creating a server In-Reply-To: References: Message-ID: On 07/10/2020 20:13, nathan tech wrote: > that's what part of my question was, really :) how does one go about > verifying all data was received? > > recv(2000000) > > seems a bit ludicrous to me It is, instead you use a loop to read the whole message: msg = '' while true: data = recv(blocksize) # or whatever msg += data if len(data) < blocksize: break # end of data > and besides, what you don't want to do is > receive an object and then half of the next one, too! Hopefully the sender sends them one at a time! Or at least your message protocol stipulates that they are sent one at a time(or in a stipulated amount, or that the number of objects is specified in the message. Whatever it takes for you to decode the received bytes. Servers stipulate their API. If clients don't abide by the API that's their problem not the servers! -- 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 cs at cskk.id.au Wed Oct 7 17:26:40 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Thu, 8 Oct 2020 08:26:40 +1100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <20201007212640.GA14993@cskk.homeip.net> On 07Oct2020 22:22, Gilbert Makgopa wrote: >The function below prints "None" in between the output lines. Please assist. That is because your format_name() function is returning None. I suspect you thing your final: print(format_name("Ernest", "Hemingway")) line is printing "Name: Hemmingway Ernest", but it is not. It is printing "None" because that is what format_name() is returning. Instead, the "Name: Hemmingway Ernest" output is coming from this code: if (first_name != "" and last_name != ""): string = print("Name: " + last_name , first_name) which itself calls print(), producing the output. For added fun, the return from print() is None, so string==None. And you return string, thus None, and then print that. Change the line to: string = "Name: " + last_name + " " + first_name and similarly elsewhere and see what happens. You will also find it illuminating to put a: print("string =", string) just before the "return string" at the bottom of your function. In fact, do that _before_ making the fix - it will make the situation more clear to you. Cheers, Cameron Simpson >Here is the results: > >Name: Hemingway Ernest >None >Name: Madonna >None >Name: Voltaire >None > >Function: >def format_name(first_name, last_name): > # code goes here > if (first_name != "" and last_name != ""): > string = print("Name: " + last_name , first_name) > elif (first_name == "" and last_name != ""): > string = print("Name: " + last_name) > > elif (first_name != "" and last_name == ""): > string = print("Name: " + first_name) > > elif (first_name == "" and last_name == ""): > string = " " > return string > > >print(format_name("Ernest", "Hemingway")) ># Should return the string "Name: Hemingway, Ernest" > >print(format_name("", "Madonna")) ># Should return the string "Name: Madonna" > >print(format_name("Voltaire", "")) ># Should return the string "Name: Voltaire" > >print(format_name("", "")) ># Should return an empty string From cs at cskk.id.au Wed Oct 7 17:29:23 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Thu, 8 Oct 2020 08:29:23 +1100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <20201007212923.GA34011@cskk.homeip.net> On 07Oct2020 22:16, Gilbert Makgopa wrote: >Kindly assist with the function below. >The task is to write a function so that it returns the sum of all the >divisors of a number, without including it. A divisor is a number that >divides into another without a remainder. > >def sum_divisors(n): > sum = 0 > div =0 > # Return the sum of all divisors of n, not including n > while (div > 0 and div!=n): > sum = sum + div > return sum Look at the indentation; Python relies on indentation to know what control structures enclose a statement. Are all the statements in the right place? Consider each individually, carefully. Cheers, Cameron Simpson >print(sum_divisors(0)) ># 0 >print(sum_divisors(3)) # Should sum of 1 ># 1 >print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 ># 55 >print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 ># 114 From alan.gauld at yahoo.co.uk Wed Oct 7 17:25:24 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 22:25:24 +0100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: On 07/10/2020 21:16, Gilbert Makgopa wrote: > def sum_divisors(n): > sum = 0 > div =0 > # Return the sum of all divisors of n, not including n > while (div > 0 and div!=n): > sum = sum + div > return sum > > print(sum_divisors(0)) > # 0 > print(sum_divisors(3)) # Should sum of 1 > # 1 > print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 > # 55 Where within your function do you check to see if div is actually a divisor? In fact your function is severely broken and will always return None (the default return value of a Python function). If you are getting other results you must be running different code to what you posted. Things wrong: 1) You start with div=0 then immediately check if div > 0 which it isn't. 2) You never modify div or n so the while loop always gives the same result. 3) You never check if div is actually a diviror of n before adding it to sum. -- 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 Oct 7 17:33:36 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 7 Oct 2020 22:33:36 +0100 Subject: [Tutor] string formatting (was Re: Help) In-Reply-To: References: Message-ID: Always start a new thrad with a new *descriptive* subject line for new topics. This has nothing to do with your previous message about divisors. On 07/10/2020 21:22, Gilbert Makgopa wrote: > The function below prints "None" in between the output lines. Please assist. > Here is the results: > > Name: Hemingway Ernest > None > Name: Madonna > None > > Function: > def format_name(first_name, last_name): > # code goes here > if (first_name != "" and last_name != ""): > string = print("Name: " + last_name , first_name) What value does print() return? Try it in the interpreter. >>> val = print('') >>> print("Print returned: ", val) > print(format_name("Ernest", "Hemingway")) > # Should return the string "Name: Hemingway, Ernest" Since format_name usually returns the result from print() you should now know the answer. In more general terms your function should *return* the formatted string not print it. You should not have any print() statements inside your function. Just generate a string and return that. Your exterior code can then print the result of the format function exactly as you attempted to do. The reason for this approach is because it makes your function usable in other contexts beside printing in the console. If you need to generate a web page for example, or send the data over a network. You can still use a formatted string, but the print output would just be lost. Keep code that displays data separate from the code that creates 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 arfatyasir354 at gmail.com Wed Oct 7 17:38:37 2020 From: arfatyasir354 at gmail.com (yasir arfat) Date: Thu, 8 Oct 2020 02:38:37 +0500 Subject: [Tutor] Help In-Reply-To: <20201007212923.GA34011@cskk.homeip.net> References: <20201007212923.GA34011@cskk.homeip.net> Message-ID: #function will return sum of divisors of # n(excluding n) def sum_div(n): sum=0 # loop will iterate from 1 to less than n for i in range (1,n): #checking whether n is dividable by i that # that means n%i will return 0 that is true for # i ( divisor) of n if n%i==0: # adding value to sum variable sum+=i # finally return return sum On Thu, Oct 8, 2020, 02:29 Cameron Simpson wrote: > On 07Oct2020 22:16, Gilbert Makgopa wrote: > >Kindly assist with the function below. > >The task is to write a function so that it returns the sum of all the > >divisors of a number, without including it. A divisor is a number that > >divides into another without a remainder. > > > >def sum_divisors(n): > > sum = 0 > > div =0 > > # Return the sum of all divisors of n, not including n > > while (div > 0 and div!=n): > > sum = sum + div > > return sum > > Look at the indentation; Python relies on indentation to know what > control structures enclose a statement. Are all the statements in the > right place? Consider each individually, carefully. > > Cheers, > Cameron Simpson > > >print(sum_divisors(0)) > ># 0 > >print(sum_divisors(3)) # Should sum of 1 > ># 1 > >print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 > ># 55 > >print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 > ># 114 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From d.delfino01 at hotmail.com Wed Oct 7 17:50:58 2020 From: d.delfino01 at hotmail.com (Dario Delfino) Date: Wed, 7 Oct 2020 21:50:58 +0000 Subject: [Tutor] python grade converter Message-ID: <40BEC7F4-F207-4BCE-9002-78395F633FEA@hotmail.com> To whom this may concern, I have been creating a grade converter as a school project and was wondering if you guys could help. i need to make it so that if they got a grade 1= it would result in an f. I just need help with this, thanks[cid:C616695D-9DEA-4ED5-97F0-F02DC135A52C at home] From nacnudskim at gmail.com Wed Oct 7 19:59:26 2020 From: nacnudskim at gmail.com (Mike Duncan) Date: Wed, 7 Oct 2020 19:59:26 -0400 Subject: [Tutor] Endless loop Message-ID: <59BE09C5-6734-459A-BE4F-3ADA59398FE4@getmailspring.com> Hi all., I have an endless loop issue, frankly I don't know why it is stuck in a endless loop. I don't understand why, I am trying to add a login to a web-sight using python here is the code: (have attached a zip file with the complete web-sight) @app.route ( "/auth", methods=['GET', 'POST'] ) def authenticate_user(): """ Authenticate a user """ # authenticated = False # Encrypt password password = request.form['pwd'] username = request.form['email'] # hash_pass = sha256_crypt.hash(password) # View encrypted password # Encrypt password hash_pass = sha256_crypt.hash ( password ) hash_user = sha256_crypt.hash ( username ) userfile = open ( "user_file.txt", "r" ) while userfile: user = userfile.readline () pwdd = userfile.readline () blankline = userfile.readline () while (blankline == ''): if (sha256_crypt.verify ( username, hash_user )): print("Good User") break userfile.close () # print ( "Password: " + password + " crypto: " + hash_pass ) # print ( "Email: " + username + " crypto: " + hash_user ) # usr_store ( hash_user, hash_pass ) # usr_read () if (sha256_crypt.verify ( password, hash_pass )) & (sha256_crypt.verify ( username, hash_user )): # return Response(str(authenticated)) print ( 'Good Login' ) return render_template ( 'menu.html', currtime=currenttime ) return else: print ( 'Bad Login' ) return render_template ( 'home.html', currtime=currenttime ) return Here is the output: 127.0.0.1 - - [07/Oct/2020 17:46:39] "GET /favicon.ico HTTP/1.1" 404 - Good User Good User Good User Good User Good User Good User Good User Good User Good User Good User Any help would be great Thank you, Mike From alan.gauld at yahoo.co.uk Wed Oct 7 20:07:28 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 8 Oct 2020 01:07:28 +0100 Subject: [Tutor] python grade converter In-Reply-To: <40BEC7F4-F207-4BCE-9002-78395F633FEA@hotmail.com> References: <40BEC7F4-F207-4BCE-9002-78395F633FEA@hotmail.com> Message-ID: On 07/10/2020 22:50, Dario Delfino wrote: > To whom this may concern, > > I have been creating a grade converter as a school project and > was wondering if you guys could help. i need to make it so that > if they got a grade 1= it would result in an f. You need to show us your code so far otherwise we can't begin to guess what it looks like. Also it would help to explain the problem more clearly, don't assume we know how your school grades things. I have no idea what a grade 1= is. And I assume there are multiple grades not just f? So is it only the f grade you are stuck on or is it all of them? How are you getting the data? From a user or from a file? Are you only processing oner students grade(s?) or many? All of these things make a difference to the solution. -- 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 Oct 7 20:12:58 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 8 Oct 2020 01:12:58 +0100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: On 07/10/2020 22:25, Alan Gauld via Tutor wrote: >> def sum_divisors(n): >> sum = 0 >> div =0 >> # Return the sum of all divisors of n, not including n >> while (div > 0 and div!=n): >> sum = sum + div >> return sum > Things wrong: > 1) You start with div=0 then immediately check if div > 0 which > it isn't. > 2) You never modify div or n so the while loop always gives > the same result. > 3) You never check if div is actually a diviror of n before > adding it to sum. I missed one: 4) You unconditionally return inside the while loop so it could never run more than once. -- 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 Oct 7 20:19:37 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 8 Oct 2020 01:19:37 +0100 Subject: [Tutor] Endless loop In-Reply-To: <59BE09C5-6734-459A-BE4F-3ADA59398FE4@getmailspring.com> References: <59BE09C5-6734-459A-BE4F-3ADA59398FE4@getmailspring.com> Message-ID: On 08/10/2020 00:59, Mike Duncan wrote: > Hi all., > I have an endless loop issue, frankly I don't know why it is stuck Neither do I and since you have lost all the indentation (you need to post in plain text not HTML) it is impossible to tell where any of the loops start/end. Please repost with the message in plain text. Then we might be able to make a stab at it. > @app.route ( "/auth", methods=['GET', 'POST'] ) > def authenticate_user(): > password = request.form['pwd'] > username = request.form['email'] > hash_pass = sha256_crypt.hash ( password ) > hash_user = sha256_crypt.hash ( username ) > > userfile = open ( "user_file.txt", "r" ) > while userfile: This might be the culprit. You are testing if the usefile object exists. The object will still exist even when you've read to the end of it, so the while will run forever unless you have a break. Which you do but I don't know where it fits in the logic, hence the need for a repost.... > user = userfile.readline () > pwdd = userfile.readline () > blankline = userfile.readline () > while (blankline == ''): > if (sha256_crypt.verify ( username, hash_user )): > print("Good User") > break > userfile.close () > if (sha256_crypt.verify ( password, hash_pass )) & (sha256_crypt.verify ( username, hash_user )): > print ( 'Good Login' ) > return render_template ( 'menu.html', currtime=currenttime ) > return > else: > print ( 'Bad Login' ) > return render_template ( 'home.html', currtime=currenttime ) > return -- 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 cs at cskk.id.au Wed Oct 7 23:34:51 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Thu, 8 Oct 2020 14:34:51 +1100 Subject: [Tutor] python grade converter In-Reply-To: <40BEC7F4-F207-4BCE-9002-78395F633FEA@hotmail.com> References: <40BEC7F4-F207-4BCE-9002-78395F633FEA@hotmail.com> Message-ID: <20201008033451.GA5659@cskk.homeip.net> On 07Oct2020 21:50, Dario Delfino wrote: >I have been creating a grade converter as a school project and was wondering if you guys could help. i need to make it so that if they got a grade 1= it would result in an f. I just need help with this, thanks[cid:C616695D-9DEA-4ED5-97F0-F02DC135A52C at home] I suspect from the "[cid:...]" above that you pasted a screenshot. This list discards screenshots; instead we work entirely in text (which lets us edit it, modify it, etc - it is also essential for vision impaired people). Please reply with the programme code pasted inline in the message as text. Don't forget that indentation is critical in Python, so check the cut/paste to make sure it reads correctly before sending the message. Cheers, Cameron Simpson From manpritsinghece at gmail.com Wed Oct 7 21:04:46 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Thu, 8 Oct 2020 06:34:46 +0530 Subject: [Tutor] Unpack arguments out of an Iterator Message-ID: Dear sir , Consider a problem, in which I have to print all odd numbers inside a list . I would prefer solving this problem by writing the code as given below : num_list = [2, 5, 8, 7, 4, 3, 1] odd_nums = (num for num in num_list if num % 2 != 0) print(*odd_nums) The answer is 5 7 3 1 , which is the right answer . Actually I have been experimenting with iterators for long and find it very convenient to work, so I have developed a habit to use iterators a lot. In this example you can see that odd_nums is an iterator consisting of all odd numbers from the list num_list, and for printing those odd numbers, I have used unpacking of the iterator using (*) inside print( ) function. Need your comments on the way i have used the iterator in the above program and the way i have unpacked the values from the iterator using (*) inside print. Regards Manprit Singh Need your comments, on this program From alan.gauld at yahoo.co.uk Thu Oct 8 05:32:55 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 8 Oct 2020 10:32:55 +0100 Subject: [Tutor] Unpack arguments out of an Iterator In-Reply-To: References: Message-ID: On 08/10/2020 02:04, Manprit Singh wrote: > num_list = [2, 5, 8, 7, 4, 3, 1] > odd_nums = (num for num in num_list if num % 2 != 0) > print(*odd_nums) > Actually I have been experimenting with iterators for long and find it very > convenient to work, so I have developed a habit to use iterators a lot. I think you might be meaning generators not iterators? The above code uses a generator expression inside parentheses to create a tuple. In the print statement you unpack the tuple (which could be created in any way you like) > this example you can see that odd_nums is an iterator consisting of all odd > numbers from the list num_list, and for printing those odd numbers, I have > used unpacking of the iterator using (*) inside print( ) function. All the basic Python collection types are iterators or can be used as such. You can also unpack lists. But not all iterators can be unpacked. > Need your comments on the way i have used the iterator in the above program > and the way i have unpacked the values from the iterator using (*) inside > print. Its correct and works and is appropriate. But that's more to do with using a tuple data type than using iterators. I'm not sure what other kind of feedback you are looking for. The more normal use for iterators is in calling next() etc. -- 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 aliyan.navaid at gmail.com Thu Oct 8 07:29:52 2020 From: aliyan.navaid at gmail.com (Aliyan Navaid) Date: Thu, 8 Oct 2020 16:29:52 +0500 Subject: [Tutor] Valid Username Program Message-ID: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> def valid_username(username): ??? if len(username) < 3: ??????? print("Username must be atleast 3 characters long") ??? elif len(username) > 15: ??????? print("Username is too long") ??? else: ??????? print("Valid Username") ? ? Dear Sir, So this program checks the validity of a username. I wanted to ask that instead of elif, I could?ve written another If statement in this program right ? And can you please also explain that when to use elif statement and when to use multiple if statements. ? From Richard at Damon-Family.org Thu Oct 8 09:05:55 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Thu, 8 Oct 2020 09:05:55 -0400 Subject: [Tutor] Valid Username Program In-Reply-To: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> References: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> Message-ID: <05bd892f-3396-4869-f263-6dbe36fd51ce@Damon-Family.org> On 10/8/20 7:29 AM, Aliyan Navaid wrote: > def valid_username(username): > > ??? if len(username) < 3: > > ??????? print("Username must be atleast 3 characters long") > > ??? elif len(username) > 15: > > ??????? print("Username is too long") > > ??? else: > > ??????? print("Valid Username") > > ? > > ? > > Dear Sir, > > So this program checks the validity of a username. > > I wanted to ask that instead of elif, I could?ve written another If > statement in this program right ? > > And can you please also explain that when to use elif statement and when > to use multiple if statements. > If the elif had been an if, then the final else would be run for any username <= 15 characters long, even if they are <3 characters long (those would print: Username must be at least 3 characters long Valid Username The key here is that an if / elif / else chain will only run exactly one of the following code sections, but with if / if? / else the final two are not eliminated by the success of the first. -- Richard Damon From alan.gauld at yahoo.co.uk Thu Oct 8 09:16:34 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 8 Oct 2020 14:16:34 +0100 Subject: [Tutor] Valid Username Program In-Reply-To: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> References: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> Message-ID: On 08/10/2020 12:29, Aliyan Navaid wrote: > def valid_username(username): > ??? if len(username) < 3: > ??????? print("Username must be atleast 3 characters long") > ??? elif len(username) > 15: > ??????? print("Username is too long") > ??? else: > ??????? print("Valid Username") > I wanted to ask that instead of elif, I could?ve written another If > statement in this program right ? Not quite. Consider the else part. How would you have written that? You would need a third if statement that checked the inverse of both the previous conditions: if 3 <= len(username) <= 15: print("Valid Username") So you have to decide if the extra comparison is better or worse than the elif structure. In this case it doesn't make much difference, but what if you had several elif statements your "else" test would need to incorporate all of those tests negated. Also you have to be very careful not to double-process values. You are OK in this example but it can get more complex. consider the following: size = int(input("size")) if size > 50: print("Too big") if size > 30: print("That's a big one!") if size > 20: print("Normal") if size > 10: print("That's small!") is size <= 10: print("Too small") Now what happens if size is 60? The first 4 tests all print! But if we used elifs instead then only the first condition would be triggered. > And can you please also explain that when to use elif statement and when > to use multiple if statements. You can use multiple if statements a) if the tests are completely independent(and will always stay that way) or b) if, in a case like the example above, you actually want multiple cases to trigger. But those are the exception rather than the rule, in most scenarios elif is the safer option. The third scenario to use multiple ifs is inside a function where each 'if' triggers a 'return' statement that will exit the function. In that case the subsequent 'if' is only reached if the predecessors were not triggered. That will only make sense if you have studied functions already. If not just ignore it for now! -- 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 aliyan.navaid at gmail.com Thu Oct 8 10:44:17 2020 From: aliyan.navaid at gmail.com (Aliyan Navaid) Date: Thu, 8 Oct 2020 19:44:17 +0500 Subject: [Tutor] Valid Username Program In-Reply-To: References: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> Message-ID: Since i'm a beginner could you please give examples for the last part ? where you list all the possible scenarios. On Thu, Oct 8, 2020, 6:17 PM Alan Gauld via Tutor wrote: > On 08/10/2020 12:29, Aliyan Navaid wrote: > > def valid_username(username): > > if len(username) < 3: > > print("Username must be atleast 3 characters long") > > elif len(username) > 15: > > print("Username is too long") > > else: > > print("Valid Username") > > > I wanted to ask that instead of elif, I could?ve written another If > > statement in this program right ? > > Not quite. Consider the else part. How would you have written that? > You would need a third if statement that checked the inverse of > both the previous conditions: > > if 3 <= len(username) <= 15: > print("Valid Username") > > So you have to decide if the extra comparison is better or worse > than the elif structure. In this case it doesn't make much difference, > but what if you had several elif statements your "else" test would need > to incorporate all of those tests negated. > > Also you have to be very careful not to double-process values. You are > OK in this example but it can get more complex. consider the following: > > size = int(input("size")) > if size > 50: print("Too big") > if size > 30: print("That's a big one!") > if size > 20: print("Normal") > if size > 10: print("That's small!") > is size <= 10: print("Too small") > > Now what happens if size is 60? > The first 4 tests all print! > But if we used elifs instead then only the first condition > would be triggered. > > > And can you please also explain that when to use elif statement and > when > > to use multiple if statements. > > You can use multiple if statements > a) if the tests are completely independent(and will always stay that > way) or > b) if, in a case like the example above, you actually want multiple > cases to trigger. > > But those are the exception rather than the rule, in most scenarios > elif is the safer option. > > The third scenario to use multiple ifs is inside a function > where each 'if' triggers a 'return' statement that will exit > the function. In that case the subsequent 'if' is only > reached if the predecessors were not triggered. > That will only make sense if you have studied functions already. > If not just ignore it for now! > > > -- > 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 manpritsinghece at gmail.com Thu Oct 8 10:00:56 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Thu, 8 Oct 2020 19:30:56 +0530 Subject: [Tutor] Unpack arguments out of an Iterator In-Reply-To: References: Message-ID: Dear sir , This time, i am raising a question based on your reply . As far as i know a generator expression returns an iterator . Is my knowledge incorrect ? The generator expression is assigned to the variable odd_nums, and hence i am saying that odd_nums is an iterator. Kindly comment Regards Manprit Singh On Thu, Oct 8, 2020 at 3:03 PM Alan Gauld via Tutor wrote: > On 08/10/2020 02:04, Manprit Singh wrote: > > > num_list = [2, 5, 8, 7, 4, 3, 1] > > odd_nums = (num for num in num_list if num % 2 != 0) > > print(*odd_nums) > > > Actually I have been experimenting with iterators for long and find it > very > > convenient to work, so I have developed a habit to use iterators a lot. > > I think you might be meaning generators not iterators? > The above code uses a generator expression inside > parentheses to create a tuple. > > In the print statement you unpack the tuple (which could > be created in any way you like) > > > this example you can see that odd_nums is an iterator consisting of all > odd > > numbers from the list num_list, and for printing those odd numbers, I > have > > used unpacking of the iterator using (*) inside print( ) function. > > All the basic Python collection types are iterators or > can be used as such. You can also unpack lists. > But not all iterators can be unpacked. > > > Need your comments on the way i have used the iterator in the above > program > > and the way i have unpacked the values from the iterator using (*) inside > > print. > > Its correct and works and is appropriate. But that's more > to do with using a tuple data type than using iterators. > I'm not sure what other kind of feedback you are looking for. > > The more normal use for iterators is in calling next() etc. > > -- > 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 manpritsinghece at gmail.com Thu Oct 8 15:22:16 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 9 Oct 2020 00:52:16 +0530 Subject: [Tutor] using conditional expression Message-ID: Dear sir , Let us consider a problem where i have to make a new list of all even values present in an existing list . Now if the existing list has no even item , the newly constructed list will be empty . Now i have to write a program that prints the new list if it has even value , otherwise it should print "Generated list is empty". The most popular way of doing this is : list1 = [3, 7, 5, 9, 1] list2 = [i for i in list1 if i % 2 == 0] if list2: print(list2) else: print("Generated list is empty") Just need to check if this can be written as given below or not : list1 = [3, 7, 5, 9, 1] list2 = [i for i in list1 if i % 2 == 0] res = list2 if list2 else "Generated list is empty" print(res) Here in this example a conditional expression is used . Third alternative way is : list1 = [3, 7, 5, 9, 1] list2 = [i for i in list1 if i % 2 == 0] res = list2 or "Generated list is empty" print(res) Which way should be preferred to solve this kind of problem ? need your comments Regards Manprit Singh From PyTutor at DancesWithMice.info Thu Oct 8 16:53:35 2020 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 9 Oct 2020 09:53:35 +1300 Subject: [Tutor] using conditional expression In-Reply-To: References: Message-ID: <0269cc43-6178-fda4-6c25-a6995660727e@DancesWithMice.info> On 09/10/2020 08:22, Manprit Singh wrote: > Dear sir , > Let us consider a problem where i have to make a new list of all even ... > Just need to check if this can be written as given below or not : What happened when you wrote it that way and ran the program? > Third alternative way is : Can you solve the problem all on one line? Can you solve the problem with a single loop rather than multiple compound statements? > Which way should be preferred to solve this kind of problem ? > need your comments How might the answer depend upon the level of competence - of you, your colleagues, and/or future coders who may be expected to maintain this code? What are your arguments for code-brevity and the exertion of powerful coding-constructs (and inevitably, increased complexity)? What might be the arguments for eschewing comprehensions and the like, in favor of 'straight-line', if longer, code blocks? -- Regards =dn From PyTutor at DancesWithMice.info Thu Oct 8 19:17:38 2020 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 9 Oct 2020 12:17:38 +1300 Subject: [Tutor] Valid Username Program In-Reply-To: References: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> Message-ID: On 09/10/2020 03:44, Aliyan Navaid wrote: > Since i'm a beginner could you please give examples for the last part ? > where you list all the possible scenarios. > > On Thu, Oct 8, 2020, 6:17 PM Alan Gauld via Tutor wrote: > >> On 08/10/2020 12:29, Aliyan Navaid wrote: >>> def valid_username(username): >>> if len(username) < 3: >>> print("Username must be atleast 3 characters long") >>> elif len(username) > 15: >>> print("Username is too long") >>> else: >>> print("Valid Username") >> >>> I wanted to ask that instead of elif, I could?ve written another If >>> statement in this program right ? ... >> But those are the exception rather than the rule, in most scenarios >> elif is the safer option. +1 In 'the ?good, old, days' you would have been asked to draw a flowchart of the decision(s). Such a 'picture' quickly illustrates @Richard's point - neatly covered by http://web.engr.oregonstate.edu/~rookert/cs162/ecampus-video/CS161/template/chapter_4/ifelse.html In the case of a single "independent-variable" (len( username ), above), we can code a "ladder" of if and elif clauses (probably terminating with an else). Here we have such a short "ladder" it is barely recognisable as such - we'll come back to that later. Let's split the problem into its components (as per code, above): 1 the "independent variable": username_length = len( username ) 2 what should happen if the username_length is less than three-characters. 3 what should happen if the username_length is more than 15-characters. 4 what should happen if the username_length is not either of the "3" or "15" considerations. The first suggestion is to use a value: username_length; in that it is better to compute something once, rather than hundreds of times (appreciating that in this 'toy example' the difference is inconsequential, but let's call it "good practice" or a habit worth cultivating). Also, it simplifies explanations to have a single-word description. The second suggestion is to pick-up the hint in using the term "independent variable". We compare it to three values: 3, 15, and 'between'. Let's express them in a more logical sequence: "3, between, 15" This leads us neatly into @Alan's suggestion of a function which returns three different results, as appropriate: def username_length_decision( username_length ): if username_length < 3: return "short" if username_length < 15: return "valid" return "long" Reverting to the flowchart, and comparing that to this re-statement of the code, can you start to see the "ladder"? If not, code imaginary alternative actions to take place at 20 and 25. The study-example which is popularly used is to look at converting percentage grades for student-assignments into a letter ("A" (very good) through "F" (failure) ) wherein there are five decisions to be made (if or elif) and six alternate results. Try flowcharting and/or coding that one... To finish, let's look at the more advanced issue: the more general solution, and the more numerous case. How would you like to code a procedure which requires a choice to be made amongst 100 different levels? Indeed, even the student-grades application mentioned, starts to make my typing-fingers weary! Is there another (pythonic) solution? (of course there is!) - starting from the specification outlined above, def[ine] a function for each (distinct) action that could be carried-out under the control of this decision, eg def short()... def valid()... def long()... (etc) NB this approach is a good coding habit, called "modular programming". ...and here's the 'trick': in Python a function is a "first class object". We can quietly ignore that ComSc definition by understanding that a function can be treated as if it was a piece of data. This is an informal or "rule of thumb", but it will do for today. This enables us to put these three, six (or hundreds) of function names together with the username_length "independent variable". Create a dictionary and populate it with "pairs": the "independent variable" and its ("dependent") action-function: decision_dict = { 3:short, 15:valid, } Now, faced with a decision to be made, we can loop through the dictionary, and apply the "independent variable" to each key, and once the key is chosen, execute the appropriate function: for key_username_length, action_function in decision_dict.items(): if username_length < key_username_length: action_function() break The first time through the loop is exactly: if username_length < 3: short() and if it that condition is true, the break saves us from looping any further. It's as easy as that, because - there's only one "independent variable" driving the choice, - the choices all use the same boolean comparison, and - the choices can be logically-sequenced. Oh but wait, is something missing? Yes! We've covered everything that used to be in an if or elif clause, but what about the else-choice, ie >15 characters? Here we apply another advanced and pythonic solution: Python's for-loops include an optional else-clause too. In this case, (only) if the loop terminates without break-ing, will control pass to the else-clause. Thus: for key_username_length... if ... else: long() WebRefs: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops https://book.pythontips.com/en/latest/for_-_else.html Warning: the use of else clauses after for- (or while-) loops is widely misunderstood (pronounce the "else" as: 'else if no break'). For this reason, most try not to use them. However, if more of us learned their proper use, that would cease to be a concern. That "which came first, the chicken or the egg" problem is something for another day... PS If the solution depends upon multiple dependent-variables then please review https://en.wikipedia.org/wiki/Decision_table -- Regards =dn From alan.gauld at yahoo.co.uk Thu Oct 8 19:43:48 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 9 Oct 2020 00:43:48 +0100 Subject: [Tutor] Unpack arguments out of an Iterator In-Reply-To: References: Message-ID: On 08/10/2020 15:00, Manprit Singh wrote: > This time, i am raising a question based on your reply . > > As far as i know a generator expression returns an iterator No you are correct, but that is like saying you like arithmetic operators because they return numbers. Numbers are useful in all sorts of other contexts. Likewise iterators are a far more general concept than those returned by generator expressions. And the iterator aspect of the collections returned by generator expressions has nothing much to do with your ability to unpack them using *. That has always been a feature of python tuples and lists. Even before iterators were introduced to the language. These are two separate features and it wasn't clear in your first post whether you were interested in the iterable nature of collections or the ability to unpack from them. > The generator expression is assigned to the variable odd_nums, and hence i > am saying that odd_nums is an iterator. That's correct but entirely orthogonal to your ability to unpack its values. Python collections can be unpacked with *, they always have been. And Python collections are iterable. But the two are not directly connected(except perhaps at the implementation level). You can deine your own iterables that can also be unpacked: >>> def f(a,b,c): print(a,b,c) >>> class three_ones: def __init__(self): self.count = 0 def __iter__(self): return self # part of iterator protocol def __next__(self): # ditto if self.count < 3: self.count+= 1 return 1 else: raise StopIteration >>> to = three_ones() >>> f(*to) 1 1 1 >>> So when you said: """I have developed a habit to use iterators a lot""" and """Need your comments on the way i have used the iterator in the above program and the way i have unpacked the values from the iterator using (*) inside print.""" It's not clear whether you are using unpacking from collections (aka iterators) a lot or whether you use generator expressions a lot. -- 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 Oct 8 20:08:54 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 9 Oct 2020 01:08:54 +0100 Subject: [Tutor] Valid Username Program In-Reply-To: References: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> Message-ID: On 08/10/2020 15:44, Aliyan Navaid wrote: > Since i'm a beginner could you please give examples for the last part ? > where you list all the possible scenarios. I'll try... >> You can use multiple if statements >> a) if the tests are completely independent(and will always stay that >> way) or if size = value1: ...do something if size == value2: do something else... These are tests for specific values so it doesn't need an elif, only one specific test can ever be true.(Assuming value1 does not equal value2!) Of course you still have the problem of creating an else if size not in (value1,value2,......): ...do else... So every time you add an if test for a new value you need to add a value to the "else" test.... A different take in the independent tests scenario is where we check for different types of concept. Consider an order processing app that has to check an order item: if order.stock == 0: put_on_wait_list(order) if order.value > 1000: process(high_value(order)) if order.shipping_Method == DOWNLOAD: copy_to_ftp(order) Here we are checking multiple things but we want to perform all checks on all orders, we explicitly don't want to have an else before each test. So elif would be the wrong thing to use. >> b) if, in a case like the example above, you actually want multiple >> cases to trigger. Lets reconstruct the previous example slightly so that we do want multiple outputs: size = int(input("size")) if size <= 10: print("Too small") if size > 10: print("Not bad") if size > 20: print("Reasonable") if size > 30: print("That's a big one") if size > 50: print("That's too big!") Now if we enter a value <= 20 we get one output. But if we enter 21 up we get multiple outputs But they are not contradictory. For example 40 yields: Not bad Reasonable That's a big one. This is rather contrived but if instead of printing a message we wanted to perform some size specific data processing then it might be good to perform it in stages after each applicable if test. But as I said this is a very rare scenario. in most cases you'd just use elif: size = int(input("size")) if size > 50: print("Too big") elif size > 30: print("That's a big one!") elif size > 20: print("Normal") elif size > 10: print("That's small!") else: print("Too small") >> The third scenario to use multiple ifs is inside a function >> where each 'if' triggers a 'return' statement that will exit >> the function. def appraise_size(size): if size > 50: return "Too big" if size > 30: return "That's a big one!" if size > 20: return "Normal" if size > 10: return "That's small!" return "Too small" Each return statement stops execution of the rest of the function so we don't need elif statements. Similarly we don't need else since the only way to reach the last line if if all the if tests failed. This is probably the most common case where elif is not used but could have been. I hope that clarifies what I meant. -- 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 Oct 8 20:17:15 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 9 Oct 2020 01:17:15 +0100 Subject: [Tutor] using conditional expression In-Reply-To: References: Message-ID: On 08/10/2020 20:22, Manprit Singh wrote: > print "Generated list is empty". The most popular way of doing this is : > > list1 = [3, 7, 5, 9, 1] > list2 = [i for i in list1 if i % 2 == 0] > if list2: > print(list2) > else: > print("Generated list is empty") > > Just need to check if this can be written as given below or not : > > list1 = [3, 7, 5, 9, 1] > list2 = [i for i in list1 if i % 2 == 0] > res = list2 if list2 else "Generated list is empty" > print(res) Yes it can, it works. Although arguably it would be more readable to miss out the redundant variable res and just put the expression in the print: print(list2 if list2 else "Generated list is empty") Which ou choose depends on which is most readable sand therefore maintainable. Conditional expressions can seem confusing to some readers, and can get very complex if there are more than 2 options. In that case I'd definitely revert to explicit if/else. > Third alternative way is : > list1 = [3, 7, 5, 9, 1] > list2 = [i for i in list1 if i % 2 == 0] > res = list2 or "Generated list is empty" > print(res) This was common practice before conditional expressions were introduced and is still used by some die-hards but is now deprecated in favour of conditionals. Conditionals are harder to get wrong and do not abuse a side-effect of boolean logic implementation (albeit a guaranteed side effect)! -- 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 manpritsinghece at gmail.com Fri Oct 9 11:37:20 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 9 Oct 2020 21:07:20 +0530 Subject: [Tutor] Duplicate items in list Message-ID: Dear sir, Consider a list as given below : lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] I need to print the values as given below and in same order: 3 # print 3 only once as there are two occurrence of 3 in the beginning in list 5 # print 5 only once as there are 3 occurrence of 5 after 3 in the list 6 # print 6 only once as there are 3 occurrence of 6 after 5 in the list 5 # print 5 only once as there is single occurrence of 5 after 6 in the list 9 # print 9 only once as there is single occurrence of 9 after 5 in the list 3 # print 3 only once as there are 3 occurrence of 3 after 9 in the list 5 # print 5 only once as there are 2 occurrence of 5 in the last I have written the code as given below: lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] for i, j in enumerate(lst[:-1]): if lst[i+1] != j: print(j) print(lst[-1]) which gives the answer as given above I feel that a better code can be written for this problem , Need your guidance. Regards Manprit singh From mats at wichmann.us Fri Oct 9 12:16:50 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 9 Oct 2020 10:16:50 -0600 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: On 10/9/20 9:37 AM, Manprit Singh wrote: > Dear sir, > > Consider a list as given below : > > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > I need to print the values as given below and in same order: > > 3 # print 3 only once as there are two occurrence of 3 in the > beginning in list > 5 # print 5 only once as there are 3 occurrence of 5 after 3 in the > list > 6 # print 6 only once as there are 3 occurrence of 6 after 5 in the > list > 5 # print 5 only once as there is single occurrence of 5 after 6 in > the list > 9 # print 9 only once as there is single occurrence of 9 after 5 in > the list > 3 # print 3 only once as there are 3 occurrence of 3 after 9 in the > list > 5 # print 5 only once as there are 2 occurrence of 5 in the last > > I have written the code as given below: > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > for i, j in enumerate(lst[:-1]): > if lst[i+1] != j: > print(j) > print(lst[-1]) > > which gives the answer as given above > I feel that a better code can be written for this problem , Need your > guidance. Turns out there are a ton of ways to get the unique values from a list. The problem comes up often, usually in the context of "what is the fastest way...". The answer depends on whether you need to preserve the order or not, and what degree of cleverness feels comfortable in your code. If order doesn't matter, using a set will give you unique uniques = set(lst) # and to print: print(*uniques) If order does matter - as you have indicated it does, it is now possible to do with with a dictionary operation. This wins for speed, but isn't necessarily the "most obvious": uniques = list(dict.fromkeys(lst)) dict.fromkeys constructs (using dict's alternate constructor) a dictionary given a list of keys (the values will all be None). When you then convert the dictionary to a list, that is implicitly like doing list(d.keys()), but you don't have to specify the keys(). Since dictionary keys by definition must be unique, this uniquifies. Other options exist, as noted... One is to use a set, but only as a tracking devices: seen = set() uniques = [x for x in lst if x not in seen and not seen.add(x)] From mats at wichmann.us Fri Oct 9 12:40:42 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 9 Oct 2020 10:40:42 -0600 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: <80478469-d717-e4fc-565e-6a88a8e6fb0b@wichmann.us> On 10/9/20 10:16 AM, Mats Wichmann wrote: > On 10/9/20 9:37 AM, Manprit Singh wrote: >> Dear sir, >> >> Consider a list as given below : >> >> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] >> I need to print the values as given below and in same order: >> >> 3 # print 3 only once as there are two occurrence of 3 in the >> beginning in list >> 5 # print 5 only once as there are 3 occurrence of 5 after 3 in the >> list >> 6 # print 6 only once as there are 3 occurrence of 6 after 5 in the >> list >> 5 # print 5 only once as there is single occurrence of 5 after 6 in >> the list >> 9 # print 9 only once as there is single occurrence of 9 after 5 in >> the list >> 3 # print 3 only once as there are 3 occurrence of 3 after 9 in the >> list >> 5 # print 5 only once as there are 2 occurrence of 5 in the last >> >> I have written the code as given below: >> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] >> for i, j in enumerate(lst[:-1]): >> if lst[i+1] != j: >> print(j) >> print(lst[-1]) >> >> which gives the answer as given above >> I feel that a better code can be written for this problem , Need your >> guidance. > > Turns out there are a ton of ways to get the unique values from a list. It also helps if you grasp the whole problem, sigh... you don't want unique values per se, you just want to remove consecutive duplicates. That wants a different answer. If someone else doesn't pop up, I might swing back and look at the actual question later :) From manpritsinghece at gmail.com Fri Oct 9 12:41:13 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 9 Oct 2020 22:11:13 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Dear Mats Wichmann, Here in this question my purpose is not to remove duplicates from the list.This question is about removing duplicates from the groups. see the list is lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5], the output i need is : 3 5 6 5 9 3 5 As you can see 3 and 5 are still repeating in the output , there are 2 groups of 3 in the list, i have to write a program that gives a single three for each group of 3, in that way 3 will occur in the output for 2 times, for the same reason 5 will occur in the output for 3 times . Regards Manprit Singh On Fri, Oct 9, 2020 at 9:47 PM Mats Wichmann wrote: > On 10/9/20 9:37 AM, Manprit Singh wrote: > > Dear sir, > > > > Consider a list as given below : > > > > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > > I need to print the values as given below and in same order: > > > > 3 # print 3 only once as there are two occurrence of 3 in the > > beginning in list > > 5 # print 5 only once as there are 3 occurrence of 5 after 3 in the > > list > > 6 # print 6 only once as there are 3 occurrence of 6 after 5 in the > > list > > 5 # print 5 only once as there is single occurrence of 5 after 6 in > > the list > > 9 # print 9 only once as there is single occurrence of 9 after 5 in > > the list > > 3 # print 3 only once as there are 3 occurrence of 3 after 9 in > the > > list > > 5 # print 5 only once as there are 2 occurrence of 5 in the last > > > > I have written the code as given below: > > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > > for i, j in enumerate(lst[:-1]): > > if lst[i+1] != j: > > print(j) > > print(lst[-1]) > > > > which gives the answer as given above > > I feel that a better code can be written for this problem , Need your > > guidance. > > Turns out there are a ton of ways to get the unique values from a list. > The problem comes up often, usually in the context of "what is the > fastest way...". The answer depends on whether you need to preserve the > order or not, and what degree of cleverness feels comfortable in your code. > > If order doesn't matter, using a set will give you unique > > uniques = set(lst) > # and to print: > print(*uniques) > > If order does matter - as you have indicated it does, it is now possible > to do with with a dictionary operation. This wins for speed, but isn't > necessarily the "most obvious": > > uniques = list(dict.fromkeys(lst)) > > dict.fromkeys constructs (using dict's alternate constructor) a > dictionary given a list of keys (the values will all be None). When you > then convert the dictionary to a list, that is implicitly like doing > list(d.keys()), but you don't have to specify the keys(). Since > dictionary keys by definition must be unique, this uniquifies. > > Other options exist, as noted... > > One is to use a set, but only as a tracking devices: > > seen = set() > uniques = [x for x in lst if x not in seen and not seen.add(x)] > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From manpritsinghece at gmail.com Fri Oct 9 12:50:17 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 9 Oct 2020 22:20:17 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: <80478469-d717-e4fc-565e-6a88a8e6fb0b@wichmann.us> References: <80478469-d717-e4fc-565e-6a88a8e6fb0b@wichmann.us> Message-ID: Dear Sir , And another try to write it in the form of a generator function as given below : (Just want to share it with you ). def remove_cons(lst): for i, j in enumerate(lst[:-1]): if lst[i+1] != j: yield j yield lst[-1] lst1 = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5] for i in remove_cons(lst1): print(i) On Fri, Oct 9, 2020 at 10:10 PM Mats Wichmann wrote: > On 10/9/20 10:16 AM, Mats Wichmann wrote: > > On 10/9/20 9:37 AM, Manprit Singh wrote: > >> Dear sir, > >> > >> Consider a list as given below : > >> > >> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > >> I need to print the values as given below and in same order: > >> > >> 3 # print 3 only once as there are two occurrence of 3 in the > >> beginning in list > >> 5 # print 5 only once as there are 3 occurrence of 5 after 3 in > the > >> list > >> 6 # print 6 only once as there are 3 occurrence of 6 after 5 in > the > >> list > >> 5 # print 5 only once as there is single occurrence of 5 after 6 > in > >> the list > >> 9 # print 9 only once as there is single occurrence of 9 after 5 > in > >> the list > >> 3 # print 3 only once as there are 3 occurrence of 3 after 9 in > the > >> list > >> 5 # print 5 only once as there are 2 occurrence of 5 in the last > >> > >> I have written the code as given below: > >> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > >> for i, j in enumerate(lst[:-1]): > >> if lst[i+1] != j: > >> print(j) > >> print(lst[-1]) > >> > >> which gives the answer as given above > >> I feel that a better code can be written for this problem , Need your > >> guidance. > > > > Turns out there are a ton of ways to get the unique values from a list. > > It also helps if you grasp the whole problem, sigh... you don't want > unique values per se, you just want to remove consecutive duplicates. > That wants a different answer. If someone else doesn't pop up, I might > swing back and look at the actual question later :) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From mats at wichmann.us Fri Oct 9 12:56:02 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 9 Oct 2020 10:56:02 -0600 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: On 10/9/20 10:41 AM, Manprit Singh wrote: > Dear Mats Wichmann, > > Here in this question my purpose is not to remove duplicates from the > list.This question is about removing duplicates from the groups. > see the list is lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5], the > output i need is : > 3 > 5 > 6 > 5 > 9 > 3 > 5 > As you can see 3 and 5 are still repeating in the output , there are 2 > groups of 3 in the list, i have to write a program that gives a single > three for each group of 3, in that way 3 will occur in the output for 2 > times, for the same reason 5 will occur in the output for 3 times . Once you used the word group it triggered the memory that There's a Method For That: itertools.groupby. >>> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] >>> z = itertools.groupby(lst) >>> # groupby gives you back the list split into tuples representing the groups >>> print(*z) (3, ) (5, ) (6, ) (5, ) (9, ) (3, ) (5, ) >>> # So a possible solution: >>> nodupes = [x[0] for x in itertools.groupby(lst)] >>> nodupes [3, 5, 6, 5, 9, 3, 5] From breamoreboy at gmail.com Fri Oct 9 12:57:29 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 9 Oct 2020 17:57:29 +0100 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: On 09/10/2020 17:16, Mats Wichmann wrote: > On 10/9/20 9:37 AM, Manprit Singh wrote: >> Dear sir, >> >> Consider a list as given below : >> >> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] >> I need to print the values as given below and in same order: >> >> 3 # print 3 only once as there are two occurrence of 3 in the >> beginning in list >> 5 # print 5 only once as there are 3 occurrence of 5 after 3 in the >> list >> 6 # print 6 only once as there are 3 occurrence of 6 after 5 in the >> list >> 5 # print 5 only once as there is single occurrence of 5 after 6 in >> the list >> 9 # print 9 only once as there is single occurrence of 9 after 5 in >> the list >> 3 # print 3 only once as there are 3 occurrence of 3 after 9 in the >> list >> 5 # print 5 only once as there are 2 occurrence of 5 in the last >> >> I have written the code as given below: >> lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] >> for i, j in enumerate(lst[:-1]): >> if lst[i+1] != j: >> print(j) >> print(lst[-1]) >> >> which gives the answer as given above >> I feel that a better code can be written for this problem , Need your >> guidance. > > Turns out there are a ton of ways to get the unique values from a list. > The problem comes up often, usually in the context of "what is the > fastest way...". The answer depends on whether you need to preserve the > order or not, and what degree of cleverness feels comfortable in your code. > > If order doesn't matter, using a set will give you unique > > uniques = set(lst) > # and to print: > print(*uniques) > > If order does matter - as you have indicated it does, it is now possible > to do with with a dictionary operation. This wins for speed, but isn't > necessarily the "most obvious": > > uniques = list(dict.fromkeys(lst)) > > dict.fromkeys constructs (using dict's alternate constructor) a > dictionary given a list of keys (the values will all be None). When you > then convert the dictionary to a list, that is implicitly like doing > list(d.keys()), but you don't have to specify the keys(). Since > dictionary keys by definition must be unique, this uniquifies. > > Other options exist, as noted... > > One is to use a set, but only as a tracking devices: > > seen = set() > uniques = [x for x in lst if x not in seen and not seen.add(x)] > That doesn't work, but if it makes you feel any better I fell for it as well from the subject line :) Check the OP's output and 3 appears twice, 5 three times. Unless there's a one liner using the itertools module, which I'm too lazy to try out right now, I'd say that you might as well stick with his original loop. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From mats at wichmann.us Fri Oct 9 13:39:04 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 9 Oct 2020 11:39:04 -0600 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: <427594f9-6eb2-c4ec-0276-b164f9c60ebb@wichmann.us> On 10/9/20 10:57 AM, Mark Lawrence wrote: Check the OP's output and 3 appears > twice, 5 three times. yeah, my bad, I followed up. Unless there's a one liner using the itertools > module, which I'm too lazy to try out right now, I'd say that you might > as well stick with his original loop. turns out there is :) From nathan-tech at hotmail.com Fri Oct 9 16:22:56 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Fri, 9 Oct 2020 21:22:56 +0100 Subject: [Tutor] creating a server In-Reply-To: References: Message-ID: Hi folks, going off of the feedback I have created these two files which I have attached. One is the server and the other is a basic client I used to test it. Notes: 1. In the server I've been a bit lax with the try and except statements but I've noted that in the comments as this is just a proof of concept for the moment. 2. On the client, if it were a real client, i'd imagine it'd have to have a similar set up to the server for sending and receiving, except instead of raising on failure, the server would resend the message length and start again. I would be really interested on opinions and thoughts you all may have as I continue to learn :) Thanks in advance Nathan On 07/10/2020 22:15, Alan Gauld via Tutor wrote: > On 07/10/2020 20:33, nathan tech wrote: > >> There's a delay due to moderator approval (is that because I am new/) >> and the question has been answered :) > If you are new then you will be automatically put on full moderation > until I get around to removing you. > > I've just done that so newer messages should go straight through. > > Alan g. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://nam10.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&data=02%7C01%7C%7C93d6ceec71d2433a0dda08d86b06510b%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637377022150293957&sdata=iKvFv%2FDOvI39%2FHdbTh8AfXV5FsKwQmhJvVhWS0rG5HU%3D&reserved=0 -------------- next part -------------- # just a simple example sending function import socket HOST = "localhost" PORT = 8000 def send(sock, msg): l=len(msg) # number of bites of message s.send(b"{"+(str(l).encode("utf8"))+b"}") if(sock.recv(2)!=b"ok"): raise("Socket error.") sock.sendall(msg) if(sock.recv(2)!=b"ok"): raise("Socket error.") return 1 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) send(s, b"Hello!") print(s.recv(1024)) s.close() -------------- next part -------------- import socket import time class user: def __init__(self, sock): self.sock=sock self.read=b'' self.msg=b'' self.expected_length=0 def rec(self): try: # non blocking error avoidance data=self.sock.recv(1024) except: # will want to put a catch in here for except read error because connection is closed and return something for the main loop to handle data=b'' self.read=self.read+data if(self.expected_length != 0): if(len(self.read)>=self.expected_length): self.msg=self.read[:self.expected_length+1] # +1 because of indexes self.read=self.read[self.expected_length+1:] self.expected_length=0 self.sock.send(b"ok") self.process() if(self.expected_length==0 and len(self.read)>2 and self.read.find(b"{")==0 and self.read.find(b"}")>1): before=self.read.find(b"{") end=self.read.find(b"}") try: # just in case invalid self.expected_length=int(self.read[before+1:end]) except: self.sock.send(b"reset") self.read=b'' self.expected_length=0 self.read=self.read[end+1:] self.sock.send(b"ok") def process(self): if(self.msg==b"Hello!"): self.sock.send(b"Hi there, client. It's nice to be working with you!") users=[] HOST = 'localhost' PORT = 8000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(10000) # random high number s.setblocking(0) print("Server running.") while 1: # normally would tie this to a variable of shutdown but for testing purposes keyboard interupt is fine try: # catch any and all not ready yet socket errors conn, addr = s.accept() print("Say hello to ", addr[0], " on port ", addr[1]) users.append(user(conn)) except: # no one wants to join us, sad times ok=1 # just a variable so you don't get bugged about syntax for x in users: x.rec() time.sleep(0.01) # so we're not hogging resources. Necessary? From alan.gauld at yahoo.co.uk Fri Oct 9 19:33:11 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 10 Oct 2020 00:33:11 +0100 Subject: [Tutor] Valid Username Program In-Reply-To: References: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> Message-ID: On 09/10/2020 18:44, Dennis Lee Bieber wrote: > And even not quite the "good, old, days" one would have used > Nassi-Schneiderman (aka Chapin) charts. I've been aware of NS charts for years but I've never seen anyone use them outside college. I'm curious, has anyone actually use NS charts in real world projects? The reason I ask is that around 2002 I wrote a book called "A Software Designers Toolbox"(*) which documented around 40 software design notations that I had used (or seen used) and found useful in real projects. I considered NS charts but in the end left them out because they failed the test that I had actually seen them in use and they were effective. So has anyone used these and found them effective? (*)The book was alas never published since the publisher decided the market was too small. If anyone is curious the PDF of the draft(around 400 pages) is available on request! Every now and then I consider the effort to update it and self-publish just to put it out there... -- 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 PyTutor at DancesWithMice.info Fri Oct 9 21:40:34 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sat, 10 Oct 2020 14:40:34 +1300 Subject: [Tutor] Valid Username Program In-Reply-To: References: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> Message-ID: <35370926-0272-7693-1cb8-27912ad33b47@DancesWithMice.info> On 10/10/2020 06:44, Dennis Lee Bieber wrote: > On Fri, 9 Oct 2020 12:17:38 +1300, dn via Tutor > declaimed the following: > > >> In 'the ?good, old, days' you would have been asked to draw a flowchart >> of the decision(s). Such a 'picture' quickly illustrates @Richard's >> point - neatly covered by > > And even not quite the "good, old, days" one would have used > Nassi-Schneiderman (aka Chapin) charts. N-S charts being more structured > than flowcharts, and hence fit better with the "structured programming" > phase of the science. > > https://en.wikipedia.org/wiki/Nassi%E2%80%93Shneiderman_diagram I'm a flowchart-native and that may be the reason that I never 'took' to N-S charts. Per @Alan's observation, I've never seen them used in-anger either, but once did have a Tutor who liked them and I agreed to let him teach accordingly. The 'problem' with training courses and 'toy examples' is that there is seldom an obvious *need* for diagramming. Thus, trainees inevitably prefer to go straight-to-code. Accordingly, the power and virtue of diagramming is often 'lost'! When developing with flowcharts, there is a discipline of avoiding 'writing code', in order to concentrate on the logic. Whereas with N-S the tools were very much (as you say) to do with the program[me]'s structure and how it would implement the logic - but where did the logic [design] come-from? Almost a feeling of, write the code first, and then do the diagram[me]s; so that the Tutor doesn't criticise... (perhaps?) In the case of the OP's problem, where there were three outcomes and thus two?three decision-points; my feeling is that if you put an N-S diagram side-by-side with a flowchart, the latter would be both easier to express, and to read. The other consideration (which was offered to the OP as a possible-solution), is that when something is charted (pictured/diagrammed), we will often realise some advantage to re-arranging the logical sequence. This is a lot easier with a flowchart - albeit my opinion and maybe others feel otherwise... Nevertheless, will agree in the sense that https://en.wikipedia.org/wiki/A_picture_is_worth_a_thousand_words - many problems that 'Apprentices' bring, could be easily solved by using a 'visualisation tool'! -- Regards =dn From PyTutor at DancesWithMice.info Fri Oct 9 21:43:41 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sat, 10 Oct 2020 14:43:41 +1300 Subject: [Tutor] Valid Username Program In-Reply-To: References: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> Message-ID: <278200c6-7407-340e-f5e0-118bae449582@DancesWithMice.info> On 10/10/2020 06:44, Dennis Lee Bieber wrote: > On Fri, 9 Oct 2020 12:17:38 +1300, dn via Tutor > declaimed the following: > > >> In 'the ?good, old, days' you would have been asked to draw a flowchart >> of the decision(s). Such a 'picture' quickly illustrates @Richard's >> point - neatly covered by > > And even not quite the "good, old, days" one would have used > Nassi-Schneiderman (aka Chapin) charts. N-S charts being more structured > than flowcharts, and hence fit better with the "structured programming" > phase of the science. Assuming that the OP is now satisfied with/by the responses, like @Alan I'd like to risk hi-jacking the thread into another/related topic: My (non-COVID) $day-job, involves training in languages other than Python. There are major differences (obviously) between "Procedural" and "Declarative" languages, but there are also 'overlaps'. NB A fast-and-loose understanding of "Declarative" is that the code 'shows' the computer what/where the output should appear, rather than "Procedural" saying 'how to do it', eg a DB-query: SELECT name, rank, serial_number FROM person WHERE rank >= "Captain"; will output a table with three columns of data, and as many rows as there are people of senior rank appearing in the DB. This morning I was shown a (children's) book, "Flotsam"* which tells a story *entirely* in pictures - the only words are on the title-page, etc. The art-work is 'art' rather than 'comic-book' ("graphic novel" to sophisticates). Its communication-style fascinated. I was wondering if I could dream-up ('art' is definitely beyond my capacity) a how-to, for a particular tutorial in a declarative-language course, entirely presented as pictures, ie cause and effect - or more likely: effect, and how-to-cause? * apologies, didn't note bibliographic details -- Regards =dn From manpritsinghece at gmail.com Fri Oct 9 23:09:55 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 10 Oct 2020 08:39:55 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Dear sir , I would like to see suggestions for the solution of the problem given in my last mail without using any python standard library module .Is it possible ? Regards Manprit Singh On Fri, Oct 9, 2020 at 9:07 PM Manprit Singh wrote: > Dear sir, > > Consider a list as given below : > > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > I need to print the values as given below and in same order: > > 3 # print 3 only once as there are two occurrence of 3 in the > beginning in list > 5 # print 5 only once as there are 3 occurrence of 5 after 3 in the > list > 6 # print 6 only once as there are 3 occurrence of 6 after 5 in the > list > 5 # print 5 only once as there is single occurrence of 5 after 6 in > the list > 9 # print 9 only once as there is single occurrence of 9 after 5 in > the list > 3 # print 3 only once as there are 3 occurrence of 3 after 9 in the > list > 5 # print 5 only once as there are 2 occurrence of 5 in the last > > I have written the code as given below: > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > for i, j in enumerate(lst[:-1]): > if lst[i+1] != j: > print(j) > print(lst[-1]) > > which gives the answer as given above > I feel that a better code can be written for this problem , Need your > guidance. > > Regards > Manprit singh > > > From manpritsinghece at gmail.com Sat Oct 10 01:31:08 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 10 Oct 2020 11:01:08 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Dear sir , Kindly look at the solution given below : Kindly suggest , if something can be done better: def remove_cons(lst): for i in range(len(lst)-1): if lst[i] != lst[i+1]: yield lst[i] yield lst[-1] lst1 = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5, 5] print(*remove_cons(lst1)) The answer will be : 3 5 6 5 9 3 5 Regards Manprit Singh On Fri, Oct 9, 2020 at 9:07 PM Manprit Singh wrote: > Dear sir, > > Consider a list as given below : > > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > I need to print the values as given below and in same order: > > 3 # print 3 only once as there are two occurrence of 3 in the > beginning in list > 5 # print 5 only once as there are 3 occurrence of 5 after 3 in the > list > 6 # print 6 only once as there are 3 occurrence of 6 after 5 in the > list > 5 # print 5 only once as there is single occurrence of 5 after 6 in > the list > 9 # print 9 only once as there is single occurrence of 9 after 5 in > the list > 3 # print 3 only once as there are 3 occurrence of 3 after 9 in the > list > 5 # print 5 only once as there are 2 occurrence of 5 in the last > > I have written the code as given below: > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > for i, j in enumerate(lst[:-1]): > if lst[i+1] != j: > print(j) > print(lst[-1]) > > which gives the answer as given above > I feel that a better code can be written for this problem , Need your > guidance. > > Regards > Manprit singh > > > From navinray91 at gmail.com Sat Oct 10 00:41:30 2020 From: navinray91 at gmail.com (navin ray) Date: Sat, 10 Oct 2020 10:11:30 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Hi Manprit It's been a pleasure and a great learning to follow you and others on this mailing list. I am particularly interested in this problem because this was recently asked in interview which I wasn't able to answer. Could you provide solution to the same problem using very simple code (I.e without using any built in functions) so that even a noob like me could understand. I prefer codes written using simple logic (even though they are longer), they are easier to understand. I am sorry if my suggestions is not relevant to the mailing list. My apologies in advance. Regards// On Sat, 10 Oct 2020, 08:40 Manprit Singh, wrote: > Dear sir , > > I would like to see suggestions for the solution of the problem given in my > last mail without using any python standard library module .Is it possible > ? > > Regards > Manprit Singh > > On Fri, Oct 9, 2020 at 9:07 PM Manprit Singh > wrote: > > > Dear sir, > > > > Consider a list as given below : > > > > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > > I need to print the values as given below and in same order: > > > > 3 # print 3 only once as there are two occurrence of 3 in the > > beginning in list > > 5 # print 5 only once as there are 3 occurrence of 5 after 3 in the > > list > > 6 # print 6 only once as there are 3 occurrence of 6 after 5 in the > > list > > 5 # print 5 only once as there is single occurrence of 5 after 6 in > > the list > > 9 # print 9 only once as there is single occurrence of 9 after 5 in > > the list > > 3 # print 3 only once as there are 3 occurrence of 3 after 9 in > the > > list > > 5 # print 5 only once as there are 2 occurrence of 5 in the last > > > > I have written the code as given below: > > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > > for i, j in enumerate(lst[:-1]): > > if lst[i+1] != j: > > print(j) > > print(lst[-1]) > > > > which gives the answer as given above > > I feel that a better code can be written for this problem , Need your > > guidance. > > > > Regards > > Manprit singh > > > > > > > _______________________________________________ > 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 Oct 10 06:14:45 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 10 Oct 2020 11:14:45 +0100 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: On 10/10/2020 04:09, Manprit Singh wrote: > I would like to see suggestions for the solution of the problem given in my > last mail without using any python standard library module .Is it possible ? You have had several suggestions, including your own suggestions, which are all valid. However, they are suboptimal since if the standard library offers a better solution we should choose that over writing our own code - it is likely to be faster, more reliable and more consistent with other code. If a standard library solution exists you should always use it unless there are very strong reasons not to. -- 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 Sat Oct 10 06:23:29 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 10 Oct 2020 11:23:29 +0100 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: On 10/10/2020 05:41, navin ray wrote: > provide solution to the same problem using very simple code (I.e without > using any built in functions) so that even a noob like me could understand. It is almost impossible to write code without using the built in functions. They are part of the language without which almost every task becomes impossible. If however, you mean without using the standard library - which is also part of the language, albeit not part of its definition - then that is possible and may help you understand the principle. But you should understand that not using the library would be considered bad practice and could, in an interview situation, be considered a fail. > I am sorry if my suggestions is not relevant to the mailing list. It is completely relevant, and helping people understand basic programming principles is part of what this list is for. IMHO The best solution posted so far that does not use the library is the one by Dennis Beiber (slightly modified for clarity): data = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] previous = None for item in data: if item != previous: print(item) previous = 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 manpritsinghece at gmail.com Sat Oct 10 06:27:16 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 10 Oct 2020 15:57:16 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Thanks a lot sir . Regards Manprit Singh On Sat, Oct 10, 2020 at 3:53 PM Alan Gauld via Tutor wrote: > On 10/10/2020 05:41, navin ray wrote: > > > provide solution to the same problem using very simple code (I.e without > > using any built in functions) so that even a noob like me could > understand. > > It is almost impossible to write code without using the > built in functions. They are part of the language without > which almost every task becomes impossible. > > If however, you mean without using the standard library - which > is also part of the language, albeit not part of its > definition - then that is possible and may help you understand > the principle. But you should understand that not using the > library would be considered bad practice and could, in > an interview situation, be considered a fail. > > > I am sorry if my suggestions is not relevant to the mailing list. > > It is completely relevant, and helping people understand basic > programming principles is part of what this list is for. > > IMHO The best solution posted so far that does not use the > library is the one by Dennis Beiber (slightly modified for > clarity): > > data = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > previous = None > for item in data: > if item != previous: > print(item) > previous = 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 > > > _______________________________________________ > 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 Oct 10 06:26:02 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 10 Oct 2020 11:26:02 +0100 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: On 10/10/2020 06:31, Manprit Singh wrote: > Kindly suggest , if something can be done better: > > def remove_cons(lst): > for i in range(len(lst)-1): > if lst[i] != lst[i+1]: > yield lst[i] > yield lst[-1] Any time you find yourself using indices to access data in a Python for loop you can usually find something better. It's nearly always the wrong thing to do. See Dennis' solution for a much cleaner option that uses Python idioms. -- 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 manpritsinghece at gmail.com Sat Oct 10 06:37:21 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 10 Oct 2020 16:07:21 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Dear Alan Sir, Your words always teach me something . This time too I got a lesson from you. Regards Manprit Singh On Sat, Oct 10, 2020 at 4:00 PM Alan Gauld via Tutor wrote: > On 10/10/2020 06:31, Manprit Singh wrote: > > > Kindly suggest , if something can be done better: > > > > def remove_cons(lst): > > for i in range(len(lst)-1): > > if lst[i] != lst[i+1]: > > yield lst[i] > > yield lst[-1] > > Any time you find yourself using indices to access > data in a Python for loop you can usually find > something better. It's nearly always the wrong thing > to do. > > See Dennis' solution for a much cleaner option > that uses Python idioms. > > -- > 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 alan.gauld at yahoo.co.uk Sat Oct 10 06:39:35 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 10 Oct 2020 11:39:35 +0100 Subject: [Tutor] OT NS charts was: Re: Valid Username Program In-Reply-To: References: <1C2D0A74-DE8A-4313-B245-DAE342CBA45E@hxcore.ol> Message-ID: On 10/10/2020 01:44, Dennis Lee Bieber wrote: > On Sat, 10 Oct 2020 00:33:11 +0100, Alan Gauld via Tutor > declaimed the following: >> anyone use them outside college. I'm curious, has anyone >> actually use NS charts in real world projects? >> > > They were being taught to software engineers at Lockheed Missiles and > Space (now Lockheed-Martin Space Systems) Yes, but were they useful? I once worked on a project where everything was documented using SSADM. But when there was a problem nobody looked to the diagrams they just jumped into the code. The diagrams were a wasteful overhead imposed by management - and often retro-fitted after the code was done! Of all the SSADM diagrams (and there are very many!) there were only about 3 or 4 that people actually used! > given to new-hires) and I suspect Lockheed has probably obtained licenses > for Enterprise Architect these days. I'm sure, or one of the many other capable alternatives! >> I had actually seen them in use and they were effective. >> So has anyone used these and found them effective? >> > Without some software support, they are tedious to maintain, but they > did map better to "structured engineering" (one-in, one-out) than > flow-charts. But were they used? I've seen flow charts (and their significantly better brethren, structure charts and UML activity diagrams) used in projects and the developers actually refer to them before looking at the code(*). But I've also seen many design diagrams used but never referred to! In fact pseudo-code is probably my preferred tool for describing code level design - many programmers think in text so feel comfortable reading pseudo code, but its still an order of magnitude faster than reading production code.. . (*)Back when I managed a maintenance team I always insisted that every project had documentation to a level where we could pinpoint a bug into at least a module, ideally a function, before looking at the code. This was in a scenario where most projects had >1 million lines of code and bugs had to be turned around in 24 hours. We simply didn't have time to trawl though reams of code. If suitable designs didn't exist we took the time to reverse engineer them ourselves! But maybe we should take this discussion to a separate thread?! :-) -- 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 manpritsinghece at gmail.com Sat Oct 10 22:40:08 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 11 Oct 2020 08:10:08 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Dear sir , I feel the use of the object() call is ok , while printing the elements of the list without printing the consecutive duplicates . lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] last = object() for itm in lst: if itm != last: ... print(itm) ... last = itm Here If the List is starting from None then it is more safer to take last = object(). Need to know why it should not be preferred ? Any specific reason ? Regards Manprit Singh On Sat, Oct 10, 2020 at 11:33 PM Dennis Lee Bieber wrote: > On Sat, 10 Oct 2020 11:23:29 +0100, Alan Gauld via Tutor > > declaimed the following: > > >IMHO The best solution posted so far that does not use the > >library is the one by Dennis Beiber (slightly modified for > >clarity): > > > Yeah -- I should have put more separation between the OP's "lst" > and my > use of "last". I used the object() call just to guard against a data set > that started with a None itself -- which was likely being overly cautious > for the given problem description... > > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfraed at ix.netcom.com > http://wlfraed.microdiversity.freeddns.org/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From manpritsinghece at gmail.com Sun Oct 11 02:38:09 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 11 Oct 2020 12:08:09 +0530 Subject: [Tutor] Using break, else with for loop Message-ID: Dear sir , Consider a problem where I have to check if a list contains an odd number. If the list contains an odd number then the program should be capable of displaying "Odd number found in list" and if there is no odd number present in the list, the program must display "List does not contain odd number". Just need to check if my approach to solve this problem is right or not . The solution done by me is given below : l = [2, 4, 6, 5, 8, 3] for i in l: if i % 2 != 0: print("Odd number found in list") break else: print("List does not contain odd number") Regards Manprit Singh From alan.gauld at yahoo.co.uk Sun Oct 11 03:54:55 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 11 Oct 2020 08:54:55 +0100 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: On 11/10/2020 03:40, Manprit Singh wrote: > Here If the List is starting from None then it is more safer to take last = > object(). Need to know why it should not be preferred ? Any specific reason The downside to object() is that it is comparatively expensive. It constructs a new instance of object which consumes more memory than None(a singleton instance) and is slower. That's why the normal sentinel/initializer value in Python is None. But it does run the risk, as in this case, that the data could contain none. So in that scenario object() would be a more reliable option. -- 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 Sun Oct 11 03:58:08 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 11 Oct 2020 08:58:08 +0100 Subject: [Tutor] Using break, else with for loop In-Reply-To: References: Message-ID: On 11/10/2020 07:38, Manprit Singh wrote: > Dear sir , > > Consider a problem where I have to check if a list contains an odd number. > l = [2, 4, 6, 5, 8, 3] > for i in l: > if i % 2 != 0: > print("Odd number found in list") > break > else: > print("List does not contain odd number") That's a valid solution. A slightly shorter version is: if any(n%2 for n in l): print("Odd no found in list") -- 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 manpritsinghece at gmail.com Sun Oct 11 04:01:54 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 11 Oct 2020 13:31:54 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Dear Sir , I have done an experiment in the shell . which clearly proves that size in Byte of None and a new instance of object ( ) are the same . Kindly have a look . import sys >>> sys.getsizeof(None) 16 >>> x = object() >>> sys.getsizeof(x) 16 >>> sys.getsizeof(x) 16 So the only downside is , it is slow ... But slowness really matters in this particular case ? Regards Manprit singh On Sun, Oct 11, 2020 at 1:25 PM Alan Gauld via Tutor wrote: > On 11/10/2020 03:40, Manprit Singh wrote: > > > Here If the List is starting from None then it is more safer to take > last = > > object(). Need to know why it should not be preferred ? Any specific > reason > The downside to object() is that it is comparatively expensive. It > constructs a new instance of object which consumes more memory than > None(a singleton instance) and is slower. That's why the normal > sentinel/initializer value in Python is None. > > But it does run the risk, as in this case, that the data could > contain none. So in that scenario object() would be a more reliable > option. > > -- > 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 alan.gauld at yahoo.co.uk Sun Oct 11 04:02:03 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 11 Oct 2020 09:02:03 +0100 Subject: [Tutor] Using break, else with for loop In-Reply-To: References: Message-ID: On 11/10/2020 08:58, Alan Gauld via Tutor wrote: > That's a valid solution. > A slightly shorter version is: > > if any(n%2 for n in l): > print("Odd no found in list") I meant to add, that this has the advantage of explicitly expressing the intent of the code in the function. -- 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 manpritsinghece at gmail.com Sun Oct 11 04:07:57 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 11 Oct 2020 13:37:57 +0530 Subject: [Tutor] Using break, else with for loop In-Reply-To: References: Message-ID: Dear sir , The point I want to raise here is , in my program I am using break because I want my program 's for loop to break at a point where an odd number is found . But in your code you are checking the entire list . Need your comments Regards Manprit Singh On Sun, Oct 11, 2020 at 1:30 PM Alan Gauld via Tutor wrote: > On 11/10/2020 07:38, Manprit Singh wrote: > > Dear sir , > > > > Consider a problem where I have to check if a list contains an odd > number. > > > l = [2, 4, 6, 5, 8, 3] > > for i in l: > > if i % 2 != 0: > > print("Odd number found in list") > > break > > else: > > print("List does not contain odd number") > > That's a valid solution. > A slightly shorter version is: > > if any(n%2 for n in l): > print("Odd no found in list") > > > > -- > 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 alan.gauld at yahoo.co.uk Sun Oct 11 04:13:13 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 11 Oct 2020 09:13:13 +0100 Subject: [Tutor] Using break, else with for loop In-Reply-To: References: Message-ID: On 11/10/2020 09:07, Manprit Singh wrote: > Dear sir , > > The point I want to raise here is , in my program I am using break because > I want my program 's for loop to break at a point where an odd number is > found . > But in your code you are checking the entire list . > Need your comments I'm not sure that's true since I would hope that any() is optimised to break when it encounters any true value. Also since any() is a built in function it is written in C so should be faster than pure Python(assuming it does break). Finally, as I've repeatedly said, readability is one of the most important features of good code. any() exactly expresses the purpose of the code which improves maintainability -- 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 Sun Oct 11 04:18:15 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 11 Oct 2020 09:18:15 +0100 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: On 11/10/2020 09:01, Manprit Singh wrote: > So the only downside is , it is slow ... But slowness really matters in > this particular case ? It's slow and uses more memory. Neither matters in this case(although might in others). But the other point is that it is less idiomatic than None. None is the most commonly used value in a scenario like this. That makes it more readable than object() where the reader a has to stop and think why that value has been chosen. Readability is important, more important than performance in most cases, but less important than reliability! So, if you are sure the list will not contain None, use None. If there is any possibility of the list containing None use object() -- 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 manpritsinghece at gmail.com Sun Oct 11 04:35:24 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 11 Oct 2020 14:05:24 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Dear sir , Agreed Regards Manprit Singh On Sun, Oct 11, 2020 at 1:48 PM Alan Gauld via Tutor wrote: > On 11/10/2020 09:01, Manprit Singh wrote: > > > So the only downside is , it is slow ... But slowness really matters in > > this particular case ? > > It's slow and uses more memory. > Neither matters in this case(although might in others). > But the other point is that it is less idiomatic than None. > > None is the most commonly used value in a scenario like this. > That makes it more readable than object() where the reader a > has to stop and think why that value has been chosen. > Readability is important, more important than performance > in most cases, but less important than reliability! > > So, if you are sure the list will not contain None, use None. > If there is any possibility of the list containing None > use object() > > -- > 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 manpritsinghece at gmail.com Sun Oct 11 04:44:21 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 11 Oct 2020 14:14:21 +0530 Subject: [Tutor] update a list Message-ID: Dear sir , Consider a problem where I have to update a list , at even places with increment of 1 and at odd places with increment of 2 . Just need to check if this can be done in a better way. My solution is given below: l = [2, 3, 5, 7, 6, 4] for i, j in enumerate(l): if i % 2 == 0: l[i] = j+1 else: l[i] = j+2 the updated list is [3, 5, 6, 9, 7, 6] Regards Manprit Singh From PyTutor at DancesWithMice.info Sun Oct 11 06:18:14 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sun, 11 Oct 2020 23:18:14 +1300 Subject: [Tutor] update a list In-Reply-To: References: Message-ID: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> On 11/10/2020 21:44, Manprit Singh wrote: > Dear sir , > > Consider a problem where I have to update a list , at even places with > increment of 1 and at odd places with increment of 2 . Just need to check > if this can be done in a better way. My solution is given below: > > l = [2, 3, 5, 7, 6, 4] > for i, j in enumerate(l): > if i % 2 == 0: > l[i] = j+1 > else: > l[i] = j+2 > > the updated list is > > [3, 5, 6, 9, 7, 6] From where are you finding these problems, or what do you intend to do with the results? I am not in-favor of updating lists/list-elements in-place because altering iterables inside their iteration can cause big problems in certain other scenarios! Accordingly, I prefer to create a new list (and if necessary, delete the old one, afterwards). Remember that you can slice a sequence. Thus, a faster solution is: >>> l = [2, 3, 5, 7, 6, 4] >>> new_l = list() >>> for index in range( 0, len( l ), 2 ): ... new_l.append( l[ index ] + 1 ) ... new_l.append( l[ index + 1 ] + 2 ) ... >>> new_l [3, 5, 6, 9, 7, 6] >>> If you insist upon updating-in-place, replace the append()s with: l[ index ] += 1 Performance comparison: No integer-division/remainder comparison, no if, and with half(ish) the number of loops! -- Regards =dn From manpritsinghece at gmail.com Sun Oct 11 07:10:43 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 11 Oct 2020 16:40:43 +0530 Subject: [Tutor] update a list In-Reply-To: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> Message-ID: Thanks a lot sir. Regards Manprit Singh On Sun, Oct 11, 2020 at 3:48 PM dn via Tutor wrote: > On 11/10/2020 21:44, Manprit Singh wrote: > > Dear sir , > > > > Consider a problem where I have to update a list , at even places with > > increment of 1 and at odd places with increment of 2 . Just need to check > > if this can be done in a better way. My solution is given below: > > > > l = [2, 3, 5, 7, 6, 4] > > for i, j in enumerate(l): > > if i % 2 == 0: > > l[i] = j+1 > > else: > > l[i] = j+2 > > > > the updated list is > > > > [3, 5, 6, 9, 7, 6] > > > From where are you finding these problems, or what do you intend to do > with the results? > > > I am not in-favor of updating lists/list-elements in-place because > altering iterables inside their iteration can cause big problems in > certain other scenarios! > > Accordingly, I prefer to create a new list (and if necessary, delete the > old one, afterwards). > > Remember that you can slice a sequence. Thus, a faster solution is: > > >>> l = [2, 3, 5, 7, 6, 4] > >>> new_l = list() > >>> for index in range( 0, len( l ), 2 ): > ... new_l.append( l[ index ] + 1 ) > ... new_l.append( l[ index + 1 ] + 2 ) > ... > >>> new_l > [3, 5, 6, 9, 7, 6] > >>> > > If you insist upon updating-in-place, replace the append()s with: > > l[ index ] += 1 > > > Performance comparison: > No integer-division/remainder comparison, no if, and with half(ish) the > number of loops! > -- > Regards =dn > _______________________________________________ > 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 Oct 11 07:13:36 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 11 Oct 2020 12:13:36 +0100 Subject: [Tutor] update a list In-Reply-To: References: Message-ID: On 11/10/2020 09:44, Manprit Singh wrote: > Consider a problem where I have to update a list , at even places with > increment of 1 and at odd places with increment of 2 . Just need to check > if this can be done in a better way. My solution is given below: > > l = [2, 3, 5, 7, 6, 4] > for i, j in enumerate(l): > if i % 2 == 0: > l[i] = j+1 > else: > l[i] = j+2 > > the updated list is > > [3, 5, 6, 9, 7, 6] Sorry, I don't understand how you got that output. I'd expect all output numbers to be odd, that is: [3,5,7,9,7,5] I think I must be missing some aspect of your problem? If it's just a typo then I'd probably prefer to use map() newlist = map(lambda n: n+1 if n%2 else n+2, oldlist) or a list comprehension newlist = [n+1 if n%2 else n+2 for n in oldlist] These both build a new list from the old list so might not be appropriate for a very large list in which case your solution is a valid one. -- 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 Sun Oct 11 07:17:31 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 11 Oct 2020 12:17:31 +0100 Subject: [Tutor] update a list In-Reply-To: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> Message-ID: On 11/10/2020 11:18, dn via Tutor wrote: > On 11/10/2020 21:44, Manprit Singh wrote: >> Dear sir , >> >> Consider a problem where I have to update a list , at even places with >> increment of 1 and at odd places with increment of 2 . Just need to check >> if this can be done in a better way. My solution is given below: > Remember that you can slice a sequence. Thus, a faster solution is: > > >>> l = [2, 3, 5, 7, 6, 4] > >>> new_l = list() > >>> for index in range( 0, len( l ), 2 ): > ... new_l.append( l[ index ] + 1 ) > ... new_l.append( l[ index + 1 ] + 2 ) > ... > >>> new_l > [3, 5, 6, 9, 7, 6] Ah! Now I understand. I read "at even places" to mean "places where the data is even" rather than places where the index is even! -- 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 PyTutor at DancesWithMice.info Sun Oct 11 07:23:19 2020 From: PyTutor at DancesWithMice.info (dn) Date: Mon, 12 Oct 2020 00:23:19 +1300 Subject: [Tutor] update a list In-Reply-To: References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> Message-ID: <93ac9a9b-0de2-652a-4404-3e68bbefa4e3@DancesWithMice.info> On 12/10/2020 00:10, Manprit Singh wrote: > Thanks a lot sir. I answered your question. Did you answer mine? (see previous contribution) -- Regards =dn From manpritsinghece at gmail.com Sun Oct 11 07:33:52 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 11 Oct 2020 17:03:52 +0530 Subject: [Tutor] update a list In-Reply-To: <93ac9a9b-0de2-652a-4404-3e68bbefa4e3@DancesWithMice.info> References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> <93ac9a9b-0de2-652a-4404-3e68bbefa4e3@DancesWithMice.info> Message-ID: Dear Sir , Let me tell you, i am still in learning stage , i started learning python some 7-8 months back, basically an electronics engineer and have experience of around 10 years the field of electronics and found python to be very clean and clear language, also it has a good ecosystem of scientific works, like numpy pandas and scipy, i feel i can carry my engg. calculations very well in python . I beg apology if something has gone wrong with me, so as a curious learner I put questions in the mailing list. As far as python list is concerned i know it is not advised to update a list, it is always good to create a new list. instead See people like you are helping me a lot in learning Python. Thank you for your support. Regards Manprit Singh On Sun, Oct 11, 2020 at 4:53 PM dn via Tutor wrote: > On 12/10/2020 00:10, Manprit Singh wrote: > > Thanks a lot sir. > > > I answered your question. > Did you answer mine? > (see previous contribution) > -- > Regards =dn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alexkleider at protonmail.com Sun Oct 11 12:21:18 2020 From: alexkleider at protonmail.com (alexkleider) Date: Sun, 11 Oct 2020 16:21:18 +0000 Subject: [Tutor] update a list In-Reply-To: References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> Message-ID: ??????? Original Message ??????? On Sunday, October 11, 2020 4:17 AM, Alan Gauld via Tutor wrote: > On 11/10/2020 11:18, dn via Tutor wrote: > > > On 11/10/2020 21:44, Manprit Singh wrote: > > > > > Dear sir , > > > Consider a problem where I have to update a list , at even places with > > > increment of 1 and at odd places with increment of 2 . Just need to check > > > if this can be done in a better way. My solution is given below: > > > Remember that you can slice a sequence. Thus, a faster solution is: > > > > > > > l = [2, 3, 5, 7, 6, 4] > > > > > new_l = list() > > > > > for index in range( 0, len( l ), 2 ): > > > > > ... new_l.append( l[ index ] + 1 ) > > > > > ... new_l.append( l[ index + 1 ] + 2 ) > > > > > ... > > > > > > > > new_l > > > > > [3, 5, 6, 9, 7, 6] The above solution breaks down if the length of the list happens to be odd: Python 3.7.3 (default, Jul 25 2020, 13:03:44) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> m = [2, 3, 5, 7, 6, 4, 9] >>> new = list() >>> for index in range(0, len(m), 2): ... new_m.append(m[index] + 1) ... new_m.append(m[index + 1] + 1) ... Traceback (most recent call last): File "", line 3, in IndexError: list index out of range >>> From manpritsinghece at gmail.com Sun Oct 11 13:07:39 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 11 Oct 2020 22:37:39 +0530 Subject: [Tutor] optional else with while Message-ID: Dear sir , Consider a problem where I have to write a program that accepts a user input (integer) and find its largest factor . If the number is a prime number the program must display " It is a prime number". I have written a program that is not valid for user input of 0 and 1 . The basic purpose is to understand how an optional else clause works with while loop . n = int(input("Enter any number")) initial = n//2 while initial > 1: if n % initial == 0: print("Greatest factor of",n,"is",initial) break initial -= 1 else: print("It is a prime number") Need your comments Regards Manprit Singh From alan.gauld at yahoo.co.uk Sun Oct 11 14:11:17 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 11 Oct 2020 19:11:17 +0100 Subject: [Tutor] optional else with while In-Reply-To: References: Message-ID: On 11/10/2020 18:07, Manprit Singh wrote: > to understand how an optional else clause works with while loop . > > n = int(input("Enter any number")) > initial = n//2 > while initial > 1: > if n % initial == 0: > print("Greatest factor of",n,"is",initial) > break > initial -= 1 > else: > print("It is a prime number") I'd say that's a pretty fair demonstration of a while/else. Mostly you don't need it since the code will just continue after the loop, but in cases like this where you want to do something only if the while exits "normally" (ie no breaks) the else clause is the right choice. -- 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 breamoreboy at gmail.com Sun Oct 11 14:34:58 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 11 Oct 2020 19:34:58 +0100 Subject: [Tutor] update a list In-Reply-To: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> Message-ID: On 11/10/2020 11:18, dn via Tutor wrote: > On 11/10/2020 21:44, Manprit Singh wrote: >> Dear sir , >> >> Consider a problem where I have to update a list , at even places with >> increment of 1 and at odd places with increment of 2 . Just need to check >> if this can be done in a better way. My solution is given below: >> >> l = [2, 3, 5, 7, 6, 4] >> for i, j in enumerate(l): >> ???? if i % 2 == 0: >> ???????? l[i] = j+1 >> ???? else: >> ???????? l[i] = j+2 >> >> the updated list is >> >> [3, 5, 6, 9, 7, 6] > > > From where are you finding these problems, or what do you intend to do > with the results? > > > I am not in-favor of updating lists/list-elements in-place because > altering iterables inside their iteration can cause big problems in > certain other scenarios! > > Accordingly, I prefer to create a new list (and if necessary, delete the > old one, afterwards). > > Remember that you can slice a sequence. Thus, a faster solution is: > > >>> l = [2, 3, 5, 7, 6, 4] > >>> new_l = list() > >>> for index in range( 0, len( l ), 2 ): > ...???? new_l.append( l[ index ] + 1 ) > ...???? new_l.append( l[ index + 1 ] + 2 ) Where is the list slicing above, all I can see is single items in the old list being used? Using 'range' and 'len' in combination is usually wrong, 'enumerate' is the preferred solution. It's been pointed out elsewhere that your solution doesn't work for an odd numbered length of the initial list, although that has been wrongly attributed to Alan Gould. > ... > >>> new_l > [3, 5, 6, 9, 7, 6] > >>> > > If you insist upon updating-in-place, replace the append()s with: > > l[ index ] += 1 > > > Performance comparison: > No integer-division/remainder comparison, no if, and with half(ish) the > number of loops! No actual measurements to show that this is the case. All I can say is that in 20 years of using Python my gut instinct for performance has never once been correct. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From PyTutor at DancesWithMice.info Sun Oct 11 16:08:53 2020 From: PyTutor at DancesWithMice.info (dn) Date: Mon, 12 Oct 2020 09:08:53 +1300 Subject: [Tutor] update a list In-Reply-To: References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> <93ac9a9b-0de2-652a-4404-3e68bbefa4e3@DancesWithMice.info> Message-ID: <1d6559b5-35a6-3072-9511-d05a8ad48a50@DancesWithMice.info> > From where are you finding these problems, or what do you intend to do with the results? On 12/10/2020 00:33, Manprit Singh wrote: > Dear Sir , > > Let me tell you, i am still in learning stage , i started learning python > some 7-8 months back, basically an electronics engineer and have experience > of around 10 years the field of electronics and found python to be very > clean and clear language, also it has a good ecosystem of scientific works, > like numpy pandas and scipy, i feel i can carry my engg. calculations very > well in python . > > I beg apology if something has gone wrong with me, so as a curious learner > I put questions in the mailing list. As far as python list is concerned i > know it is not advised to update a list, it is always good to create a new > list. instead See people like you are helping me a lot in learning Python. > > Thank you for your support. You will find some explanation for the question in my follow-up to @Alex. After 'neglecting' the Python list for some weeks?months, working 16x7 (+) on an 'urgent community-health problem' - which is probably also affecting your locality (stay safe!), I've come 'back' to see a number of similar, fairly academic, questions - and wondered why? Perhaps a series of student-assignments you face? Perhaps you're writing a book? I was intrigued...not that you were doing anything "wrong"! (it's not my place to judge you/your motivations!) Like you, I came to Python from 'elsewhere', and have found it very accessible and yet powerful. So, welcome to the gang! Rather than finding these vague problems to solve - which I have characterised (elsewhere) as somewhat 'academic'; why don't you instead choose a problem in your own field, and in solving that, learn/teach-yourself enough Python, and python technique, to achieve? You will still find questions to ask (yourself, the list, ...), and be satisfying some engineering/electronics aim, at the same time! Some people feel that they have to 'get good' in a programming language before 'starting work' with it. This is not the Python-way - happily enough! Python has been, as we have both discovered, designed well. Accordingly, one can simply 'start work'... There is a very famous quote in ComSc (Computer Science) circles that has been around since the days of mainframe computers and batch-processing: "be prepared to throw the first one away" (Fred Brooks, "The Mythical Man-Month"). The Python coder's version might be: 'be prepared to refactor', ie improve the quality of the code/solution, as you develop, as you learn, as you implement, as you clarify the specification, as you realise the implications of your coding choices... As far as learning goes, we are ("should" - IMHO) all, always learning. That's why people like myself, and @Alan (ListAdmin) enjoy being 'here' - there are questions which remind us of 'stuff' we haven't ever used or haven't used in a long time, or cause us to look at problems in a different way to our own view, and generally stretch our minds/imaginations. Thanks! PS some do criticise conversations 'here' with top-posted responses. Conversations normally proceed with a question first, and the answer following. (see how I added my original question of you, at the top of this message, then there's your response, and below the latest addition) -- Regards =dn From PyTutor at DancesWithMice.info Sun Oct 11 16:28:58 2020 From: PyTutor at DancesWithMice.info (dn) Date: Mon, 12 Oct 2020 09:28:58 +1300 Subject: [Tutor] update a list In-Reply-To: References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> Message-ID: On 12/10/2020 05:21, alexkleider via Tutor wrote: > ??????? Original Message ??????? > On Sunday, October 11, 2020 4:17 AM, Alan Gauld via Tutor wrote: > >> On 11/10/2020 11:18, dn via Tutor wrote: >> >>> On 11/10/2020 21:44, Manprit Singh wrote: >>> >>>> Dear sir , >>>> Consider a problem where I have to update a list , at even places with >>>> increment of 1 and at odd places with increment of 2 . Just need to check >>>> if this can be done in a better way. My solution is given below: >> >>> Remember that you can slice a sequence. Thus, a faster solution is: >>> >>>>>> l = [2, 3, 5, 7, 6, 4] >>>>>> new_l = list() >>>>>> for index in range( 0, len( l ), 2 ): >>>>>> ... new_l.append( l[ index ] + 1 ) >>>>>> ... new_l.append( l[ index + 1 ] + 2 ) >>>>>> ... >>>> >>>>>> new_l >>>>>> [3, 5, 6, 9, 7, 6] > > The above solution breaks down if the length of the list happens to be odd: > Python 3.7.3 (default, Jul 25 2020, 13:03:44) > [GCC 8.3.0] on linux > Type "help", "copyright", "credits" or "license" for more information. >>>> m = [2, 3, 5, 7, 6, 4, 9] >>>> new = list() >>>> for index in range(0, len(m), 2): > ... new_m.append(m[index] + 1) > ... new_m.append(m[index + 1] + 1) > ... > Traceback (most recent call last): > File "", line 3, in > IndexError: list index out of range That's absolutely true, (and continuing-on from my additional question of the OP) illustrates the tyranny of such abstract and artificial problems! - and why I won't use them as examples/assignments in my own training materials! That said, and some of my objection, if there are to be 'rules' ("specifications") then they must be stated up-front. If they are 'hidden', then the error is not ours, as coders! (but we would not 'escape' responsibility for such). In academe there are some who choose to set 'trick questions', but this seems to lead to a 'them and us' relationship, rather than a team approach. To determine if the assumption that index+1 could exist (that the list is always of zero or even length is "wrong"), requires access to the user/client, or to observations in 'the real world'. On the one hand, it is a reasonable assumption because the problem appears to assume pairs. On the other hand, 'we are not told this' - again, an assumption: that we would be told 'everything' for this version of 'true'. Anyone who has dealt with user-specifications knows that such assumptions are dangerous (both ways)! At this point, we can widen the discussion into team management, SCRUM, user involvement in dev.teams, etc, etc - but this is Python list, so I shall (attempt to) rein-in my enthusiasm! Is it our responsibility, as coders, to notice these assumptions/risks, and to bring them to the client's attention in seeking clarification? Does 'academic purity' allow such, ie how appropriate are school-room rules, such as 'use your own intelligence/initiative', 'don't copy', 'don't talk to others'? If I don't know the target, how can I meet the requirements (except by luck). If I don't know the rules/assumptions, how can I 'defend' my decisions? If we (client and coder) aren't on the same course, is unhappiness inevitable? Why do I avoid such? Because my objective is to prepare trainees to work in 'the real world'. Thus, imagine a situation where I had spent weeks/months preparing some solution, all by myself and without 'bothering' anyone else. Then you/my boss/client come-along and say "but...". Both feeling disappointment, an highly-charged, even emotional, argument might ensue. At the very least, someone has to pay for my time, and thus lose/waste money. Surely that's something to avoid? Now, to evoke a (sardonic) chuckle: re-read the above and spot the inherent assumption... Back to Python: In 'the real world', we do occasionally have need to take data 'two by two'/in-pairs - not often, but it does occur. As an example, consider PyGame which has functions to place visual objects on its "canvas" (the screen). The four arguments are: - an x,y pair, ie Cartesian Coordinates, and - a w,h pair representing the rectangular dimensions of the object (width and height). In this scenario, whilst we could consider the data as a sequence of four, or two sequences of two; if there are any geometric calculations to be performed, it is (in my experience) easier to code the first pair as an object which can, at different times, either be processed as a unit or split into x,y-scalars, as required within the application, ie Cartesian Coordinates. Similarly the second pair could be treated as a Vector, according to the full specification of needs. Accordingly, the rather academic approach, extracting pairs from a generic list structure, as outlined in the original post, doesn't see the light of day - it is not possible to have 2-D dimensions without a 'pair', nor 2-D Cartesian Coordinates. However, and to address the (quite reasonable) criticism: to deal with an 'incomplete' list of pairs, in a thoroughly 'pythonic' fashion, wrap access to the second of each 'pair', with try...except. NB Such a concern is inherently-avoided in the OP's original solution! -- Regards =dn From PyTutor at DancesWithMice.info Sun Oct 11 17:20:06 2020 From: PyTutor at DancesWithMice.info (dn) Date: Mon, 12 Oct 2020 10:20:06 +1300 Subject: [Tutor] update a list In-Reply-To: References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> Message-ID: <540e0679-c698-12d5-5322-93beb422a5ce@DancesWithMice.info> On 12/10/2020 07:34, Mark Lawrence wrote: > On 11/10/2020 11:18, dn via Tutor wrote: >> On 11/10/2020 21:44, Manprit Singh wrote: ... >> Remember that you can slice a sequence. Thus, a faster solution is: >> >> ?>>> l = [2, 3, 5, 7, 6, 4] >> ?>>> new_l = list() >> ?>>> for index in range( 0, len( l ), 2 ): >> ...???? new_l.append( l[ index ] + 1 ) >> ...???? new_l.append( l[ index + 1 ] + 2 ) > > Where is the list slicing above, all I can see is single items in the > old list being used?? Using 'range' and 'len' in combination is usually > wrong, 'enumerate' is the preferred solution.? It's been pointed out > elsewhere that your solution doesn't work for an odd numbered length of > the initial list, although that has been wrongly attributed to Alan Gould. Oh goodie, more reason for @Alan to want to beat me over the head... (joking) Yes, my email-client has a ReplyToList option, but the challenge is remembering to use it and not (simple) Reply or ReplyAll! Perhaps I have used the term a little loosely, isn't this "slicing": ...range( 0, len( l ), 2 ) by intent, if not by definition - given that the purpose is to generate every second index? Presumably, if slicing is [ i, j, k ] then precise definitions describe indexing, ie using only the [ i ]/first of the three, as not-slicing. Are we slicing definitions? I completely agree with that thesis. My opinion is that the Python for-each is one of the language's greatest virtues - the for-index (tradition) of other languages is one of the largest, continual, sources of errors in code. It is also a popular evidence of someone applying another language's 'solution' to Python. To say "doesn't work" requires an assumption (either way), as discussed elsewhere. >> ... >> ?>>> new_l >> [3, 5, 6, 9, 7, 6] >> ?>>> >> >> If you insist upon updating-in-place, replace the append()s with: >> >> l[ index ] += 1 >> >> >> Performance comparison: >> No integer-division/remainder comparison, no if, and with half(ish) >> the number of loops! > > No actual measurements to show that this is the case.? All I can say is > that in 20 years of using Python my gut instinct for performance has > never once been correct. I've experienced such upsetting mysteries too, but "cyclomatic complexity" does offer some reason - particularly in such a simple loop. Ultimately you are correct - there is no substitute for timing comparisons. However, even that doesn't reveal the 'truth', because differences between hardware, OpSys, and Python interpreter will all impact the result. Such measurement can only be relevant on the target-system, and against the (full) client specification. I often deliver statistical/numerical analyses which chunder-on for hours. It upsets the client if we can't at least estimate a finish-time; and even more-so if we reckon one period and he, on his platform, experiences some other/longer! Tell you what: you do one, and I'll measure the other... -- Regards =dn From breamoreboy at gmail.com Sun Oct 11 14:47:42 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 11 Oct 2020 19:47:42 +0100 Subject: [Tutor] optional else with while In-Reply-To: <93h6of5q7gegqugd22absnn9dm0l62tar8@4ax.com> References: <93h6of5q7gegqugd22absnn9dm0l62tar8@4ax.com> Message-ID: On 11/10/2020 19:04, Dennis Lee Bieber wrote: > > An efficient prime generator may be rather advanced concepts (I have to > confess that while I've seen "yield" used in generator functions, I've > never had a call to write that type of function). > I highly recommend this talk https://www.youtube.com/watch?v=EnSu9hHGq5o from Ned Batchelder at PyCon 2013 for anybody interested in such things. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at gmail.com Sun Oct 11 17:42:11 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 11 Oct 2020 22:42:11 +0100 Subject: [Tutor] update a list In-Reply-To: <540e0679-c698-12d5-5322-93beb422a5ce@DancesWithMice.info> References: <86e65863-6364-8eb1-56a2-417b299bc8e2@DancesWithMice.info> <540e0679-c698-12d5-5322-93beb422a5ce@DancesWithMice.info> Message-ID: On 11/10/2020 22:20, dn via Tutor wrote: [snipped to hell] > > Perhaps I have used the term a little loosely, isn't this "slicing": > > ...range( 0, len( l ), 2 ) > > by intent, if not by definition - given that the purpose is to generate > every second index? Presumably, if slicing is [ i, j, k ] then precise > definitions describe indexing, ie using only the [ i ]/first of the > three, as not-slicing. Are we slicing definitions? I've no idea at all how you manage to bring 'range' and 'len' into a discussion about slicing so please explain. > > To say "doesn't work" requires an assumption (either way), as discussed > elsewhere. That's complete nonsense as nothing in the original post says anything about the input other than it is a list. > > Tell you what: you do one, and I'll measure the other... I'm not wasting my time on something that does not work. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From PyTutor at DancesWithMice.info Tue Oct 13 18:22:06 2020 From: PyTutor at DancesWithMice.info (dn) Date: Wed, 14 Oct 2020 11:22:06 +1300 Subject: [Tutor] Helping new users install Python on MS-Win Message-ID: Questions are frequently asked about how to use newly-installed Python under MS-Windows. Might "Installing Python on Windows 10" (https://www.youtube.com/watch?v=i-MuSAwgwCU) an IDG TECHTalk video, go some way to relieving such perennial problems? (I can't judge. I don't using MS-Windows) NB it is already slightly behind our current version/web site (video loaded Mar 2020), and there's 'wiggle-room' in the narrator's option-choices/recommendations... -- Regards, =dn From PythonList at DancesWithMice.info Tue Oct 13 18:05:41 2020 From: PythonList at DancesWithMice.info (dn) Date: Wed, 14 Oct 2020 11:05:41 +1300 Subject: [Tutor] Helping new users install Python on MS-Win Message-ID: <6c200b68-0dab-c834-04af-59df27314708@etelligence.info> Questions are frequently asked about how to use newly-installed Python under MS-Windows. Might "Installing Python on Windows 10" (https://www.youtube.com/watch?v=i-MuSAwgwCU) an IDG TECHTalk video, go some way to relieving such perennial problems? (I can't judge. I don't using MS-Windows) NB it is already slightly behind our current version/web site (video loaded Mar 2020), and there's 'wiggle-room' in the narrator's option-choices/recommendations... -- Regards, =dn From phillor9 at gmail.com Tue Oct 13 19:28:46 2020 From: phillor9 at gmail.com (Phil) Date: Wed, 14 Oct 2020 09:28:46 +1000 Subject: [Tutor] Running python files Message-ID: This seemingly simple problem has me scratching my head. How do I run a python file from a directory other than the directory that the python file is in? It's a little more complex than my question implies. For example, "python3 ~/somedirectory/somefile.py" runs without a problem. However if somefile.py requires resources such as .png files then somefile.py won't run because those resources cannot be found. These resources are also stored in /somedirectory. The same somefile.py does run if stated from somedirectory. Adding somedirectory to my user path didn't help and I've experimented with Python_Path but that's not the answer either. I'm trying to run somefile.py from the system menu. -- Regards, Phil From mats at wichmann.us Tue Oct 13 19:59:12 2020 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 13 Oct 2020 17:59:12 -0600 Subject: [Tutor] Running python files In-Reply-To: References: Message-ID: <01728ce1-d443-3323-d588-83e93cc40f10@wichmann.us> On 10/13/20 5:28 PM, Phil wrote: > This seemingly simple problem has me scratching my head. How do I run a > python file from a directory other than the directory that the python > file is in? It's a little more complex than my question implies. > > For example, "python3 ~/somedirectory/somefile.py" runs without a > problem. However if somefile.py requires resources such as .png files > then somefile.py won't run because those resources cannot be found. > These resources are also stored in /somedirectory. The same somefile.py > does run if stated from somedirectory. > > Adding somedirectory to my user path didn't help and I've experimented > with Python_Path but that's not the answer either. > > I'm trying to run somefile.py from the system menu. > It's a question of context. Which so many things in computing are :) A python process has a concept of a current working directory, that's the one that is used when looking up relative paths. "foo.png" is a relative path - it's expected to be relative to the current directory. The directory you start from is current, not the directory of the script. When you put something in a menu, or in a cron job, those don't have the same context as the directory you might be working in when you type a shell command, so there's a good bit to think about here. There's a way to find the script's directory (well, maybe not just one way)... try this: put a script somewhere that contains import sys print(sys.path[0]) and run that script from some other place. Does this give you some ideas? From alan.gauld at yahoo.co.uk Tue Oct 13 20:16:46 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 14 Oct 2020 01:16:46 +0100 Subject: [Tutor] Running python files In-Reply-To: References: Message-ID: On 14/10/2020 00:28, Phil wrote: > This seemingly simple problem has me scratching my head. How do I run a > python file from a directory other than the directory that the python > file is in? There are several ways to do this. 1) Use a hard coded full path. 2) Put the full path in a config variable in a config file 3) Get the path from an environment variable (and have a default if not set) 4) change the current working directory to the folder your file is in (using the os.chdir() function) If the location of the file is variable then you might want to bring up a dialog to fetch it fom the user, there are various options from the curses based dialog module to easy-gui and the tkinter simpledialogs. Or just a simple input() call. You can also ask the program file where it is located if the data files are relative to that. A config file is probably the best option, but then you have to find the config file! :-) -- 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 Richard at Damon-Family.org Tue Oct 13 21:19:29 2020 From: Richard at Damon-Family.org (Richard Damon) Date: Tue, 13 Oct 2020 21:19:29 -0400 Subject: [Tutor] Running python files In-Reply-To: References: Message-ID: On 10/13/20 8:16 PM, Alan Gauld via Tutor wrote: > On 14/10/2020 00:28, Phil wrote: >> This seemingly simple problem has me scratching my head. How do I run a >> python file from a directory other than the directory that the python >> file is in? > There are several ways to do this. > 1) Use a hard coded full path. > 2) Put the full path in a config variable in a config file > 3) Get the path from an environment variable (and have a default if not set) > 4) change the current working directory to the folder your file is in > (using the os.chdir() function) > > If the location of the file is variable then you might want to bring up > a dialog to fetch it fom the user, there are various options from the > curses based dialog module to easy-gui and the tkinter simpledialogs. > Or just a simple input() call. > > You can also ask the program file where it is located if the > data files are relative to that. > > A config file is probably the best option, but then you have > to find the config file! :-) > The way I find the directory the script is running from is: import os os.path.dirname(os.path.realpath(__file__)) Note, __file__ is a special name that has the name of the current script, with path. -- Richard Damon From alexkleider at protonmail.com Wed Oct 14 00:34:25 2020 From: alexkleider at protonmail.com (alexkleider) Date: Wed, 14 Oct 2020 04:34:25 +0000 Subject: [Tutor] Running python files In-Reply-To: References: Message-ID: ??????? Original Message ??????? On Tuesday, October 13, 2020 6:19 PM, Richard Damon wrote: > On 10/13/20 8:16 PM, Alan Gauld via Tutor wrote: > > > On 14/10/2020 00:28, Phil wrote: > > > > > This seemingly simple problem has me scratching my head. How do I run a > > > python file from a directory other than the directory that the python > > > file is in? > > > There are several ways to do this. > > > > 1. Use a hard coded full path. > > 2. Put the full path in a config variable in a config file > > 3. Get the path from an environment variable (and have a default if not set) > > 4. change the current working directory to the folder your file is in > > (using the os.chdir() function) > > > > > > If the location of the file is variable then you might want to bring up > > a dialog to fetch it fom the user, there are various options from the > > curses based dialog module to easy-gui and the tkinter simpledialogs. > > Or just a simple input() call. > > You can also ask the program file where it is located if the > > data files are relative to that. > > A config file is probably the best option, but then you have > > to find the config file! :-) > > The way I find the directory the script is running from is: > > import os > > os.path.dirname(os.path.realpath(file)) > > Note, file is a special name that has the name of the current > script, with path. I think I've understood the OP's problem and the solutions offered and have come up with the following (trivial) example that I believe provides a way of solving the problem. No matter from where the script (to_try.py) is run, as long as helpers.py and txt.txt are in the same directory as to_try.py, it all seems to work. #!/usr/bin/env python3 # File: to_try.py import os import helpers # The way I find the directory the script is running from is: print(os.path.dirname(os.path.realpath(__file__))) dirname = os.path.dirname(os.path.realpath(__file__)) file_I_want = 'txt.txt' file_name = os.path.join(dirname, file_I_want) # Note, __file__ is a special name that has the name of the # current script, with path. with open(file_name, 'r') as instream: data = instream.read() print(data) Hope this helps to solve the OP's dilemma. Comments, critiques, ... welcome From f.hochwart at gmx.de Wed Oct 14 09:45:40 2020 From: f.hochwart at gmx.de (f.hochwart at gmx.de) Date: Wed, 14 Oct 2020 15:45:40 +0200 Subject: [Tutor] np.array operation memoryerror Message-ID: <001501d6a230$4e4e69e0$eaeb3da0$@gmx.de> Hello, for my masterthesis I have to compute e.g. np.arrays with following settings: MemoryError: Unable to allocate 7.15 TiB for an array with shape (991600, 991600) and data type float64 A = sparse.bsr_matrix(C1 * (sparse.bsr_matrix(np.eye(dA, k = dR)) -2 * sparse.bsr_matrix(np.eye(dA)) + sparse.bsr_matrix(np.eye(dA, k = -dR)))) Even if I use sparse function or np.float32 the memoryerror still appears. I searched in different forums and havent found a proper solution yet. The main question is, how can I compute big np.arrays which extend my memory. Best Regards, Florian Hochwart From johnf at jfcomputer.com Wed Oct 14 11:03:22 2020 From: johnf at jfcomputer.com (john fabiani) Date: Wed, 14 Oct 2020 08:03:22 -0700 Subject: [Tutor] downloading the whl Message-ID: <0915233d-a816-5b91-de7c-0208d23378db@jfcomputer.com> Hi, I realize that I can use pip to install modules by using 'pip install module'.? However, I have to do this for about 10 modules to install a program.? Is it possible to retrieve the 'whl' file save it on a local drive so I can instead of using the internet to retrieve the whl? If it possible to retrieve the module whl how is it done?? All of the modules I need are on pypi.org. Johnf From mats at wichmann.us Wed Oct 14 11:22:01 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 14 Oct 2020 09:22:01 -0600 Subject: [Tutor] downloading the whl In-Reply-To: <0915233d-a816-5b91-de7c-0208d23378db@jfcomputer.com> References: <0915233d-a816-5b91-de7c-0208d23378db@jfcomputer.com> Message-ID: <75757b75-326d-ddb7-7b41-09681f36c5fd@wichmann.us> On 10/14/20 9:03 AM, john fabiani wrote: > Hi, > > I realize that I can use pip to install modules by using 'pip install > module'.? However, I have to do this for about 10 modules to install a > program.? Is it possible to retrieve the 'whl' file save it on a local > drive so I can instead of using the internet to retrieve the whl? > > If it possible to retrieve the module whl how is it done?? All of the > modules I need are on pypi.org. You can use the pip "download" command, or if you've done the install on one machine, the downloaded packages can be found in the cache (although you have to do a little hunting for that). You can put the modules you need into a requirements.txt file and use that to drive the install/download. From mats at wichmann.us Wed Oct 14 12:53:29 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 14 Oct 2020 10:53:29 -0600 Subject: [Tutor] np.array operation memoryerror In-Reply-To: <001501d6a230$4e4e69e0$eaeb3da0$@gmx.de> References: <001501d6a230$4e4e69e0$eaeb3da0$@gmx.de> Message-ID: <5d5143f6-6963-41f3-6e96-9807cdf9fd09@wichmann.us> On 10/14/20 7:45 AM, f.hochwart at gmx.de wrote: > > > Hello, > > > > for my masterthesis I have to compute e.g. np.arrays with following > settings: > > > > MemoryError: Unable to allocate 7.15 TiB for an array with shape (991600, > 991600) and data type float64 Would encourage you to ask for help amongst numpy people. I'm sure this is a familiar issue, obviously sparse allocation must have some way of working or it wouldn't do much good. Try picking one of the resources from here as a starting point: https://numpy.org/gethelp/ From johnf at jfcomputer.com Wed Oct 14 12:59:43 2020 From: johnf at jfcomputer.com (john fabiani) Date: Wed, 14 Oct 2020 09:59:43 -0700 Subject: [Tutor] downloading the whl In-Reply-To: <75757b75-326d-ddb7-7b41-09681f36c5fd@wichmann.us> References: <0915233d-a816-5b91-de7c-0208d23378db@jfcomputer.com> <75757b75-326d-ddb7-7b41-09681f36c5fd@wichmann.us> Message-ID: Now I feel silly!? I did not realize the option of download was available.? Thanks for the help. Johnf On 10/14/20 8:22 AM, Mats Wichmann wrote: > On 10/14/20 9:03 AM, john fabiani wrote: >> Hi, >> >> I realize that I can use pip to install modules by using 'pip install >> module'.? However, I have to do this for about 10 modules to install a >> program.? Is it possible to retrieve the 'whl' file save it on a local >> drive so I can instead of using the internet to retrieve the whl? >> >> If it possible to retrieve the module whl how is it done?? All of the >> modules I need are on pypi.org. > > You can use the pip "download" command, or if you've done the install on > one machine, the downloaded packages can be found in the cache (although > you have to do a little hunting for that). > > You can put the modules you need into a requirements.txt file and use > that to drive the install/download. > _______________________________________________ > 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 Wed Oct 14 13:07:12 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 14 Oct 2020 18:07:12 +0100 Subject: [Tutor] np.array operation memoryerror In-Reply-To: <001501d6a230$4e4e69e0$eaeb3da0$@gmx.de> References: <001501d6a230$4e4e69e0$eaeb3da0$@gmx.de> Message-ID: On 14/10/2020 14:45, f.hochwart at gmx.de wrote: > for my masterthesis I have to compute e.g. np.arrays with following > settings: > MemoryError: Unable to allocate 7.15 TiB for an array with shape (991600, > 991600) and data type float64 This suggests you don't have enough memory to load your data. You either need to increase the memory or reduce the data! > A = sparse.bsr_matrix(C1 * (sparse.bsr_matrix(np.eye(dA, k = dR)) -2 * > sparse.bsr_matrix(np.eye(dA)) + sparse.bsr_matrix(np.eye(dA, k = -dR)))) Can't help with numpy, thee is a support forum though if you visit their web site.There may be a way of paging data or similar. > The main question is, how can I compute big np.arrays which extend my > memory. The traditional way to do that would be to load "pages" of data at a time and process each page. (It may help if you can sort the data first) Then combine the page results to get an overall result. But without knowing more about your data (in and out) and how you plan on processing it we can't say much more. You might have to work a bit harder to get your masters... :-) But I'd start by asking on the numpy fora. -- 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 manpritsinghece at gmail.com Wed Oct 14 13:26:49 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 14 Oct 2020 22:56:49 +0530 Subject: [Tutor] all( ) built in function Message-ID: Dear Sir , I just want to check my understanding of using all( ), a built in function, with examples given below : test_seq = [ [2, 3], [3, 6], [ ], [4, 8] ] all(test_seq) will return False as test_seq contains an empty list which is considered as false object when tested for truth value t_lst = [3, 5, 6, 0, 7] all(t_lst) will also return False as t_lst contains a 0 which is considered as a false object when tested for truth value. test_s = [None, True, True, True] all(test_s) will also return False as test_s contains None which is considered as a false object when tested for truth value. t_s = [3, 5, 8, 9] all(t_s) will return True as every element of t_s is considered as a true object when tested for truth value. Your precious comments needed Regards Manprit Singh Kindly let me know From nulla.epistola at web.de Wed Oct 14 14:42:01 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Wed, 14 Oct 2020 20:42:01 +0200 Subject: [Tutor] all( ) built in function In-Reply-To: References: Message-ID: <0bda05f9-9f47-1f50-c8fb-406709388c1d@web.de> Am 14.10.2020 um 19:26 schrieb Manprit Singh: > Dear Sir , > > I just want to check my understanding of using all( ), a built in > function, with examples given below : > > test_seq = [ [2, 3], [3, 6], [ ], [4, 8] ] > all(test_seq) will return False as test_seq contains an empty list which is > considered as false object when tested for truth value > > t_lst = [3, 5, 6, 0, 7] > all(t_lst) will also return False as t_lst contains a 0 which is > considered as a false object when tested for truth value. > > test_s = [None, True, True, True] > all(test_s) will also return False as test_s contains None which is > considered as a false object when tested for truth value. > > t_s = [3, 5, 8, 9] > all(t_s) will return True as every element of t_s is considered as a true > object when tested for truth value. > What did your interactive Python interpreter say? From nulla.epistola at web.de Wed Oct 14 14:42:01 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Wed, 14 Oct 2020 20:42:01 +0200 Subject: [Tutor] all( ) built in function In-Reply-To: References: Message-ID: <0bda05f9-9f47-1f50-c8fb-406709388c1d@web.de> Am 14.10.2020 um 19:26 schrieb Manprit Singh: > Dear Sir , > > I just want to check my understanding of using all( ), a built in > function, with examples given below : > > test_seq = [ [2, 3], [3, 6], [ ], [4, 8] ] > all(test_seq) will return False as test_seq contains an empty list which is > considered as false object when tested for truth value > > t_lst = [3, 5, 6, 0, 7] > all(t_lst) will also return False as t_lst contains a 0 which is > considered as a false object when tested for truth value. > > test_s = [None, True, True, True] > all(test_s) will also return False as test_s contains None which is > considered as a false object when tested for truth value. > > t_s = [3, 5, 8, 9] > all(t_s) will return True as every element of t_s is considered as a true > object when tested for truth value. > What did your interactive Python interpreter say? From johnf at jfcomputer.com Wed Oct 14 18:13:44 2020 From: johnf at jfcomputer.com (john fabiani) Date: Wed, 14 Oct 2020 15:13:44 -0700 Subject: [Tutor] downloading the whl In-Reply-To: <75757b75-326d-ddb7-7b41-09681f36c5fd@wichmann.us> References: <0915233d-a816-5b91-de7c-0208d23378db@jfcomputer.com> <75757b75-326d-ddb7-7b41-09681f36c5fd@wichmann.us> Message-ID: <0f58eec0-9502-8ceb-85a7-4cde3fe9bb1b@jfcomputer.com> when I used the download feature with the authorizenet module - the feature downloaded a .tar.gz file and not the 'whl'. So now I'm at a lost how to deal with the file. Johnf On 10/14/20 8:22 AM, Mats Wichmann wrote: > On 10/14/20 9:03 AM, john fabiani wrote: >> Hi, >> >> I realize that I can use pip to install modules by using 'pip install >> module'.? However, I have to do this for about 10 modules to install a >> program.? Is it possible to retrieve the 'whl' file save it on a local >> drive so I can instead of using the internet to retrieve the whl? >> >> If it possible to retrieve the module whl how is it done?? All of the >> modules I need are on pypi.org. > > You can use the pip "download" command, or if you've done the install on > one machine, the downloaded packages can be found in the cache (although > you have to do a little hunting for that). > > You can put the modules you need into a requirements.txt file and use > that to drive the install/download. > _______________________________________________ > 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 Oct 14 18:45:39 2020 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 14 Oct 2020 16:45:39 -0600 Subject: [Tutor] downloading the whl In-Reply-To: <0f58eec0-9502-8ceb-85a7-4cde3fe9bb1b@jfcomputer.com> References: <0915233d-a816-5b91-de7c-0208d23378db@jfcomputer.com> <75757b75-326d-ddb7-7b41-09681f36c5fd@wichmann.us> <0f58eec0-9502-8ceb-85a7-4cde3fe9bb1b@jfcomputer.com> Message-ID: <3a4a0dfb-ccfa-d690-fd0e-7cd184cc9749@wichmann.us> On 10/14/20 4:13 PM, john fabiani wrote: > when I used the download feature with the authorizenet module - the > feature downloaded a .tar.gz file and not the 'whl'. > > So now I'm at a lost how to deal with the file. that's all there is... you can always search for a package on pypi.org and click on Download Files to see what there is. https://pypi.org/project/authorizenet/#files So the author has not provided wheels. Hopefully it will work - pip is designed to work with "source distributions", some of which don't need to compile anything, and some of which do. (the latter tends to be hard to get working right if you're on a Windows system, you usually have to find the instructions indicating what setup and what non-Python dependencies there are) Just try it and see if it works? From breamoreboy at gmail.com Wed Oct 14 13:44:29 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Wed, 14 Oct 2020 18:44:29 +0100 Subject: [Tutor] all( ) built in function In-Reply-To: References: Message-ID: On 14/10/2020 18:26, Manprit Singh wrote: > Dear Sir , > > I just want to check my understanding of using all( ), a built in > function, with examples given below : > > test_seq = [ [2, 3], [3, 6], [ ], [4, 8] ] > all(test_seq) will return False as test_seq contains an empty list which is > considered as false object when tested for truth value > > t_lst = [3, 5, 6, 0, 7] > all(t_lst) will also return False as t_lst contains a 0 which is > considered as a false object when tested for truth value. > > test_s = [None, True, True, True] > all(test_s) will also return False as test_s contains None which is > considered as a false object when tested for truth value. > > t_s = [3, 5, 8, 9] > all(t_s) will return True as every element of t_s is considered as a true > object when tested for truth value. > > Your precious comments needed > Regards > Manprit Singh > > Kindly let me know > Your examples seem to match the documentation https://docs.python.org/3/library/functions.html#all and have you tried any of them with the interactive interpreter? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at yahoo.co.uk Wed Oct 14 19:08:07 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 15 Oct 2020 00:08:07 +0100 Subject: [Tutor] all( ) built in function In-Reply-To: References: Message-ID: On 14/10/2020 18:26, Manprit Singh wrote: > Dear Sir , > > I just want to check my understanding of using all( ), a built in > function, with examples given below : As others have said the best way to check your understanding in Python is to ask the interpreter. It will give you a definitive answer. And it is much faster than typing an email and then waiting for a response. It's why it exists. > test_seq = [ [2, 3], [3, 6], [ ], [4, 8] ] > all(test_seq) will return False as test_seq contains an empty list which is > considered as false object when tested for truth value > > t_lst = [3, 5, 6, 0, 7] > all(t_lst) will also return False as t_lst contains a 0 which is > considered as a false object when tested for truth value. > > test_s = [None, True, True, True] > all(test_s) will also return False as test_s contains None which is > considered as a false object when tested for truth value. > > t_s = [3, 5, 8, 9] > all(t_s) will return True as every element of t_s is considered as a true > object when tested for truth value. You're understanding is correct in all cases. -- 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 manpritsinghece at gmail.com Wed Oct 14 19:09:16 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Thu, 15 Oct 2020 04:39:16 +0530 Subject: [Tutor] all( ) built in function In-Reply-To: References: Message-ID: Dear all, I have written my first mail with the same subject after trying it on an interactive python shell. The answers are the same as given in the mail. Just need to check my understanding about this function. Regards Manprit Singh On Thu, Oct 15, 2020 at 4:33 AM Mark Lawrence wrote: > On 14/10/2020 18:26, Manprit Singh wrote: > > Dear Sir , > > > > I just want to check my understanding of using all( ), a built in > > function, with examples given below : > > > > test_seq = [ [2, 3], [3, 6], [ ], [4, 8] ] > > all(test_seq) will return False as test_seq contains an empty list which > is > > considered as false object when tested for truth value > > > > t_lst = [3, 5, 6, 0, 7] > > all(t_lst) will also return False as t_lst contains a 0 which is > > considered as a false object when tested for truth value. > > > > test_s = [None, True, True, True] > > all(test_s) will also return False as test_s contains None which is > > considered as a false object when tested for truth value. > > > > t_s = [3, 5, 8, 9] > > all(t_s) will return True as every element of t_s is considered as a true > > object when tested for truth value. > > > > Your precious comments needed > > Regards > > Manprit Singh > > > > Kindly let me know > > > > Your examples seem to match the documentation > https://docs.python.org/3/library/functions.html#all and have you tried > any of them with the interactive interpreter? > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From manpritsinghece at gmail.com Thu Oct 15 00:57:29 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Thu, 15 Oct 2020 10:27:29 +0530 Subject: [Tutor] Slowness of Python Message-ID: Dear sir , In this mail, I just need a reply from you. I have a question - 'Why python is slow in comparison to other compiled languages like c or c++. There may be several reasons. The point that is coming to my mind is - Python is a dynamically typed language, you do not need to declare a datatype of the variable when assigning a value to it . So at run time, when actual execution takes place, First the datatype of the variable is checked and then if there is any operation involved, it is also checked that the operation is valid for that datatype or not, then the execution takes place . So this kind of checking will take time . This causes slowness . There is no such checking involved in the case of compiled languages during runtime, as this process is being done at the compile time in compiled language. Is my point correct or incorrect ? Can you please tell me some more few points in this regard Regards Manprit Singh From PyTutor at DancesWithMice.info Thu Oct 15 01:03:35 2020 From: PyTutor at DancesWithMice.info (dn) Date: Thu, 15 Oct 2020 18:03:35 +1300 Subject: [Tutor] Slowness of Python In-Reply-To: References: Message-ID: On 15/10/2020 17:57, Manprit Singh wrote: > Dear sir , > > In this mail, I just need a reply from you. I have a question - 'Why python > is slow in comparison to other compiled languages like c or c++. > > There may be several reasons. The point that is coming to my mind is - > Python is a dynamically typed language, you do not need to declare a > datatype of the variable when assigning a value to it . So at run time, > when actual execution takes place, First the datatype of the variable is > checked and then if there is any operation involved, it is also checked > that the operation is valid for that datatype or not, then the execution > takes place . So this kind of checking will take time . This causes > slowness . There is no such checking involved in the case of compiled > languages during runtime, as this process is being done at the compile time > in compiled language. > Is my point correct or incorrect ? Can you please tell me some more few > points in this regard Less to do with data and typing, more to do with being an interpreted-, cf a compiled-language. https://duckduckgo.com/?q=why+is+python+slow -- Regards =dn From alan.gauld at yahoo.co.uk Thu Oct 15 05:41:17 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 15 Oct 2020 10:41:17 +0100 Subject: [Tutor] Slowness of Python In-Reply-To: References: Message-ID: On 15/10/2020 05:57, Manprit Singh wrote: > In this mail, I just need a reply from you. I have a question - 'Why python > is slow in comparison to other compiled languages like c or c++. OK, This is a very complex one. But the first thing to say is that C/C++ are currently the fastest executing languages around. All languages are slow in comparison to them and its not as simple as compiled v interpreted, or static v dynamic typing. On the other hand C++ in particular is one of the slowest languages around when it comes to development, whereas Python is one of the fastest. There is a direct tradeoff here. In C++ the programmer takes responsibility for many things that Python does for you, so you have to write a lot more code and, more importantly, think a lot more about how the code works at the machine level. That all takes rime. Python has been optimised for speed of development not speed of execution. For the few cases where speed of execution is critical we have other strategies that we can use. C/C++ on the other hand are first and foremost systems programming languages designed to interact with the hardware and speed, especially predictable timing, is of vital importance in those problem domains. The final point is that Python is a compiled language. Your code is compiled before it is interpreted. But where C++ compiles into native machine code Python (like most popular modern languages - Java, C#, Perl, Ruby etc) compiles into an intermediate language known as byte-code and then the byte-code is interpreted. This makes the interpreter easier to write and much faster and also makes the code portable across machine types and OS. An interpreter will always be slower than native machine code as produced by a good compiler. You can get interpreters for C and C++(*) and they are much slower than the compiled versions. But they allow fast development and on-the-fly code testing. (*)I'm not sure there are any modern C++ interpreters, C++ is a hugely complex language and I haven't seen a C++ interpreter since about 1996... But C interpreters do still exist. > There may be several reasons. The point that is coming to my mind is - > Python is a dynamically typed language, you do not need to declare a > datatype of the variable when assigning a value to it . So at run time, > when actual execution takes place, First the datatype of the variable is > checked and then if there is any operation involved, it is also checked > that the operation is valid for that datatype or not, then the execution > takes place. To be honest I don't know the internal details of Python well enough to answer that. But it may be that Python does not check the type it merely checks whether the operation exists or not(so called duck-typing) But you are correct in thinking that dynamic typing is the biggest factor in the speed difference between Python and statically typed languages. The interpreter must do run-type checks before performing an operation. So, even if you used a C interpreter, C would still be faster than Python because of the dynamic typing! On the other hand dynamic typing allows for much shorter code since the programmer does not need to explicitly perform multiple type conversions in his/her code. It also allows for polymorphic behaviour of collections which is much more difficult to program by hand in say C++. Finally, as mentioned earlier, Python takes a different approach to speed. It views high speed as a (relatively) rarely required feature and provides alternative strategies to achieve that. Primarily it allows functions to be written in C and then accessed from Python. That is why most of the speed critical modules in Python are written in C - things like the regex, pickle, math and others. So when you call those functions they run at the same speed as C because they are C. There are other speed boosting tools around that integrate with Python - things like Cython and Pyrex for example. But the most important tool in boosting speed is good design, both of code and data structures. And Python provides a wealth of data structures that allow efficient design of algorithms. Python also provides a profiling tool to identify bottlenecks. So if you need your code to go faster: 1) profile it to see where the time is being spent 2) optimise the design of those parts of your program (This includes checking that there are no modules that do the same job, and tuning/changing your data structures to better represent the problem - sets/dicts are often more effective than lists for example) 3) if that's still not enough rewrite those parts in C or use one of the speed enhancing tools such as Cython or Pyrex. -- 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 manpritsinghece at gmail.com Thu Oct 15 11:33:30 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Thu, 15 Oct 2020 21:03:30 +0530 Subject: [Tutor] Truth value testing in if, while and boolean operations Message-ID: Dear sir , While referring to python docs , i found that under the heading "Truth Value testing" it is written that empty sequences and collections: '', (), [], {}, set(), range(0) are considered as false . In PEP8 docs under "programming recommendations" it is written that : "For sequences, (strings, lists, tuples), use the fact that empty sequences are false: so it is a valid practice to write like this if sequence: # do_this() will be executed if sequence is not empty do_this() else: # do_this_1() will be executed if sequence is empty do_this_1() There is nothing mentioned in PEP 8 about using the sets, dicts etc in the same way as given above . As we know that empty sets & dicts are also considered false, using dicts and sets in the way as given above is valid and adheres to PEP 8 guidelines ? ___________________________________________________________________ if dict: # do_this() will be executed if dict is not empty do_this() else: # do_this_1() will be executed if dict is empty do_this_1() _____________________________________________________________________ if set: # do_this() will be executed if set is not empty do_this() else: # do_this_1() will be executed if set is empty do_this_1() ___________________________________________________________________ 2 Examples just given above are valid according to PEP 8? Regards Manprit Singh From mats at wichmann.us Thu Oct 15 11:42:21 2020 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 15 Oct 2020 09:42:21 -0600 Subject: [Tutor] Truth value testing in if, while and boolean operations In-Reply-To: References: Message-ID: <0646d497-92db-69e6-640c-46a0153bab53@wichmann.us> On 10/15/20 9:33 AM, Manprit Singh wrote: > Dear sir , > > While referring to python docs , i found that under the heading "Truth > Value testing" it is written that > > empty sequences and collections: '', (), [], {}, set(), range(0) are > considered as false . > > In PEP8 docs under "programming recommendations" it is written that : > > "For sequences, (strings, lists, tuples), use the fact that empty sequences > are false: > > so it is a valid practice to write like this > > if sequence: # do_this() will be executed if sequence is not empty > > do_this() > > else: # do_this_1() will be executed if sequence is empty > > do_this_1() > > There is nothing mentioned in PEP 8 about using the sets, dicts etc in the > same way as given above . As we know that empty sets & dicts are also > considered false, using dicts and sets in the way as given above is valid > and adheres to PEP 8 guidelines ? As long as you don't use the actual words dict and set (except as callables, to create new objects) since those are builtins and will return true because in this context they are non-empty objects. > if dict: # do_this() will be executed if dict is not empty > > do_this() > > else: # do_this_1() will be executed if dict is empty > > do_this_1() > > _____________________________________________________________________ > > if set: # do_this() will be executed if set is not empty > > do_this() > > else: # do_this_1() will be executed if set is empty > > do_this_1() >>> bool({}) False >>> bool(dict()) False >>> bool(dict) True >>> bool(set) True >>> bool(set()) False >>> From alan.gauld at yahoo.co.uk Thu Oct 15 13:02:38 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 15 Oct 2020 18:02:38 +0100 Subject: [Tutor] Truth value testing in if, while and boolean operations In-Reply-To: References: Message-ID: On 15/10/2020 16:33, Manprit Singh wrote: > Dear sir , > > While referring to python docs , i found that under the heading "Truth > Value testing" it is written that > > empty sequences and collections: '', (), [], {}, set(), range(0) are > considered as false . > > In PEP8 docs under "programming recommendations" it is written that : > > "For sequences, (strings, lists, tuples), use the fact that empty sequences > are false: > > so it is a valid practice to write like this > > if sequence: # do_this() will be executed if sequence is not empty > > do_this() > There is nothing mentioned in PEP 8 about using the sets, dicts etc in the > same way as given above . PEP 8 is a style guide not a language reference. it is not exhaustive. However it does say "if sequence" and your quote in the first paragraph says: > empty sequences and collections: '', (), [], {}, set(), range(0) are > considered as false . ie. sequence includes strings, tuples, dicts, sets, lists, ranges... So PEP8 includes all of the above. -- 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 manpritsinghece at gmail.com Thu Oct 15 21:30:54 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 16 Oct 2020 07:00:54 +0530 Subject: [Tutor] Program to find if a number entered by user is a prime number or not Message-ID: Dear Sir , I was trying to write a program which allows the user to input a number from a keyboard , it then prints the message x is prime if number input by user is a prime number and x is not prime if the number input by user is not a prime number. (here x represents the number). The program is written below: x = int(input("Enter any positive number")) a = "not prime" if all(x%i for i in range(2, int(x**0.5) + 1)): if x < 2: pass else: a = "prime" else: pass print(x,"is",a) I have these questions in my mind : 1) If you can see I have used pass two times , Initially I have assigned a string "not prime" to variable a . Now if user input is either 0 or 1 , it is not a prime number. That's why i have written a pass inside the below written block, which will maintain a = 'not prime" when user input is either 0 or 1. if all(x%i for i in range(2, int(x**0.5) + 1)): if x < 2: pass for any value of user input greater than 1 if the iterable inside all( ) is empty or all(x%i for i in range(2, int(x**0.5) + 1)) return True , the user input for sure is a prime number , and hence i have assigned a = "prime" inside that block. Again for the second time i have used pass when all(x%i for i in range(2, int(x**0.5) + 1)) returns False, in that case the number input by user is again not a prime number , and hence i have used pass again in the block to maintain the old value of variable a ="not prime". Just need to know if my way of implementing the problem is correct ? Can this program be further optimised ? Regards Manprit Singh From manpritsinghece at gmail.com Thu Oct 15 21:49:38 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 16 Oct 2020 07:19:38 +0530 Subject: [Tutor] Program to find if a number entered by user is a prime number or not In-Reply-To: References: Message-ID: Dear sir, If i simply write this program as given below: x = int(input("Enter any positive number")) a = "not prime" if all(x%i for i in range(2, int(x**0.5) + 1)): if x >= 2: a = "prime" print(x,"is",a) Will it be ok ? On Fri, Oct 16, 2020 at 7:00 AM Manprit Singh wrote: > Dear Sir , > > I was trying to write a program which allows the user to input a number > from a keyboard , it then prints the message x is prime if number input by > user is a prime number and x is not prime if the number input by user is > not a prime number. (here x represents the number). The program is written > below: > > x = int(input("Enter any positive number")) > a = "not prime" > if all(x%i for i in range(2, int(x**0.5) + 1)): > if x < 2: > pass > else: > a = "prime" > else: > pass > print(x,"is",a) > > I have these questions in my mind : > 1) If you can see I have used pass two times , Initially I have assigned a > string "not prime" to variable a . Now if user input is either 0 or 1 , it > is not a prime number. That's why i have written a pass inside the below > written block, which will maintain a = 'not prime" when user input is > either 0 or 1. > > if all(x%i for i in range(2, int(x**0.5) + 1)): > if x < 2: > pass > for any value of user input greater than 1 if the iterable inside all( ) > is empty or all(x%i for i in range(2, int(x**0.5) + 1)) return True , the > user input for sure is a prime number , and hence i have assigned a = > "prime" inside that block. > > Again for the second time i have used pass when all(x%i for i in range(2, > int(x**0.5) + 1)) returns False, in that case the number input by user is > again not a prime number , and hence i have used pass again in the block to > maintain the old value of variable a ="not prime". > > Just need to know if my way of implementing the problem is correct ? Can > this program be further optimised ? > > Regards > Manprit Singh > > > > From manpritsinghece at gmail.com Fri Oct 16 02:01:22 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 16 Oct 2020 11:31:22 +0530 Subject: [Tutor] Program to find if a number entered by user is a prime number or not In-Reply-To: References: Message-ID: Dear sir , So now i have two ways : First way : _________________________________ x = int(input("Enter a number")) if x < 2 or any(x % i == 0 for i in range(2, int(x**0.5) + 1)): print(x,"is not a prime number") else: print(x,"is a prime number") Second way : ______________________________________ x = int(input("Enter any positive number")) if all(x%i for i in range(2, int(x**0.5) + 1)) and x >= 2: print(x," is prime") else: print(x,"is not prime") What to prefer ? Regards Manprit Singh On Fri, Oct 16, 2020 at 7:19 AM Manprit Singh wrote: > Dear sir, > If i simply write this program as given below: > > x = int(input("Enter any positive number")) > a = "not prime" > if all(x%i for i in range(2, int(x**0.5) + 1)): > if x >= 2: > a = "prime" > print(x,"is",a) > > Will it be ok ? > > On Fri, Oct 16, 2020 at 7:00 AM Manprit Singh > wrote: > >> Dear Sir , >> >> I was trying to write a program which allows the user to input a number >> from a keyboard , it then prints the message x is prime if number input by >> user is a prime number and x is not prime if the number input by user is >> not a prime number. (here x represents the number). The program is written >> below: >> >> x = int(input("Enter any positive number")) >> a = "not prime" >> if all(x%i for i in range(2, int(x**0.5) + 1)): >> if x < 2: >> pass >> else: >> a = "prime" >> else: >> pass >> print(x,"is",a) >> >> I have these questions in my mind : >> 1) If you can see I have used pass two times , Initially I have assigned >> a string "not prime" to variable a . Now if user input is either 0 or 1 , >> it is not a prime number. That's why i have written a pass inside the >> below written block, which will maintain a = 'not prime" when user input >> is either 0 or 1. >> >> if all(x%i for i in range(2, int(x**0.5) + 1)): >> if x < 2: >> pass >> for any value of user input greater than 1 if the iterable inside all( ) >> is empty or all(x%i for i in range(2, int(x**0.5) + 1)) return True , the >> user input for sure is a prime number , and hence i have assigned a = >> "prime" inside that block. >> >> Again for the second time i have used pass when all(x%i for i in range(2, >> int(x**0.5) + 1)) returns False, in that case the number input by user is >> again not a prime number , and hence i have used pass again in the block to >> maintain the old value of variable a ="not prime". >> >> Just need to know if my way of implementing the problem is correct ? Can >> this program be further optimised ? >> >> Regards >> Manprit Singh >> >> >> >> From breamoreboy at gmail.com Thu Oct 15 22:40:36 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 16 Oct 2020 03:40:36 +0100 Subject: [Tutor] Program to find if a number entered by user is a prime number or not In-Reply-To: References: Message-ID: On 16/10/2020 02:49, Manprit Singh wrote: [fix extremely irritating top posting] > On Fri, Oct 16, 2020 at 7:00 AM Manprit Singh > wrote: > >> Dear Sir , >> >> I was trying to write a program which allows the user to input a number >> from a keyboard , it then prints the message x is prime if number input by >> user is a prime number and x is not prime if the number input by user is >> not a prime number. (here x represents the number). The program is written >> below: >> >> x = int(input("Enter any positive number")) >> a = "not prime" >> if all(x%i for i in range(2, int(x**0.5) + 1)): >> if x < 2: >> pass >> else: >> a = "prime" >> else: >> pass >> print(x,"is",a) >> >> I have these questions in my mind : >> 1) If you can see I have used pass two times , Initially I have assigned a >> string "not prime" to variable a . Now if user input is either 0 or 1 , it >> is not a prime number. That's why i have written a pass inside the below >> written block, which will maintain a = 'not prime" when user input is >> either 0 or 1. >> >> if all(x%i for i in range(2, int(x**0.5) + 1)): >> if x < 2: >> pass >> for any value of user input greater than 1 if the iterable inside all( ) >> is empty or all(x%i for i in range(2, int(x**0.5) + 1)) return True , the >> user input for sure is a prime number , and hence i have assigned a = >> "prime" inside that block. >> >> Again for the second time i have used pass when all(x%i for i in range(2, >> int(x**0.5) + 1)) returns False, in that case the number input by user is >> again not a prime number , and hence i have used pass again in the block to >> maintain the old value of variable a ="not prime". >> >> Just need to know if my way of implementing the problem is correct ? Can >> this program be further optimised ? >> >> Regards >> Manprit Singh >> > Dear sir, > If i simply write this program as given below: > > x = int(input("Enter any positive number")) > a = "not prime" > if all(x%i for i in range(2, int(x**0.5) + 1)): > if x >= 2: > a = "prime" > print(x,"is",a) > > Will it be ok ? > If you have tested it yes it will be ok. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at yahoo.co.uk Fri Oct 16 04:40:48 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 16 Oct 2020 09:40:48 +0100 Subject: [Tutor] Program to find if a number entered by user is a prime number or not In-Reply-To: References: Message-ID: On 16/10/2020 02:30, Manprit Singh wrote: > x = int(input("Enter any positive number")) > a = "not prime" > if all(x%i for i in range(2, int(x**0.5) + 1)): > if x < 2: > pass > else: > a = "prime" > else: > pass > print(x,"is",a) This is bad on several counts. The biggest issue is that you do the call to all() before checking if the no is <2 which is a huge wasted effort. Much better to put the check for <2 before calling all() Also pass does nothing so there is no need to have else: pass just leave off the else. And if you have pass in an if and code in the else that means you should probably invert the if condition. > Just need to know if my way of implementing the problem is correct ? Can > this program be further optimised ? Its very convoluted. I notice you have now pasted two better solutions. I'll comment on them separately. -- 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 Oct 16 04:44:44 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 16 Oct 2020 09:44:44 +0100 Subject: [Tutor] Program to find if a number entered by user is a prime number or not In-Reply-To: References: Message-ID: On 16/10/2020 07:01, Manprit Singh wrote: > Dear sir , > > So now i have two ways : > > First way : > _________________________________ > > x = int(input("Enter a number")) > if x < 2 or any(x % i == 0 for i in range(2, int(x**0.5) + 1)): > print(x,"is not a prime number") > else: > print(x,"is a prime number") > > Second way : > ______________________________________ > x = int(input("Enter any positive number")) > if all(x%i for i in range(2, int(x**0.5) + 1)) and x >= 2: > print(x," is prime") > else: > print(x,"is not prime") > > What to prefer ? Provided you move the x >=2 test to the front of the all() then there should not be any difference in them. Pick whichever seems the most readable solution. Or, if you want to be sure, test them both for speed and pick the fastest. (I would hope there would be no significant 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 phillor9 at gmail.com Fri Oct 16 19:41:23 2020 From: phillor9 at gmail.com (Phil) Date: Sat, 17 Oct 2020 09:41:23 +1000 Subject: [Tutor] Running python files - solved In-Reply-To: References: Message-ID: <85065582-dc06-9b1e-4fdf-c63cd95bd084@gmail.com> On 14/10/20 10:16 am, Alan Gauld via Tutor wrote: > On 14/10/2020 00:28, Phil wrote: >> This seemingly simple problem has me scratching my head. How do I run a >> python file from a directory other than the directory that the python >> file is in? > There are several ways to do this. > 1) Use a hard coded full path. > 2) Put the full path in a config variable in a config file > 3) Get the path from an environment variable (and have a default if not set) > 4) change the current working directory to the folder your file is in > (using the os.chdir() function) Thank you everyone for your replies. However, I think my question was not fully understood, no doubt to my clumsiness. Anyway I have a solution, although I did take me some time to realise how simple the solution is. What I did was to create a launcher bash script that I have stored in my home directory. The launcher script changes to the directory where the python script is stored and then runs the python script. The system menu calls the launcher script. -- Regards, Phil From mats at wichmann.us Fri Oct 16 20:02:18 2020 From: mats at wichmann.us (Mats Wichmann) Date: Fri, 16 Oct 2020 18:02:18 -0600 Subject: [Tutor] Running python files - solved In-Reply-To: <85065582-dc06-9b1e-4fdf-c63cd95bd084@gmail.com> References: <85065582-dc06-9b1e-4fdf-c63cd95bd084@gmail.com> Message-ID: On 10/16/20 5:41 PM, Phil wrote: > Thank you everyone for your replies. However, I think my question was > not fully understood, no doubt to my clumsiness. Anyway I have a > solution, although I did take me some time to realise how simple the > solution is. > > What I did was to create a launcher bash script that I have stored in my > home directory. The launcher script changes to the directory where the > python script is stored and then runs the python script. The system menu > calls the launcher script. Glad you got it sorted. This is actually what some of us tried to point to: the context when you run things from a menu, or a crontab, or something other than your shell - is different than in that shell. And your launcher is a way to make the context on startup be what you want it to be. There are other ways to make that happen too, but you have something working - good on you! From manpritsinghece at gmail.com Sun Oct 18 01:39:20 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 18 Oct 2020 11:09:20 +0530 Subject: [Tutor] Nested list comprehensions Message-ID: Dear sir , While reading about nested list comprehensions, i have tried to write an example of making a 2D list with m rows and n columns with each element of list equals e. Just need to know , if my understanding is correct or not ? def two_d(row, col, ele): return [[ele for _ in range(col)] for _ in range(row)] m = int(input("Enter no of rows")) n = int(input("Enter no of columns")) e = int(input("Enter the element to be placed inside list')) two_d(m, n, e) Regards Manprit Singh From PyTutor at DancesWithMice.info Sun Oct 18 03:39:36 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sun, 18 Oct 2020 20:39:36 +1300 Subject: [Tutor] Nested list comprehensions In-Reply-To: References: Message-ID: <2727e3aa-2442-8297-a463-a59d4933badf@DancesWithMice.info> On 18/10/2020 18:39, Manprit Singh wrote: > Dear sir , > > While reading about nested list comprehensions, i have tried to write an > example of making a 2D list with m rows and n columns with each element of > list equals e. > Just need to know , if my understanding is correct or not ? > > def two_d(row, col, ele): > return [[ele for _ in range(col)] for _ in range(row)] > > m = int(input("Enter no of rows")) > n = int(input("Enter no of columns")) > e = int(input("Enter the element to be placed inside list')) > two_d(m, n, e) What appears when you print the returned result? (the result of the function which is 'lost', at present) NB to make it easier to read, import and use pprint (pretty-print) instead of print() and the default format for list(s). -- Regards =dn From breamoreboy at gmail.com Sun Oct 18 03:29:55 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 18 Oct 2020 08:29:55 +0100 Subject: [Tutor] Nested list comprehensions In-Reply-To: References: Message-ID: On 18/10/2020 06:39, Manprit Singh wrote: > Dear sir , > > While reading about nested list comprehensions, i have tried to write an > example of making a 2D list with m rows and n columns with each element of > list equals e. > Just need to know , if my understanding is correct or not ? > > def two_d(row, col, ele): > return [[ele for _ in range(col)] for _ in range(row)] > > m = int(input("Enter no of rows")) > n = int(input("Enter no of columns")) > e = int(input("Enter the element to be placed inside list')) > two_d(m, n, e) > > Regards > Manprit Singh > I don't intend doing your testing for you, so please try the code in the interactive interpreter or place the code in a script and run it. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From manpritsinghece at gmail.com Sun Oct 18 03:47:37 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 18 Oct 2020 13:17:37 +0530 Subject: [Tutor] Nested list comprehensions In-Reply-To: References: Message-ID: Dear sir, I have already tested the code.....the answer is correct too. My concern was just to check if my understanding about using nested list comprehensions is correct or not. Regards Manprit Singh On Sun, 18 Oct, 2020, 13:12 Mark Lawrence, wrote: > On 18/10/2020 06:39, Manprit Singh wrote: > > Dear sir , > > > > While reading about nested list comprehensions, i have tried to write an > > example of making a 2D list with m rows and n columns with each element > of > > list equals e. > > Just need to know , if my understanding is correct or not ? > > > > def two_d(row, col, ele): > > return [[ele for _ in range(col)] for _ in range(row)] > > > > m = int(input("Enter no of rows")) > > n = int(input("Enter no of columns")) > > e = int(input("Enter the element to be placed inside list')) > > two_d(m, n, e) > > > > Regards > > Manprit Singh > > > > I don't intend doing your testing for you, so please try the code in the > interactive interpreter or place the code in a script and run it. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From aliyan.navaid at gmail.com Sun Oct 18 03:58:32 2020 From: aliyan.navaid at gmail.com (Aliyan Navaid) Date: Sun, 18 Oct 2020 12:58:32 +0500 Subject: [Tutor] (no subject) Message-ID: <23EF7BBD-2E34-4C5A-863C-6EB57228661B@hxcore.ol> I want to write a program which list ALL the errors while entering a user name. (If I use if elif blocks the program will end at the first error it catches) ? characters = 90 special_characters = True ? if characters < 3: ??? print(?Username too short?) elif characters > 50: ??? print(?Username too long?) elif special_characters: ??? print(?Special characters not allowed?) else: ??? print(?Username is valid?) ? ? ? #This program only outputs ?Username too long? even though there is another error ( I.e. ?Special characters not allowed? ) From alan.gauld at yahoo.co.uk Sun Oct 18 07:27:12 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 18 Oct 2020 12:27:12 +0100 Subject: [Tutor] Nested list comprehensions In-Reply-To: References: Message-ID: On 18/10/2020 08:47, Manprit Singh wrote: > I have already tested the code.....the answer is correct too. Which is the reason for Mark's frustration. Your understanding of how to write a nested comprehension must be correct if the code works and produces the right answer. The interpreter is the definitive arbiter of what is right. So it is not clear what exactly you are asking for. > My concern was just to check if my understanding about using nested list > comprehensions is correct or not. Correct in what way? Technically yes, it is obviously right if the interpreter can execute it and produce the result you are looking for. What more do you want to know? Please ask specific questions then we can provide specific answers. If you want to know about whether its an appropriate scenario for a nested comprehension then say so - the answer is probably. We'd need more context to be definitive. The only thing to be wary of with nested comprehensions is that they can rapidly become unreadably complex and they are very difficult to debug because too much is happening in a single line. Beyond that, what do you want to know? -- 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 Sun Oct 18 07:34:11 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 18 Oct 2020 12:34:11 +0100 Subject: [Tutor] (no subject) In-Reply-To: <23EF7BBD-2E34-4C5A-863C-6EB57228661B@hxcore.ol> References: <23EF7BBD-2E34-4C5A-863C-6EB57228661B@hxcore.ol> Message-ID: On 18/10/2020 08:58, Aliyan Navaid wrote: > I want to write a program which list ALL the errors while entering a user > name. > > (If I use if elif blocks the program will end at the first error it > catches) You have just answered your own question. Stop using elif clauses. Just use if. hasErrors = False if characters < 3: ??? print(?Username too short?) hasErrors = True if characters > 50: ??? print(?Username too long?) hasErrors = Trueif special_characters: ??? print(?Special characters not allowed?) hasErrors = True if not hasErrors: print(?Username is valid?) if hasErrors: # Now do something to recover! But it must be said that its an unusual strategy. Most programs detect the first error and stop. -- 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 Sun Oct 18 07:42:42 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 18 Oct 2020 12:42:42 +0100 Subject: [Tutor] Nested list comprehensions In-Reply-To: References: Message-ID: On 18/10/2020 06:39, Manprit Singh wrote: > Just need to know , if my understanding is correct or not ? Its hard to know what your understanding is from this example. Thee are multiple ways to write nested comprehensions. This example is really just one comprehension embeded in another. A comprehension is: [ ] The expression can be any valid Python expression, which obviously includes a comprehension. The condition likewise can be any Python expression that evaluates to a thruth-like value - so that too could be a comprehension. And the for loop can have multiple elements which is also referred to as a nested comprehension. And you can nest comprehensions to an arbitrary number of levels, resulting in code that is completely incomprehensible. Does your understanding encompass all those variety of nested comprehension? > def two_d(row, col, ele): > return [[ele for _ in range(col)] for _ in range(row)] > > m = int(input("Enter no of rows")) > n = int(input("Enter no of columns")) > e = int(input("Enter the element to be placed inside list')) > two_d(m, n, e) -- 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 Sun Oct 18 08:24:25 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 18 Oct 2020 06:24:25 -0600 Subject: [Tutor] Nested list comprehensions In-Reply-To: References: Message-ID: <8bc58a50-aa52-fb90-4454-faaace10b9a7@wichmann.us> On 10/17/20 11:39 PM, Manprit Singh wrote: > Dear sir , > > While reading about nested list comprehensions, i have tried to write an > example of making a 2D list with m rows and n columns with each element of > list equals e. > Just need to know , if my understanding is correct or not ? > > def two_d(row, col, ele): > return [[ele for _ in range(col)] for _ in range(row)] > > m = int(input("Enter no of rows")) > n = int(input("Enter no of columns")) > e = int(input("Enter the element to be placed inside list')) > two_d(m, n, e) To the other replies let me add a thought: when you build an object using a comprehension, you are committing to creating the whole thing there as that line runs. For most of what we do - *especially* in small artificial learning examples - that's fine, and just what you want. But when you're nesting to initialize a multi-dimensional array, it can easily get big, and slow. Try giving your sample code some bigger numbers, say 50,000 x 50,000 - you'll notice a considerable delay as it creates. Maybe you didn't need to fully allocate all of that up front? Python has ways of deferring the computation - range is an example - it's a lazy iterable that produces its values when asked for them - though when used as above, you lose the effect of the lazyness since you ask for all the values in a loop. The map function, while much less popular than it used to be since comprehensions became "the thing", returns an iterator, another kind of "just-in-time" object. From manpritsinghece at gmail.com Sun Oct 18 09:08:43 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 18 Oct 2020 18:38:43 +0530 Subject: [Tutor] Nested list comprehensions In-Reply-To: References: Message-ID: Dear sir , I realized my mistake, the question is incomplete . But With the previous replies i have got clarity about nested list comprehensions too . See when we go through Python docs for nested list comprehension, the example given(Transpose of a matrix) really is quite difficult to understand(less readable) . So Someone like me who is reading this example given in Python docs will be forced to think - what is the appropriate use case of nested list comprehensions . Hope I am right ? Example given in Python docs is given below : matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12],] To transpose rows and columns : [[row[i] for row in matrix] for i in range(4)] See this is not a readable solution. When i read it for the first time, i too didn't get what's going with this comprehension. So clearly i will not prefer using it. So the question comes to explain the valid and readable use case for nested list comprehension . For that i quickly wrote an example to create a 2D list with for loop and with list comprehension . which are as follows : def two_d(r, c, e): l1 = [] for i in range(r): l2 = [] for j in range(c): l2.append(e) l1.append(l2) return l1 two_d(3, 5, 8) Out[4]: [[8, 8, 8, 8, 8], [8, 8, 8, 8, 8], [8, 8, 8, 8, 8]] Obviously this for loop based solution may be disliked by most of the people , hance i tried to write it in list comprehension form as follows and found it more convenient , which is given below : def two_d(row, col, ele): return [[ele for _ in range(col)] for _ in range(row)] x = two_d(3, 5, 8) print(x) and got the same answer . See here the nested comprehension is quite clear to read, and hence i wrote a question but unfortunately i wasn't able to express myself fully . So comparing my own example with the example given in the Python documentation, i feel my example is readable one and can be used to explain the valid use case of nested list comprehension . I hope my question is clear now . Regards Manprit Singh On Sun, Oct 18, 2020 at 11:09 AM Manprit Singh wrote: > Dear sir , > > While reading about nested list comprehensions, i have tried to write an > example of making a 2D list with m rows and n columns with each element of > list equals e. > Just need to know , if my understanding is correct or not ? > > def two_d(row, col, ele): > return [[ele for _ in range(col)] for _ in range(row)] > > m = int(input("Enter no of rows")) > n = int(input("Enter no of columns")) > e = int(input("Enter the element to be placed inside list')) > two_d(m, n, e) > > Regards > Manprit Singh > From cthwong at yahoo.com Sun Oct 18 08:57:37 2020 From: cthwong at yahoo.com (Carlene Wong) Date: Sun, 18 Oct 2020 08:57:37 -0400 Subject: [Tutor] Slicing index References: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B.ref@yahoo.com> Message-ID: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B@yahoo.com> Hello, I?m new but I?m getting trouble with slicing an index into another. Eg. Def mysentence (sentence, old, new) If old in sentence[-4:]: n= sentence.index(old) newsent=Sentence [:n]+new return newsent return mysentence print(mysentence(?Hello there, it?s raining cats and cats?, ? cats?, ? dogs?) It keeps printing Hello there, it?s raining dogs Your help Sent from my iPhone From mats at wichmann.us Sun Oct 18 11:55:26 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 18 Oct 2020 09:55:26 -0600 Subject: [Tutor] Slicing index In-Reply-To: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B@yahoo.com> References: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B.ref@yahoo.com> <96456A2E-9598-4E3B-B6BC-2D1055A1F94B@yahoo.com> Message-ID: <4e0ceb53-1bbb-2afd-d57f-33579d9bbe0d@wichmann.us> On 10/18/20 6:57 AM, Carlene Wong via Tutor wrote: > Hello, I?m new but I?m getting trouble with slicing an index into another. > Eg. Def mysentence (sentence, old, new) > If old in sentence[-4:]: > n= sentence.index(old) > newsent=Sentence [:n]+new > return newsent > return mysentence > print(mysentence(?Hello there, it?s raining cats and cats?, ? cats?, ? dogs?) > > It keeps printing > Hello there, it?s raining dogs If you've transcribed that correctly, which one suspects you haven't, that's not what you should get. (in future, please paste directly from a code editor - I see in the print statement what looks like Microsoft-style smart quotes, which are not a valid Python string delimiter, plus the indentation is all wrong to be syntactically correct) In your function, you try to match the passed-in string, which as written is five characters " cats" (including a leading space) to a slice of the last four characters of sentence, which will never match. On to your actual question: you're trying to first check if the string to be replaced appears at the end of the sentence, but then when you call the index method, you'll get the index of the *first* match (use , and you slice that off and add the replacement string, so the outcome is as one would expect in this case - the selected slice is "Hello there, it's raining" and you add to that " dogs". Use rindex() if you want to match from the right, aka the *last* match. From nulla.epistola at web.de Sun Oct 18 13:42:40 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 18 Oct 2020 19:42:40 +0200 Subject: [Tutor] (no subject) In-Reply-To: References: <23EF7BBD-2E34-4C5A-863C-6EB57228661B@hxcore.ol> Message-ID: <9039dad7-1d3f-040b-ff0e-54c2d3618da9@web.de> Am 18.10.2020 um 13:34 schrieb Alan Gauld via Tutor: > On 18/10/2020 08:58, Aliyan Navaid wrote: >> I want to write a program which list ALL the errors while entering a user >> name. >> >> (If I use if elif blocks the program will end at the first error it >> catches) > > You have just answered your own question. > Stop using elif clauses. Just use if. > Exception: if two conditions can't both be true, but can both be false, as the two first conditions here. In this case I'd leave the elif in. > hasErrors = False > if characters < 3: > ??? print(?Username too short?) > hasErrors = True > if characters > 50: > ??? print(?Username too long?) > hasErrors = Trueif special_characters: > ??? print(?Special characters not allowed?) > hasErrors = True > if not hasErrors: > print(?Username is valid?) > > if hasErrors: # Now do something to recover! > > > But it must be said that its an unusual strategy. > Most programs detect the first error and stop. > From nulla.epistola at web.de Sun Oct 18 13:42:40 2020 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sun, 18 Oct 2020 19:42:40 +0200 Subject: [Tutor] (no subject) In-Reply-To: References: <23EF7BBD-2E34-4C5A-863C-6EB57228661B@hxcore.ol> Message-ID: <9039dad7-1d3f-040b-ff0e-54c2d3618da9@web.de> Am 18.10.2020 um 13:34 schrieb Alan Gauld via Tutor: > On 18/10/2020 08:58, Aliyan Navaid wrote: >> I want to write a program which list ALL the errors while entering a user >> name. >> >> (If I use if elif blocks the program will end at the first error it >> catches) > > You have just answered your own question. > Stop using elif clauses. Just use if. > Exception: if two conditions can't both be true, but can both be false, as the two first conditions here. In this case I'd leave the elif in. > hasErrors = False > if characters < 3: > ??? print(?Username too short?) > hasErrors = True > if characters > 50: > ??? print(?Username too long?) > hasErrors = Trueif special_characters: > ??? print(?Special characters not allowed?) > hasErrors = True > if not hasErrors: > print(?Username is valid?) > > if hasErrors: # Now do something to recover! > > > But it must be said that its an unusual strategy. > Most programs detect the first error and stop. > From cranky.frankie at gmail.com Sun Oct 18 14:36:50 2020 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Sun, 18 Oct 2020 14:36:50 -0400 Subject: [Tutor] Clearing the screen from the terminal Message-ID: Is there a way, before I run my Python program in command/terminal mode (no GUI), to clear the screen before the program starts? If so, can it be done while the program is running as well? Frank L. "Cranky Frankie" Palmeri, Risible Riding Raconteur & Writer WORK Hard - PLAY Hard - READ Hard - THINK Hard From breamoreboy at gmail.com Sun Oct 18 12:22:05 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 18 Oct 2020 17:22:05 +0100 Subject: [Tutor] Slicing index In-Reply-To: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B@yahoo.com> References: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B.ref@yahoo.com> <96456A2E-9598-4E3B-B6BC-2D1055A1F94B@yahoo.com> Message-ID: On 18/10/2020 13:57, Carlene Wong via Tutor wrote: > Hello, I?m new but I?m getting trouble with slicing an index into another. > Eg. Def mysentence (sentence, old, new) This will fail with a syntax error as 'Def' is wrong. > If old in sentence[-4:]: Fix the 'Def' and this looks for 'old' starting 4 characters from the end of 'v'. > n= sentence.index(old) Fix the indentation and this finds the index of 'old' > newsent=Sentence [:n]+new This will fail as 'Sentence' does not exist. Fix that and I think you'll get what you want, I'm feeling too lazy to try it for myself. > return newsent Fix all the above and you'll get here eventually. > return mysentence I'll assume that you mean to return the original 'sentence' here if you don't take the 'if' path. > print(mysentence(?Hello there, it?s raining cats and cats?, ? cats?, ? dogs?) > > It keeps printing > Hello there, it?s raining dogs No it doesn't, see all the above problems. Having said that for this sort of problem I'd probably look at string methods https://docs.python.org/3/library/stdtypes.html#string-methods rather than slicing. > > Your help > > Sent from my iPhone > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at gmail.com Sun Oct 18 14:31:19 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sun, 18 Oct 2020 19:31:19 +0100 Subject: [Tutor] Slicing index In-Reply-To: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B@yahoo.com> References: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B.ref@yahoo.com> <96456A2E-9598-4E3B-B6BC-2D1055A1F94B@yahoo.com> Message-ID: On 18/10/2020 13:57, Carlene Wong via Tutor wrote: > Hello, I?m new but I?m getting trouble with slicing an index into another. > Eg. Def mysentence (sentence, old, new) > If old in sentence[-4:]: > n= sentence.index(old) > newsent=Sentence [:n]+new > return newsent > return mysentence > print(mysentence(?Hello there, it?s raining cats and cats?, ? cats?, ? dogs?) > > It keeps printing > Hello there, it?s raining dogs No it doesn't, you'd fail at the 'Def' with an invalid syntax error and there's a colon missing at the end of the line. Having said that looking at what you're trying to achieve why bother with string slicing, why not the string 'replace' method https://docs.python.org/3/library/stdtypes.html#str.replace ? > > Your help > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From chrisloy9829 at gmail.com Sun Oct 18 11:42:00 2020 From: chrisloy9829 at gmail.com (Christopher Loy) Date: Sun, 18 Oct 2020 10:42:00 -0500 Subject: [Tutor] python tutorial issue Message-ID: I?m currently on mac with python running python in terminal going through the tutorial off of the website python.org. https://docs.python.org/3/tutorial/controlflow.html on the control flow of the python part 4.6 doing the example every time I try to do the example on python part of the terminal I?m getting a Syntaxerror: invalid syntax on the equals sign on print on line 5 of the code. I could not figure out the issue trying different ways of typing but i have it typed as so def fib(n): # write Fibonacci series up to n ???Print a Fibonacci series up to n.??? a, b= 0, 1 while a < n: print(a, end=? ?) after I hit enter for this line it gives me a syntax error on the equals sign?. What could I be doing wrong. Please help thank you. Christopher Loy From alan.gauld at yahoo.co.uk Sun Oct 18 15:02:42 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 18 Oct 2020 20:02:42 +0100 Subject: [Tutor] Nested list comprehensions In-Reply-To: References: Message-ID: On 18/10/2020 14:08, Manprit Singh wrote: > def two_d(row, col, ele): > return [[ele for _ in range(col)] for _ in range(row)] > > > x = two_d(3, 5, 8) > print(x) > > and got the same answer . See here the nested comprehension is quite clear > to read, I suspect that's only because it was you who wrote it. Personally I find it about the same as the example from the tutorial. They are almost identical in form. -- 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 joel.goldstick at gmail.com Sun Oct 18 15:15:46 2020 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 18 Oct 2020 15:15:46 -0400 Subject: [Tutor] Clearing the screen from the terminal In-Reply-To: References: Message-ID: On Sun, Oct 18, 2020 at 2:37 PM Cranky Frankie wrote: > > Is there a way, before I run my Python program in command/terminal mode (no > GUI), to clear the screen before the program starts? If so, can it be done > while the program is running as well? type clear at the command prompt before running > > Frank L. "Cranky Frankie" Palmeri, Risible Riding Raconteur & Writer > WORK Hard - PLAY Hard - READ Hard - THINK Hard > _______________________________________________ > 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 alan.gauld at yahoo.co.uk Sun Oct 18 15:18:04 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 18 Oct 2020 20:18:04 +0100 Subject: [Tutor] Clearing the screen from the terminal In-Reply-To: References: Message-ID: On 18/10/2020 19:36, Cranky Frankie wrote: > Is there a way, before I run my Python program in command/terminal mode (no > GUI), to clear the screen before the program starts? If so, can it be done > while the program is running as well? The problem is that there are literally hundreds of terminals (and terminal emulators) out there and they all use different control codes to clear the screen. There are two easy ways to do this: import os def clear(): os.system('clear') # if its a *nix based system OR def clearscreen(size = 25): print '\n' * size Fast enough for normal human use. The first leaves your cursor at the top. The second it's at the bottom. The "correct" way of doing screen control in a terminal (as used by vim and the top commands etc) is to use the curses module. Curses provides screen and cursor control regardless of terminal type. But that introduces a whole extra layer of complexity (along with power). For example regular print() and input() fuctions won't work, you need to use curses own equivalents. A minimal curses program to clear the screen is: import curses def main(win): # win refers to the terminal screen. win.clear() # your program here.... curses.wrapper(main) See my tutorial topic on "Event Driven Programming" for a little more info on curses (and read the official docs of course). -- 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 PyTutor at DancesWithMice.info Sun Oct 18 15:23:24 2020 From: PyTutor at DancesWithMice.info (dn) Date: Mon, 19 Oct 2020 08:23:24 +1300 Subject: [Tutor] (no subject) In-Reply-To: References: <23EF7BBD-2E34-4C5A-863C-6EB57228661B@hxcore.ol> Message-ID: On 19/10/2020 00:34, Alan Gauld via Tutor wrote: > On 18/10/2020 08:58, Aliyan Navaid wrote: >> I want to write a program which list ALL the errors while entering a user >> name. >> >> (If I use if elif blocks the program will end at the first error it >> catches) > > You have just answered your own question. > Stop using elif clauses. Just use if. > > hasErrors = False > if characters < 3: > ??? print(?Username too short?) > hasErrors = True > if characters > 50: > ??? print(?Username too long?) > hasErrors = Trueif special_characters: > ??? print(?Special characters not allowed?) > hasErrors = True > if not hasErrors: > print(?Username is valid?) > > if hasErrors: # Now do something to recover! > > > But it must be said that its an unusual strategy. > Most programs detect the first error and stop. There is an advert on (local) TV, mocking the situation where I'd prefer that the above/usual case not apply: Two 'wild west' cowboys are apparently being chased, and the bullets are flying. They reach what they think will be the safety of the barricaded farm-house and desperately demand to be allowed to enter. "What's the password?" comes back. They guess. "It has a number in it" is the unsympathetic response. Next time around, there's some other requirement. All the while the bullets are flying... Apparently, that is the time one takes a break to eat a Kit-Kat (a chocolate bar - with the advertising jingle "have a break, have a Kit-Kat). How many times have I been asked to select a password, and some wise-guy at the web-site has decided that (s)he will enforce the use of "strong passwords"? (for some definition of "strong") Yet, (s)he doesn't think to communicate all of these requirements up-front - minimum length, must have at least one letter/digit, must include a "special character", must be able to shoot coders who fail to communicate... Per the OP's use-case, listing all* of my (supposed) transgressions at once would reduce frustration, if not my chocolate intake! * "all" being those relating (only) to this password selection task - "all" would take much too long! PS I'm on-vacation, so I'm eating whatever I want... Jokes aside, haven't we discussed this before? Question: are the criteria all dependent upon a single value or factor, eg into which (statistical) "bucket" or category does my age fit? (child, youth, adult, old-f...) Alternately, if there are several independent factors (password-length, content-characters), might fitting test-data into a "decision table" help to clarify (all!) the various possible combinations of 'inputs' and their corresponding 'outputs'? ie it is not really a coding problem, but rules and logic? (which should be clarified before fingers touch keyboard!) -- Regards =dn From alan.gauld at yahoo.co.uk Sun Oct 18 15:20:23 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 18 Oct 2020 20:20:23 +0100 Subject: [Tutor] python tutorial issue In-Reply-To: References: Message-ID: On 18/10/2020 16:42, Christopher Loy wrote: > I?m currently on mac with python running python in terminal going through the tutorial off of the website python.org. https://docs.python.org/3/tutorial/controlflow.html on the control flow of the python part 4.6 doing the example every time I try to do the example on python part of the terminal I?m getting a Syntaxerror: invalid syntax on the equals sign on print on line 5 of the code. I could not figure out the issue trying different ways of typing but i have it typed as so > > def fib(n): # write Fibonacci series up to n > ???Print a Fibonacci series up to n.??? > a, b= 0, 1 > while a < n: > print(a, end=? ?) I think the problem is the quote signs. They are not the regular ASCII versions but the fancy kind you use in a word processor. What are you using to type the code? Is it a simple text editor or a word processor? It should be the former for programming - well, not necessarily simple but a plain text editor at least! -- 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 Sun Oct 18 15:22:30 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 18 Oct 2020 20:22:30 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: <23EF7BBD-2E34-4C5A-863C-6EB57228661B@hxcore.ol> Message-ID: On 18/10/2020 12:34, Alan Gauld via Tutor wrote: > hasErrors = False > if characters < 3: > ??? print(?Username too short?) > hasErrors = True > if characters > 50: > ??? print(?Username too long?) > hasErrors = True if special_characters: > ??? print(?Special characters not allowed?) > hasErrors = True Oops, formatting error, sorry. -- 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 Sun Oct 18 15:25:27 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 18 Oct 2020 20:25:27 +0100 Subject: [Tutor] (no subject) In-Reply-To: <9039dad7-1d3f-040b-ff0e-54c2d3618da9@web.de> References: <23EF7BBD-2E34-4C5A-863C-6EB57228661B@hxcore.ol> <9039dad7-1d3f-040b-ff0e-54c2d3618da9@web.de> Message-ID: On 18/10/2020 18:42, Sibylle Koczian wrote: > Am 18.10.2020 um 13:34 schrieb Alan Gauld via Tutor: >> On 18/10/2020 08:58, Aliyan Navaid wrote: >>> I want to write a program which list ALL the errors while entering a user >>> name. > Exception: if two conditions can't both be true, but can both be false, > as the two first conditions here. In this case I'd leave the elif in. That complicates things with two different styles. If the OP wants to be sure ALL errors are printed simple ifs are more reliable. But of course you can get all sorts of complexity where two conditions are bnoth required and only having one is an error. Then you need compound tests etc. Here be dragons! Let the programmer beware! -- 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 PyTutor at DancesWithMice.info Sun Oct 18 15:51:38 2020 From: PyTutor at DancesWithMice.info (dn) Date: Mon, 19 Oct 2020 08:51:38 +1300 Subject: [Tutor] Slicing index In-Reply-To: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B@yahoo.com> References: <96456A2E-9598-4E3B-B6BC-2D1055A1F94B.ref@yahoo.com> <96456A2E-9598-4E3B-B6BC-2D1055A1F94B@yahoo.com> Message-ID: On 19/10/2020 01:57, Carlene Wong via Tutor wrote: > Hello, I?m new but I?m getting trouble with slicing an index into another. > Eg. Def mysentence (sentence, old, new) > If old in sentence[-4:]: > n= sentence.index(old) > newsent=Sentence [:n]+new > return newsent > return mysentence > print(mysentence(?Hello there, it?s raining cats and cats?, ? cats?, ? dogs?) > > It keeps printing > Hello there, it?s raining dogs (adding to other replies) Some have suggested (IMHO: better) approaches other than slicing. Assuming your assignment is to learn how to use "slicing", don't change methods part-way (by using string.index() )! 0 start with sentence 1 grab the last four characters into a new string: in sentence[ -4: ] 2 similarly, use the same structure if the sentence is to be changed: sentence[ :-4 ] + new Yes, please copy-paste from the Python interpreter/REPL (or editor/IDE) the source code, the full error and "stack trace", plus relevant i/p and o/p - also, the text of the assignment/problem. (so, (see "Assuming" above) that we can help you learn the particular technique that the course is covering today!) Advanced coding technique: - notice how the "-4" appears twice (in the suggested solution, above) - if we wanted to re-use the code to handle tigers, we now need to examine more than the last four characters! (did I say "advanced"? Handling cats is tricky, but handling tigers is dangerous!) - how many times would we have to make changes to the code? - what are the chances we would 'forget' and only make one change? So, it is a good idea to 'parameterise' such values, eg suffix_length = -4 ... in sentence[ suffix_length: ] ... sentence[ :suffix_length ] + new Now, we would only have to change the "control" once, to handle cats of any size and length of claws! -- Regards =dn From rzzzwilson at gmail.com Sun Oct 18 20:29:01 2020 From: rzzzwilson at gmail.com (Ross Wilson) Date: Mon, 19 Oct 2020 07:29:01 +0700 Subject: [Tutor] python tutorial issue In-Reply-To: References: Message-ID: On 18/10/2563 BE 22:42, Christopher Loy wrote: > def fib(n): # write Fibonacci series up to n > ???Print a Fibonacci series up to n.??? > a, b= 0, 1 > while a < n: > print(a, end=? ?) Assuming that all the funny characters in your post were NOT in your code... You appear to be using python 2 which is the standard python that is installed on a Mac.? You can check this by executing this in your terminal: ??? python -V If you want to run python 3 you need to install it.? Go to python.org and select "Downloads" from the menu bar and install the PKG file.? Then you need to use "python3" on the command line to actually execute python3.? Do this to check the version of the new python: ??? python3 -V From alan.gauld at yahoo.co.uk Mon Oct 19 04:42:02 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 19 Oct 2020 09:42:02 +0100 Subject: [Tutor] python tutorial issue In-Reply-To: References: Message-ID: On 19/10/2020 01:29, Ross Wilson wrote: > On 18/10/2563 BE 22:42, Christopher Loy wrote: >> def fib(n): # write Fibonacci series up to n >> ???Print a Fibonacci series up to n.??? >> a, b= 0, 1 >> while a < n: >> print(a, end=? ?) > > Assuming that all the funny characters in your post were NOT in your code... I'm seeing the "funny characters" as slanted quote signs. Hence my reply, but... > You appear to be using python 2 which is the standard python that is > installed on a Mac.? You can check this by executing this in your terminal: Good catch. Its so long since I used Python 2 that I'd forgotten that the named parameters were added in v3. I think you've got the answer. To the OP; if you had posted the full error message we would have seen that in the first line of the text. Please always post error messages in full. -- 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 shubhamsinghlmp578 at gmail.com Mon Oct 19 06:44:22 2020 From: shubhamsinghlmp578 at gmail.com (Shubham Singh 103) Date: Mon, 19 Oct 2020 16:14:22 +0530 Subject: [Tutor] Asking question . Message-ID: How to build games in python ? From adameyring at gmail.com Mon Oct 19 09:18:00 2020 From: adameyring at gmail.com (Adam Eyring) Date: Mon, 19 Oct 2020 09:18:00 -0400 Subject: [Tutor] Asking question . In-Reply-To: References: Message-ID: Try: pygame.org https://arcade.academy/ https://inventwithpython.com/invent4thed/ http://inventwithpython.com/pygame/ On Mon, Oct 19, 2020 at 9:15 AM Shubham Singh 103 < shubhamsinghlmp578 at gmail.com> wrote: > How to build games in python ? > _______________________________________________ > 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 Oct 19 09:20:45 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 19 Oct 2020 14:20:45 +0100 Subject: [Tutor] Asking question . In-Reply-To: References: Message-ID: On 19/10/2020 11:44, Shubham Singh 103 wrote: > How to build games in python ? To some extent it depends on what kind of games you want to build. Basically its the same as building games in any language. You'd need to be more specific about what you need to know if you want more detail. There is however a package designed for games that gives access to extra graphics and multimedia tools called PyGame. There is an active support forum where you will find many more people actively writing games in Python, I'm sure they will be able to answer any more specific questions you may have. https://www.pygame.org/wiki/info -- 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 manpritsinghece at gmail.com Mon Oct 19 19:19:51 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Tue, 20 Oct 2020 04:49:51 +0530 Subject: [Tutor] Possible usage of dict comprehensions Message-ID: Dear sir , Assume I am using Python 3.7 or later, in which dictionary insertion order is maintained. If I want to remove duplicates from a list while maintaining the order of its elements, doing like this is a valid and a useful use case ? >>> l = [2, 4, 5, 3, 4, 5, 2, 1] # List whose duplicates have to be removed >>> list({i:None for i in l}) [2, 4, 5, 3, 1] # Resultant list with duplicates removed , order preserved Regards Manprit Singh From mats at wichmann.us Mon Oct 19 19:36:38 2020 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 19 Oct 2020 17:36:38 -0600 Subject: [Tutor] Possible usage of dict comprehensions In-Reply-To: References: Message-ID: <2df58a18-08f3-fdbe-4f33-d1048a10f03b@wichmann.us> On 10/19/20 5:19 PM, Manprit Singh wrote: > Dear sir , > > Assume I am using Python 3.7 or later, in which dictionary insertion order > is maintained. If I want to remove duplicates from a list while maintaining > the order of its elements, doing like this is a valid and a useful use case > ? > >>>> l = [2, 4, 5, 3, 4, 5, 2, 1] # List whose duplicates have to be > removed >>>> list({i:None for i in l}) > [2, 4, 5, 3, 1] # Resultant list with duplicates removed > , order preserved Yes, but note that what you have written exists as the fromkeys() method already: list(dict.fromkeys(I)) You can fall back to a dict comprehension if you want the values to not all be the same object, but since you don't care about the values, fromkeys is fine. From alan.gauld at yahoo.co.uk Mon Oct 19 19:42:36 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 20 Oct 2020 00:42:36 +0100 Subject: [Tutor] Possible usage of dict comprehensions In-Reply-To: References: Message-ID: On 20/10/2020 00:19, Manprit Singh wrote: > is maintained. If I want to remove duplicates from a list while maintaining > the order of its elements, doing like this is a valid and a useful use case >>>> l = [2, 4, 5, 3, 4, 5, 2, 1] # List whose duplicates have to be > removed >>>> list({i:None for i in l}) > [2, 4, 5, 3, 1] # Resultant list with duplicates removed > , order preserved Well you have demonstrated that it works so it must be valid. How useful it is depends on whether you need to perform that operation. Assuming you do then yes its useful. It's probably fairly efficient too but I haven't timed 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 manpritsinghece at gmail.com Tue Oct 20 01:15:06 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Tue, 20 Oct 2020 10:45:06 +0530 Subject: [Tutor] function call inside generator expression Message-ID: Dear sir , Consider an example where I have to print only those items from the old existing list whose sum of digits is equals or greater than 13. The code is given below: def sum_digit(x): m = x tot = 0 while m != 0: m, r = divmod(m, 10) tot = tot + r return tot l = [23, 47, 42, 98, 65, 91, 66, 58, 21, 49, 34, 69] lst_flt = (i for i in l if sum_digit(i) >= 13) print(*lst_flt) The output is : 98 58 49 69 Which is the right answer. So as you can see i have used sum_digit(i) >= 13 inside the generator expression, which is a function call. It is ok to use function calls inside generator expressions and comprehensions in the way as given above . I have one more question. If you can see the function definition, you can found that i have done m = x, reason for doing this is actually i do not have the habit to modify the formal parameter of the function definition. Now here x is immutable , modifying m inside definition will not have any effect on x. If the function was made to accept a list, i would have made a shallow copy of list by doing y = x[:] and then have performed any action on y to get the result so that the list passed to formal parameter does not get affected. Need your sincere suggestion on this point. Secondarily if there is any other efficient way to implement it ? Regards Manprit Singh From breamoreboy at gmail.com Mon Oct 19 20:34:48 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Tue, 20 Oct 2020 01:34:48 +0100 Subject: [Tutor] Possible usage of dict comprehensions In-Reply-To: References: Message-ID: On 20/10/2020 00:42, Alan Gauld via Tutor wrote: > On 20/10/2020 00:19, Manprit Singh wrote: >> is maintained. If I want to remove duplicates from a list while maintaining >> the order of its elements, doing like this is a valid and a useful use case > >>>>> l = [2, 4, 5, 3, 4, 5, 2, 1] # List whose duplicates have to be >> removed >>>>> list({i:None for i in l}) >> [2, 4, 5, 3, 1] # Resultant list with duplicates removed >> , order preserved > > Well you have demonstrated that it works so it must be valid. > How useful it is depends on whether you need to perform that operation. > Assuming you do then yes its useful. > > It's probably fairly efficient too but I haven't timed it. > Plenty of background here https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From la_spirou at hotmail.com Mon Oct 19 19:56:45 2020 From: la_spirou at hotmail.com (P L) Date: Mon, 19 Oct 2020 23:56:45 +0000 Subject: [Tutor] Format problem Message-ID: Hello, I'm currently doing the Google Coursera python program and I have a question in regard to the code below. I'm not sure why the __str__(self) is not working as intended. All my outputs are not at the nearest hundredth. Thanks for your time. import random class Server: def __init__(self): """Creates a new server instance, with no active connections.""" self.connections = {} def add_connection(self, connection_id): """Adds a new connection to this server.""" # Add the connection to the dictionary with the calculated load connection_load = random.random()*10+1 self.connections[connection_id]= connection_load def close_connection(self, connection_id): """Closes a connection on this server.""" # Remove the connection from the dictionary del self.connections[connection_id] def load(self): """Calculates the current load for all connections.""" # Add up the load for each of the connections total = 0 for connect in self.connections.values(): total += connect return total def __str__(self): """Returns a string with the current load of the server""" return "{:.2f}%".format(self.load()) server = Server() server.add_connection("192.168.1.1") print(server.load()) From alan.gauld at yahoo.co.uk Tue Oct 20 05:37:30 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 20 Oct 2020 10:37:30 +0100 Subject: [Tutor] function call inside generator expression In-Reply-To: References: Message-ID: On 20/10/2020 06:15, Manprit Singh wrote: > lst_flt = (i for i in l if sum_digit(i) >= 13) > print(*lst_flt) > > The output is : > 98 58 49 69 > > Which is the right answer. So as you can see i have used sum_digit(i) >= 13 > inside the generator expression, which is a function call. It is ok to use > function calls inside generator expressions and comprehensions in the way as As we have told you many times if the interpreter accepts it then it is OK. The interpreter is the definitive answer to whether things are OK to use. As I said in a recent post the structure of a GE is: [ ] The expressions can be as arbirtrarily compex as you wish to make them, Python does not care. You can call functions, create objects, nest expressions. have as many compound expressions as you like. It makes no difference to Python. Whether you (or your colleagues) will be able to read or maintain them in 6 months time is quite another matter. > I have one more question. If you can see the function definition, you can > found that i have done m = x, reason for doing this is actually i do not > have the habit to modify the formal parameter of the function definition. Except that m and x are the same thing. They are both just names that refer to the same object. > Now here x is immutable , modifying m inside definition will not have > any effect on x. That is correct because you will be assigning a new object to m so it will no longer be referencing the same object as x. > If the function was made to accept a list, i would have> made a shallow copy of list by doing y = x[:] and then have performed any > action on y to get the result so that the list passed to formal parameter> does not get affected. Need your sincere suggestion on this point. What you describe is normal practice. If you get an immutable object you might as well use it since you can't change it. If you get a mutable object and don;t want to change the original you must make a copy, you have no choice. It all depends on what you want to achieve. If you are going to assign the modified object back the argument at some point you may as well use the original (and save a lot of copying) but if you want to end up with both objects then you must make a copy. But you say you'd make a shallow copy. That may not be enough, it may need to be a deep copy, depending on what you are doing. Consider: L1 = [1,2,3] L2 = [4,5,6] def f(L): Lt = L[:] # shallow copy lt[0].append(7) return Lt L3 = f([L1,L2] # L1 is still modified despite the shallow copy > Secondarily if there is any other efficient way to implement it ? Implement what? Your original GE?, the function? Or do you mean can we avoid doing the shallow copy? -- 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 Oct 20 06:15:45 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 20 Oct 2020 11:15:45 +0100 Subject: [Tutor] Format problem In-Reply-To: References: Message-ID: On 20/10/2020 00:56, P L wrote: > I'm not sure why the __str__(self) is not working as intended. > All my outputs are not at the nearest hundredth. You never call the __str__() method so how do you know it is not working? > import random > > class Server: > def __init__(self): > def add_connection(self, connection_id): > def close_connection(self, connection_id): > def load(self): > def __str__(self): > > server = Server() > server.add_connection("192.168.1.1") > print(server.load()) You print the result of load() you never print server. To call __str__ you'd need a line like: print(server) 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 manpritsinghece at gmail.com Tue Oct 20 11:06:22 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Tue, 20 Oct 2020 20:36:22 +0530 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: Dear sir , I have written some code for the same problem . Need your comments on the efficiency of this code : l = [2, 3, 3, 3, 6, 6, 7, 7, 3, 2, 2, 2, 9, 6] it = iter(l) ini = next(it) print(ini) for i in it: if i != ini: print(i) ini = i It removes all consecutive duplicates . I am getting the correct answer See if you remember, we had a discussion on when to use None or object() for a variable that was initialized in the beginning of for loop . This code eliminated the need for the same . Need your comments on the efficiency of this code . Regards Manprit singh On Fri, Oct 9, 2020 at 9:07 PM Manprit Singh wrote: > Dear sir, > > Consider a list as given below : > > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > I need to print the values as given below and in same order: > > 3 # print 3 only once as there are two occurrence of 3 in the > beginning in list > 5 # print 5 only once as there are 3 occurrence of 5 after 3 in the > list > 6 # print 6 only once as there are 3 occurrence of 6 after 5 in the > list > 5 # print 5 only once as there is single occurrence of 5 after 6 in > the list > 9 # print 9 only once as there is single occurrence of 9 after 5 in > the list > 3 # print 3 only once as there are 3 occurrence of 3 after 9 in the > list > 5 # print 5 only once as there are 2 occurrence of 5 in the last > > I have written the code as given below: > lst = [3, 3, 5, 5, 5, 6, 6, 6, 5, 9, 3, 3, 3, 5, 5] > for i, j in enumerate(lst[:-1]): > if lst[i+1] != j: > print(j) > print(lst[-1]) > > which gives the answer as given above > I feel that a better code can be written for this problem , Need your > guidance. > > Regards > Manprit singh > > > From alan.gauld at yahoo.co.uk Tue Oct 20 12:32:44 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 20 Oct 2020 17:32:44 +0100 Subject: [Tutor] Format problem In-Reply-To: References: Message-ID: Please always reply to the list using ReplyAll or ReplyList according to your mail program. On 20/10/2020 15:07, P L wrote: > I thought by server=Server() would make it call the __str__ No, __str__() is the function called any time Python has to convert your server instances to a string. The main use of that being when we call print() - because print converts all its arguments to str(). > So that means I have to directly put the __str__ in the > variable instance load(). No, that would result in load have strings to deal with but it uses numbers and that's how it should be! > I'm not sure how to format my output total to two decimals. You have done it correctly, you just aren't using it because you are not printing a server object. -- 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 Oct 20 12:59:33 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 20 Oct 2020 17:59:33 +0100 Subject: [Tutor] Duplicate items in list In-Reply-To: References: Message-ID: <360fa8b8-b654-f114-ea56-79d295daaba8@yahoo.co.uk> On 20/10/2020 16:06, Manprit Singh wrote: > I have written some code for the same problem . Need your comments on the > efficiency of this code : > > l = [2, 3, 3, 3, 6, 6, 7, 7, 3, 2, 2, 2, 9, 6] > it = iter(l) > ini = next(it) > print(ini) > for i in it: > if i != ini: > print(i) > ini = i This is you basically doing the for loops work for it! There is a much simpler way to do this: L = [2, 3, 3, 3, 6, 6, 7, 7, 3, 2, 2, 2, 9, 6] prev = L[0] print(prev) for n in L[1:]: ??? if prev != n: ??????? print(n) ??????? prev = n No need to create iterators(the list is already iterable). > Need your comments on the efficiency of this code . No, you don't. As we have repeatedly said, use the interpreter. It will tell you which is most efficient. Put the code you want to compare into two functions. Then use the timeit module to run both functions and see which is faster - ie. more efficient. Then read again the advice about efficiency being less important than readability in 99% of cases! >>> def f(): ??? p = L[0] ??? res = [p] ??? for n in L[1:]: ??? ??? if res[-1] != n: ??? ??? ??? res.append(n) ??? return res >>> import timeit as t >>> t.timeit(f) 1.8774931590305641 If you similarly define your previous code as g() you can compare the timings. That way we don't need to guess or rely on anecdotal evidence, we can measure the results. -- 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 manpritsinghece at gmail.com Thu Oct 22 03:21:42 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Thu, 22 Oct 2020 12:51:42 +0530 Subject: [Tutor] For loop with break & else Message-ID: Dear sir , consider a problem where there is a for loop with break and else: for i in range(2, y): if cond: break else : do_something( ) in this pattern, let 's say if y is a user input. and at a particular time the user inputs the value of y equals to 2 . At that time, the "else" part will be executed or not ? Regards Manprit singh From alan.gauld at yahoo.co.uk Thu Oct 22 04:20:16 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 22 Oct 2020 09:20:16 +0100 Subject: [Tutor] For loop with break & else In-Reply-To: References: Message-ID: On 22/10/2020 08:21, Manprit Singh wrote: > Dear sir , > > consider a problem where there is a for loop with break and else: > > for i in range(2, y): > if cond: > break > else : > do_something( ) > > in this pattern, let 's say if y is a user input. and at a particular time > the user inputs the value of y equals to 2 . At that time, the "else" > part will be executed > or not ? Why not just ask the interpreter? >>> def f(y): i = 0 for i in range(2,y): if i > 10: break else: print('in else') return i >>> f(2) in else 0 >>> Apparently the answer is yes. -- 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 gadfum at gmail.com Wed Oct 21 19:07:19 2020 From: gadfum at gmail.com (gad fum) Date: Wed, 21 Oct 2020 19:07:19 -0400 Subject: [Tutor] pygame Message-ID: Im a beginner and im watching a lot of tutorials there's one that I really liked it is about creating a pygame for beginners, I chose falppy bird. So I started and the first step was to install a pygame. It told me to go on Command Prompt and write this:py -m pip install pygame. I did that but its giving me this message: ERROR: Command errored out with exit status 1: command: 'C:\Users\user\Documents\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-fbs2xk25\\pygame\\setup.py'"'"'; __file__='"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-fbs2xk25\\pygame\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\user\AppData\Local\Temp\pip-pip-egg-info-wmjnlqip' cwd: C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\ Complete output (17 lines): WARNING, No "Setup" File Exists, Running "buildconfig/config.py" Using WINDOWS configuration... Download prebuilts to "prebuilt_downloads" and copy to "./prebuilt-x64"? [Y/n]Traceback (most recent call last): File "", line 1, in File "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\setup.py", line 194, in buildconfig.config.main(AUTO_CONFIG) File "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\config.py", line 210, in main deps = CFG.main(**kwds) File "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\config_win.py", line 576, in main and download_win_prebuilt.ask(**download_kwargs): File "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\download_win_prebuilt.py", line 302, in ask reply = raw_input( EOFError: EOF when reading a line ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. So would anybody know what this means.Thx for all help.:) From alan.gauld at yahoo.co.uk Thu Oct 22 06:48:47 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 22 Oct 2020 11:48:47 +0100 Subject: [Tutor] pygame In-Reply-To: References: Message-ID: On 22/10/2020 00:07, gad fum wrote: > Command Prompt and write this:py -m pip install pygame. I did that but its > giving me this message: There are a couple of oddities in this. The first is that you seem to be using Python v2 but that is out of support so you really should be using Python v3 (although I'm not sure if pygame supports v3?!) The other thing is that you appear to have Python installed in your Documents folder which is not the usual place... Beyond that I'm not sure what the error is indicating. Perhaps you could try the pygame forum, I'm guessing they will be more au-fait with pygame install niggles than we are. > ERROR: Command errored out with exit status 1: > > command: 'C:\Users\user\Documents\python.exe' -c 'import sys, setuptools, > tokenize; sys.argv[0] = > '"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-fbs2xk25\\pygame\\setup.py'"'"'; > __file__='"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-fbs2xk25\\pygame\\setup.py'"'"';f=getattr(tokenize, > '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', > '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' > egg_info --egg-base > 'C:\Users\user\AppData\Local\Temp\pip-pip-egg-info-wmjnlqip' > > cwd: C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\ > > Complete output (17 lines): ... > File > "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\download_win_prebuilt.py", > line 302, in ask > > reply = raw_input( > > EOFError: EOF when reading a line > > ---------------------------------------- > > ERROR: Command errored out with exit status 1: python setup.py egg_info > Check the logs for full command output. -- 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 bouncingcats at gmail.com Thu Oct 22 08:38:36 2020 From: bouncingcats at gmail.com (David) Date: Thu, 22 Oct 2020 23:38:36 +1100 Subject: [Tutor] pygame In-Reply-To: References: Message-ID: On Thu, 22 Oct 2020 at 21:49, Alan Gauld via Tutor wrote: > There are a couple of oddities in this. > The first is that you seem to be using Python v2 but that is > out of support so you really should be using Python v3 > (although I'm not sure if pygame supports v3?!) Looks like pygame can be built for either Python 2 or Python 3. There are current Debian packages for each. (I've never used pip). https://www.pygame.org/wiki/GettingStarted says: "Use python 3.7.7 or greater" and https://www.pygame.org/wiki/GettingStarted#Windows%20installation says: "Make sure you install python3.6" From johnf at jfcomputer.com Thu Oct 22 09:55:05 2020 From: johnf at jfcomputer.com (john fabiani) Date: Thu, 22 Oct 2020 06:55:05 -0700 Subject: [Tutor] pygame In-Reply-To: References: Message-ID: <87883160-018b-cc4a-623d-79e5b7e9f507@jfcomputer.com> This person appears to be using windows.? There is a 'C:\' in the error message. Johnf On 10/22/20 5:38 AM, David wrote: > On Thu, 22 Oct 2020 at 21:49, Alan Gauld via Tutor wrote: > >> There are a couple of oddities in this. >> The first is that you seem to be using Python v2 but that is >> out of support so you really should be using Python v3 >> (although I'm not sure if pygame supports v3?!) > Looks like pygame can be built for either Python 2 or > Python 3. There are current Debian packages for each. > (I've never used pip). > > https://www.pygame.org/wiki/GettingStarted > says: "Use python 3.7.7 or greater" > > and > https://www.pygame.org/wiki/GettingStarted#Windows%20installation > says: "Make sure you install python3.6" > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From johnf at jfcomputer.com Thu Oct 22 09:59:09 2020 From: johnf at jfcomputer.com (john fabiani) Date: Thu, 22 Oct 2020 06:59:09 -0700 Subject: [Tutor] pygame In-Reply-To: References: Message-ID: Pygame can be download and installed via 'exe'.? Please take a look at: https://www.pygame.org/download.shtml About the middle you will see some windows install files.? Just pick the right one for your python install. Johnf On 10/21/20 4:07 PM, gad fum wrote: > Im a beginner and im watching a lot of tutorials there's one that I really > liked it is about creating a pygame for beginners, I chose falppy bird. So > I started and the first step was to install a pygame. It told me to go on > Command Prompt and write this:py -m pip install pygame. I did that but its > giving me this message: > > ERROR: Command errored out with exit status 1: > > command: 'C:\Users\user\Documents\python.exe' -c 'import sys, setuptools, > tokenize; sys.argv[0] = > '"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-fbs2xk25\\pygame\\setup.py'"'"'; > __file__='"'"'C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-fbs2xk25\\pygame\\setup.py'"'"';f=getattr(tokenize, > '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', > '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' > egg_info --egg-base > 'C:\Users\user\AppData\Local\Temp\pip-pip-egg-info-wmjnlqip' > > cwd: C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\ > > Complete output (17 lines): > > > > WARNING, No "Setup" File Exists, Running "buildconfig/config.py" > > Using WINDOWS configuration... > > > > Download prebuilts to "prebuilt_downloads" and copy to "./prebuilt-x64"? > [Y/n]Traceback (most recent call last): > > File "", line 1, in > > File > "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\setup.py", > line 194, in > > buildconfig.config.main(AUTO_CONFIG) > > File > "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\config.py", > line 210, in main > > deps = CFG.main(**kwds) > > File > "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\config_win.py", > line 576, in main > > and download_win_prebuilt.ask(**download_kwargs): > > File > "C:\Users\user\AppData\Local\Temp\pip-install-fbs2xk25\pygame\buildconfig\download_win_prebuilt.py", > line 302, in ask > > reply = raw_input( > > EOFError: EOF when reading a line > > ---------------------------------------- > > ERROR: Command errored out with exit status 1: python setup.py egg_info > Check the logs for full command output. > > So would anybody know what this means.Thx for all help.:) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From gmphelps at ualr.edu Thu Oct 22 13:02:21 2020 From: gmphelps at ualr.edu (Garrett Phelps) Date: Thu, 22 Oct 2020 12:02:21 -0500 Subject: [Tutor] Program help Message-ID: Perhaps someone can help me write this code: The USPopulation.txt file contains the midyear population of United States, in thousands, during the years 1950 through 1990. The first line in the file contains the population for 1950, the second line contains the population for 1951, and so forth. Create an application that reads the file's contents into a list. The application should do the following: - (15 points) Read the file into an list of integers (multiply by 1000) - Iterate through the array and display: - (10 points) Year - Population - (10 points) Change from previous year (subtract current year minus previous year) - (10 points) Percent change in population over last year (change in population divided by previous year population) - When complete, display the following based on the changes in population (not changes in percent): - (10 points) Average Population Change - (10 points) Minimum Population Change and Year - (10 points) Maximum Population Change and Year Best Regards, Garrett Phelps From mats at wichmann.us Thu Oct 22 18:43:56 2020 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 22 Oct 2020 16:43:56 -0600 Subject: [Tutor] Program help In-Reply-To: References: Message-ID: <71ec99d3-5f0a-d9c6-bc8b-a319ceef4b08@wichmann.us> On 10/22/20 11:02 AM, Garrett Phelps wrote: > Perhaps someone can help me write this code: We can... but since it looks like homework, we won't write it *for* you. Out of these things, what do you know how to do? What is proving problematic? > > The USPopulation.txt file contains the midyear population of United States, > in thousands, during the years 1950 through 1990. The first line in the > file contains the population for 1950, the second line contains the > population for 1951, and so forth. Create an application that reads the > file's contents into a list. The application should do the following: > > - (15 points) Read the file into an list of integers (multiply by 1000) > - Iterate through the array and display: > - (10 points) Year > - Population > - (10 points) Change from previous year (subtract current year minus > previous year) > - (10 points) Percent change in population over last year (change in > population divided by previous year population) > - When complete, display the following based on the changes in > population (not changes in percent): > - (10 points) Average Population Change > - (10 points) Minimum Population Change and Year > - (10 points) Maximum Population Change and Year > > Best Regards, > Garrett Phelps > _______________________________________________ > 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 Oct 22 18:47:14 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 22 Oct 2020 23:47:14 +0100 Subject: [Tutor] Program help In-Reply-To: References: Message-ID: On 22/10/2020 18:02, Garrett Phelps wrote: > Perhaps someone can help me write this code: We are happy to help but won't do it for you... So you need to show us your code and ask specific questions. If you get errors include the *full* error message not a summary. > The USPopulation.txt file contains the midyear population of United States, > in thousands, during the years 1950 through 1990. The first line in the > file contains the population for 1950, the second line contains the > population for 1951, and so forth. Create an application that reads the > file's contents into a list. The application should do the following: > > - (15 points) Read the file into an list of integers (multiply by 1000) Have you done this bit? > - Iterate through the array and display: > - (10 points) Year > - Population This should be straightforward, have you got it working? > - (10 points) Change from previous year (subtract current year minus > previous year) This is a bit harder but uses a similar approach to a recent thread about removing duplicates from a list, take a look in the archives. > - (10 points) Percent change in population over last year (change in > population divided by previous year population) If you got the last bit this is easy. > - When complete, display the following based on the changes in > population (not changes in percent): > - (10 points) Average Population Change > - (10 points) Minimum Population Change and Year > - (10 points) Maximum Population Change and Year This is slightly more tricky, you need to keep some running values But if you did that then its not too hard. Now, how far have you got? Which bits are sticking? Show us your 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 PyTutor at DancesWithMice.info Thu Oct 22 19:40:18 2020 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 23 Oct 2020 12:40:18 +1300 Subject: [Tutor] Program help In-Reply-To: References: Message-ID: On 23/10/2020 06:02, Garrett Phelps wrote: > Perhaps someone can help me write this code: Sure! > The USPopulation.txt file contains the midyear population of United States, > in thousands, during the years 1950 through 1990. The first line in the > file contains the population for 1950, the second line contains the > population for 1951, and so forth. Create an application that reads the > file's contents into a list. The application should do the following: > > - (15 points) Read the file into an list of integers (multiply by 1000) > - Iterate through the array and display: > - (10 points) Year > - Population > - (10 points) Change from previous year (subtract current year minus > previous year) > - (10 points) Percent change in population over last year (change in > population divided by previous year population) > - When complete, display the following based on the changes in > population (not changes in percent): > - (10 points) Average Population Change > - (10 points) Minimum Population Change and Year > - (10 points) Maximum Population Change and Year I have very mixed-feelings about the use of rubrics. On the one hand they are useful marking/grading aids, and help to justify an assessor's decisions in a semi-objective fashion (cf a subjective "I think your partial-effort is worth..."). On the other hand, there is a degree of 'solve the problem like this' and thus 'there is only one way to solve this problem'; whereas I prefer people to learn how to approach their 'homework' problems because that's preparation for what happens on-the-job. Generally-speaking, a competent assessment will be an opportunity for you to prove what you have just learned (mainly) and your ability to add that to what was learned earlier in the course. So, if you've just covered Python-lists, do you really need to be told to use them in the very next quiz? [rant over] Have you come-across the Python docs? (https://www.python.org/doc/). The "Tutorial" will have similar example-problems to the above. I find myself referring to the "Library Reference" frequently. Both are worth opening as tabs in your web-browser! Additionally, whilst I've been typing @Alan has also replied 'here', and you will find a web-ref to his tutorial at the foot of that message. Are you aware that the Python eco-system offers great ways to experiment with code and structures without needing to write whole programs? On my system (likely differs from yours) I open a "terminal", fire-up Python, and can immediately test my solutions, eg <<< dn $ ... python Python 3.8.5 (default, Aug 12 2020, 00:00:00) [GCC 10.2.1 20200723 (Red Hat 10.2.1-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x = 2 >>> y = 3 >>> x + y 5 >>> print( x + y ) 5 >>> z = x + y >>> print( z ) 5 >>> I didn't need to start pointing at successive fingers on my hands to answer the question - Python tells me the answer! Notice three ways to 'see' the answer. If you use PyCharm or similar IDE, they usually enable a built-in "command line" or Python environment. Alternately, you will find various on-line 'fiddles' and REPLs (defined: https://pythonprogramminglanguage.com/repl/), of which I heartily recommend Philip Guo's pythontutor.com because it will also help when you want to 'see' what happens to your data and act as a "debugger" when you reach such topics. Aside from my comments, you have been given a rubric which acts as a useful guide, so let's use it! How does one open a file? Will you read its data one record/line at a time, or given that it is so short, read the whole file with one command? If the former, how does one take the record and add it to a list? If the latter, is there are string/list function which will break-up the single string into a list of elements. NB Python (itself) does not have an "array" data-structure! There's a 'gotcha' in the midst of all this. Are the years/dates strings or numbers? Are the population-values strings or numbers? (read the docs, and experiment in your REPL) It is not crystal-clear, above, if the year is part of the incoming data. It would appear not. If not, how will you relate "1950" to the first-read data-item? There are a couple of approaches to this, but we don't know your level of Python knowledge. You may think to calculate the year, each time; or perhaps to construct a logically-linked list. (draw them side-by-side on a sheet of paper it you can't see what I mean) You need to be able to perform arithmetic to compare 1990's with 1989's population (for example) - did you solve the "gotcha" above? The next issue is how to "address" the 1989 data when you are 'looking at' 1990? The arithmetic I leave to you... (it's probably too difficult for me) Lastly, there are the aggregate analyses. You could partially compute or assemble these within the 'display' loop, above, finishing with some final-touches at this end. Alternately, you could look for Python functions in 'the docs' (per above), and find that Python will do most?all of it for you. Again, multiple solutions, depending mostly upon your level of Python knowledge/progress through the training course. As with all programming tasks, the "systems approach" is to break the 'big problem' into smaller component-problems (and them into ...) until each can be solved one-at-a-time. In your case, each sub-problem should be solved by experimenting with code in the REPL. Thereafter it is a simple matter (hah - easy for me to say!) of assembling all the small-solutions into 'the whole thing'! Without the benefit of your rubric, this is exactly how professionals approach their work-assignments - the only difference is how small the 'small problem' ("chunk") needs to become, before we start 'building'. So, start as suggested, and get back to us when you either have 'something', or you strike a coding problem. (in which case, copy-paste the code and any error-messages into your email - no attachments!) -- Regards =dn From nathan-tech at hotmail.com Thu Oct 22 18:16:56 2020 From: nathan-tech at hotmail.com (nathan tech) Date: Thu, 22 Oct 2020 23:16:56 +0100 Subject: [Tutor] Program help In-Reply-To: References: Message-ID: Hi Garrett This reads rather like a homework assignment! :) Here are some tips that I hope may help: think through what you need to do: 1. Load the data. 2. Do something with the data. 3. Display the data in some way. the first bit is quite easy: f=open("population.txt","r") data=f.read() f.close() data=data.split("\n") Convert it to numbers: for x in range(data): ?data[x]=int(data[x]) The rest is just some fancy footwork with a for loop like the one above and some organisation into variables depending on what you want to do with it. Hope this helps! Nathan On 22/10/2020 18:02, Garrett Phelps wrote: > Perhaps someone can help me write this code: > > The USPopulation.txt file contains the midyear population of United States, > in thousands, during the years 1950 through 1990. The first line in the > file contains the population for 1950, the second line contains the > population for 1951, and so forth. Create an application that reads the > file's contents into a list. The application should do the following: > > - (15 points) Read the file into an list of integers (multiply by 1000) > - Iterate through the array and display: > - (10 points) Year > - Population > - (10 points) Change from previous year (subtract current year minus > previous year) > - (10 points) Percent change in population over last year (change in > population divided by previous year population) > - When complete, display the following based on the changes in > population (not changes in percent): > - (10 points) Average Population Change > - (10 points) Minimum Population Change and Year > - (10 points) Maximum Population Change and Year > > Best Regards, > Garrett Phelps > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&data=04%7C01%7C%7C4ebacf3dddaf46f45fa708d876d0fbf3%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637389987231288846%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&sdata=AnQRyun6MqNQhcGAAMK%2BnLUPHn4fjgrEMrziPdYZdPU%3D&reserved=0 From alexkleider at protonmail.com Fri Oct 23 14:25:52 2020 From: alexkleider at protonmail.com (alexkleider) Date: Fri, 23 Oct 2020 18:25:52 +0000 Subject: [Tutor] Program help In-Reply-To: References: Message-ID: ??????? Original Message ??????? On Thursday, October 22, 2020 3:16 PM, nathan tech wrote: > Hi Garrett > > This reads rather like a homework assignment! :) > > Here are some tips that I hope may help: > > think through what you need to do: > > 1. Load the data. > 2. Do something with the data. > 3. Display the data in some way. > > the first bit is quite easy: > > f=open("population.txt","r") > > data=f.read() > > f.close() > > data=data.split("\n") > > Convert it to numbers: > > for x in range(data): > > ?data[x]=int(data[x]) > > The rest is just some fancy footwork with a for loop like the one above > and some organisation into variables depending on what you want to do > with it. > > Hope this helps! > > Nathan The for loop didn't seem quite right to me since data appears to be a list. Python 3.7.3 (default, Jul 25 2020, 13:03:44) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> d = ['1', '3', '4'] >>> for x in range(d): ... data[x] = int(d[x]) ... Traceback (most recent call last): File "", line 1, in TypeError: 'list' object cannot be interpreted as an integer >>> ... or am I missing something? From alan.gauld at yahoo.co.uk Fri Oct 23 15:07:14 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 23 Oct 2020 20:07:14 +0100 Subject: [Tutor] Program help In-Reply-To: References: Message-ID: On 23/10/2020 19:25, alexkleider via Tutor wrote: >> Convert it to numbers: >> >> for x in range(data): >> ?data[x]=int(data[x]) > The for loop didn't seem quite right to me since data appears to be a list. >>>> d = ['1', '3', '4'] > >>>> for x in range(d): > ... data[x] = int(d[x]) > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: 'list' object cannot be interpreted as an integer >>>> > > ... or am I missing something? Its missing a len() for x in range(len(data)): data[x] = int(data[x]) But better still would be a list comprehension data = [int(n) for n in 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 breamoreboy at gmail.com Fri Oct 23 15:15:10 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 23 Oct 2020 20:15:10 +0100 Subject: [Tutor] Program help In-Reply-To: References: Message-ID: On 23/10/2020 19:25, alexkleider via Tutor wrote: > ??????? Original Message ??????? > On Thursday, October 22, 2020 3:16 PM, nathan tech wrote: > >> Hi Garrett >> >> This reads rather like a homework assignment! :) >> >> Here are some tips that I hope may help: >> >> think through what you need to do: >> >> 1. Load the data. >> 2. Do something with the data. >> 3. Display the data in some way. >> >> the first bit is quite easy: >> >> f=open("population.txt","r") >> >> data=f.read() >> >> f.close() >> >> data=data.split("\n") >> >> Convert it to numbers: >> >> for x in range(data): >> >> ?data[x]=int(data[x]) >> >> The rest is just some fancy footwork with a for loop like the one above >> and some organisation into variables depending on what you want to do >> with it. >> >> Hope this helps! >> >> Nathan > > > The for loop didn't seem quite right to me since data appears to be a list. > Python 3.7.3 (default, Jul 25 2020, 13:03:44) > [GCC 8.3.0] on linux > Type "help", "copyright", "credits" or "license" for more information. >>>> d = ['1', '3', '4'] > >>>> for x in range(d): > ... data[x] = int(d[x]) > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: 'list' object cannot be interpreted as an integer >>>> > > ... or am I missing something? > No, the loop was clearly untested. Why not:- >>> data = ['1', '3', '4'] >>> data = [int(x) for x in data] >>> data [1, 3, 4] -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From mysecretrobotfactory at gmail.com Fri Oct 23 15:14:35 2020 From: mysecretrobotfactory at gmail.com (Chris C) Date: Fri, 23 Oct 2020 12:14:35 -0700 Subject: [Tutor] Which way is better? Message-ID: Hi, I have two ways to do string operation, they both do the job fine, but I have been wondering if there is a reason to prefer either. Is it more pythonic to use the 2nd method? Which way is faster/better? Please help. Thanks. The purpose of the following code is to turn a string, such as '-4353,2339' into 2 int(), by splitting the raw string into two, divided by ',' You can run the following code to see what I mean. # Should I do this? raw_string = '-4353,2339' first_part = '' second_part = '' for n in range(len(raw_string)): if raw_string[n] == ',': first_part = raw_string[0:n] second_part = raw_string[n+1:] print(int(first_part)) print(int(second_part)) # Or this? raw_string = '-4353,2339' raw_string = raw_string.split(',') print(raw_string) print(int(raw_string[0])) print(int(raw_string[1])) From alan.gauld at yahoo.co.uk Fri Oct 23 19:12:56 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 24 Oct 2020 00:12:56 +0100 Subject: [Tutor] Which way is better? In-Reply-To: References: Message-ID: On 23/10/2020 20:14, Chris C wrote: > the 2nd method? Which way is faster/better? Those two terms are often result in contradictory answers. But in this case not so... > The purpose of the following code is to turn a string, such as > '-4353,2339'into 2 int(), by splitting the raw string into two, > for n in range(len(raw_string)): > if raw_string[n] == ',': > first_part = raw_string[0:n] > second_part = raw_string[n+1:] > # Or this? > > raw_string = raw_string.split(',') The second. Reasons? 1) It's shorter and easier to type 2) It's more readable - the meaning is in the name - split 3) It's faster because the library code is in C. 4) The compiler will tell you if you spell it wrong 5) It works. (the for loop breaks if there is no comma in the string!) The first one isn't even a good Python version. It iterates over the string when you could use the find() method to locate the ',' and slice based on that. Any time you write a for loop in Python that iterates over range(len(x)) you should think again and check for a better solution, there usually is one to be found. -- 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 manpritsinghece at gmail.com Sat Oct 24 02:24:16 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 24 Oct 2020 11:54:16 +0530 Subject: [Tutor] returning None from function definition Message-ID: Dear Sir , Consider a problem : WAP a program that accepts two integers as user input from keyboard (a and b), and then prints all prime numbers within the range(a, b+1). def prime(x): if x < 2: return None else: for i in range(2, int(x**0.5) + 1): if x % i == 0: return None return True a = int(input("Enter first number")) b = int(input("Enter second number")) for k in range(a, b+1): if prime(k): print(k) In this program each value within the range(a, b+1) will be checked if it is prime number or not . and if it is a prime number it will get printed. A second version of the function written above : def prime(x): if x > 1: for i in range(2, int(x**0.5) + 1): if x % i == 0: return None else: return True In this definition there is no check for values below or equal 1 , although this function will also work in the problem stated at the top, values equals or below 1 will never be printed as prime using this function. So according to you, which function is more readable? keeping readability as the main factor which function definition is more acceptable in this case ? What about returning None instead of False inside Function definition in this case ? Kindly suggest if any improvement needed. Regards Manprit Singh From alan.gauld at yahoo.co.uk Sat Oct 24 06:40:28 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 24 Oct 2020 11:40:28 +0100 Subject: [Tutor] returning None from function definition In-Reply-To: References: Message-ID: On 24/10/2020 07:24, Manprit Singh wrote: > def prime(x): > if x < 2: > return None Don't return none here, return False. None implies no value (although Python considers it false in boolean tests thats effectively a coincidence!) You are explicitly returning a negative result so make it explicit, use False. > else: > for i in range(2, int(x**0.5) + 1): > if x % i == 0: > return None Again return False not None > return True After all you used the explicit true value here. > A second version of the function written above : > > def prime(x): > if x > 1: > for i in range(2, int(x**0.5) + 1): > if x % i == 0: > return None Again, return False not none > else: > return True > In this definition there is no check for values below or equal 1 , although > this function will also work in the problem stated at the top, values > equals or below 1 will never be printed as prime using this function. It works, but it does so by accident because it relies on Python returning None by default. One of the principles of Python is that explicit is better than implicit so you should return False for a boolean function. In this case by adding return False as the last line of the function that handled the x <= 1 cases (you could add an else to make the link to the initial if more obvious, that's a moot choice). > So according to you, which function is more readable? keeping readability > as the main factor which function definition is more acceptable in this > case ? As they stand neither are good since both rely on side-effects and default responses. (And that's ignoring the use of one instead of false!) The second version with an added else: return False on the last line would be the best (IMHO) since that explicitly handles all cases. > What about returning None instead of False inside Function > definition in this case ? That's definitely inferior. False explicitly says why it is being returned. None requires the mental leap to remember that None is considered false in Python logic. Don't make your reader do more work than is necessary. -- 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 mysecretrobotfactory at gmail.com Fri Oct 23 19:58:56 2020 From: mysecretrobotfactory at gmail.com (Chris C) Date: Fri, 23 Oct 2020 16:58:56 -0700 Subject: [Tutor] Which way is better? In-Reply-To: References: Message-ID: cool, thanks! On Fri, Oct 23, 2020 at 4:14 PM Alan Gauld via Tutor wrote: > On 23/10/2020 20:14, Chris C wrote: > > > the 2nd method? Which way is faster/better? > > Those two terms are often result in contradictory answers. > But in this case not so... > > > The purpose of the following code is to turn a string, such as > > '-4353,2339'into 2 int(), by splitting the raw string into two, > > > for n in range(len(raw_string)): > > if raw_string[n] == ',': > > first_part = raw_string[0:n] > > second_part = raw_string[n+1:] > > > # Or this? > > > > raw_string = raw_string.split(',') > > The second. > Reasons? > 1) It's shorter and easier to type > 2) It's more readable - the meaning is in the name - split > 3) It's faster because the library code is in C. > 4) The compiler will tell you if you spell it wrong > 5) It works. (the for loop breaks if there is no comma in the string!) > > The first one isn't even a good Python version. > It iterates over the string when you could use > the find() method to locate the ',' and slice based > on that. Any time you write a for loop in Python > that iterates over range(len(x)) you should think > again and check for a better solution, there usually > is one to be found. > > > -- > 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 mysecretrobotfactory at gmail.com Fri Oct 23 20:44:20 2020 From: mysecretrobotfactory at gmail.com (Chris C) Date: Fri, 23 Oct 2020 17:44:20 -0700 Subject: [Tutor] Python "returning .split() without empty strings Message-ID: Hi all, I have a question regarding string operations. the following string needs to be chopped up, having the 0's dividing the data that I wanted, therefore the string here becomes # run this string = '1111022220000333300044405550055' string = string.split('0') # get this ['1111', '2222', '', '', '', '3333', '', '', '444', '555', '', '55'] # but I want it without the empty strings, so I ran another loop to pick up # only what I wanted key_list = list() for key in string : if key != '': key_list.append(key) print(key_list) # the above is this ['1111', '2222', '3333', '444', '555', '55'] The point is to remove all the 0's, however many there are. I hope I have explained it well, please let me know if I didn't. So, the question is, is it possible to do this without the 2nd stage? Thanks! From alan.gauld at yahoo.co.uk Sat Oct 24 07:08:06 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 24 Oct 2020 12:08:06 +0100 Subject: [Tutor] returning None from function definition In-Reply-To: References: Message-ID: On 24/10/2020 11:40, Alan Gauld via Tutor wrote: > That's definitely inferior. False explicitly says why it is being > returned. None requires the mental leap to remember that None is > considered false in Python logic. Don't make your reader do > more work than is necessary. In fact its worse. it will cause the function to fail in the case of explicit tests for True/false. Consider: >>> def f(): return False >>> if f() is False: print("Its false") Its false >>> def g(): return None >>> if g() is False: print("Its false") >>> Note that an explicit test of the return value for False (using is) fails when None is returned. While I would not recommend using is in boolean tests it does happen in real life. So returning none is not only less readable it is also potentially buggy! -- 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 sourceonly at gmail.com Sat Oct 24 07:10:12 2020 From: sourceonly at gmail.com (An Liu) Date: Sat, 24 Oct 2020 13:10:12 +0200 Subject: [Tutor] Python "returning .split() without empty strings In-Reply-To: References: Message-ID: Hi you might have a look at re.spilt import re res=re.spilt(r?0+?, string) I didn?t test it myself, but should not far away from Working FYI On Sat, Oct 24, 2020 at 13:03 Chris C wrote: > Hi all, I have a question regarding string operations. > the following string needs to be chopped up, having the 0's dividing the > data that I wanted, therefore the string here becomes > > # run this > string = '1111022220000333300044405550055' > string = string.split('0') > > # get this > ['1111', '2222', '', '', '', '3333', '', '', '444', '555', '', '55'] > > # but I want it without the empty strings, so I ran another loop to pick up > # only what I wanted > > key_list = list() > > for key in string : > if key != '': > key_list.append(key) > > print(key_list) > > > # the above is this > ['1111', '2222', '3333', '444', '555', '55'] > > > The point is to remove all the 0's, however many there are. > I hope I have explained it well, please let me know if I didn't. > > So, the question is, is it possible to do this without the 2nd stage? > > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Liu An From alan.gauld at yahoo.co.uk Sat Oct 24 07:14:23 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 24 Oct 2020 12:14:23 +0100 Subject: [Tutor] Python "returning .split() without empty strings In-Reply-To: References: Message-ID: On 24/10/2020 01:44, Chris C wrote: > Hi all, I have a question regarding string operations. > the following string needs to be chopped up, having the 0's dividing the > data that I wanted, therefore the string here becomes > > # run this > string = '1111022220000333300044405550055' > string = string.split('0') > > # get this > ['1111', '2222', '', '', '', '3333', '', '', '444', '555', '', '55'] > > # but I want it without the empty strings, There are (at least) two ways to tackle this. One is to do the split using regular expressions to select multiple 0's. import re string = '1111022220000333300044405550055' key_list = re.split('0+',string) #split on 1 or more 0s The other is to use a map or generator expression to filter them out. Given regex propensity for complicating things I'd usually go with a GE: > key_list = list() > for key in string : > if key != '': > key_list.append(key) Which is what the above is in disguise... key_list = [key for key in string if key] It does the same work but is shorter and arguably more readable. -- 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 Sat Oct 24 07:26:13 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 24 Oct 2020 05:26:13 -0600 Subject: [Tutor] returning None from function definition In-Reply-To: References: Message-ID: On October 24, 2020 12:24:16 AM MDT, Manprit Singh wrote: >Dear Sir , > >Consider a problem : >WAP a program that accepts two integers as user input from keyboard (a >and >b), and then prints all prime numbers within the range(a, b+1). > >def prime(x): > if x < 2: > return None > else: > for i in range(2, int(x**0.5) + 1): > if x % i == 0: > return None > return True Consider if you decided to annotate this function, because you want to be clear about the intent. What would you write? def prime(x: int) -> bool: would be a declaration that the return is a boolean. If you now run one of the host of checkers available, it would complain that in two places the return type is not expected. Here's a case where the type checking actually can be a bit useful. -- Sent from a mobile device with K-9 Mail. Please excuse my brevity. From mats at wichmann.us Sat Oct 24 07:35:23 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 24 Oct 2020 05:35:23 -0600 Subject: [Tutor] Python "returning .split() without empty strings In-Reply-To: References: Message-ID: <3BE93D7A-8D00-427B-9490-8F5BA3BD352F@wichmann.us> On October 24, 2020 5:14:23 AM MDT, Alan Gauld via Tutor wrote: >On 24/10/2020 01:44, Chris C wrote: >> Hi all, I have a question regarding string operations. >> the following string needs to be chopped up, having the 0's dividing >the >> data that I wanted, therefore the string here becomes >> >> # run this >> string = '1111022220000333300044405550055' >> string = string.split('0') there's nothing syntactically wrong with this, but I don't like it: you're reassigning to the name string, and now the name is misleading, because it's a list of strings now. Better to pick a different name, or... skip it as a separate step. See below: >> >> # get this >> ['1111', '2222', '', '', '', '3333', '', '', '444', '555', '', '55'] >> >> # but I want it without the empty strings, > >There are (at least) two ways to tackle this. >One is to do the split using regular expressions to select multiple >0's. > >import re >string = '1111022220000333300044405550055' >key_list = re.split('0+',string) #split on 1 or more 0s > >The other is to use a map or generator expression to filter them out. >Given regex propensity for complicating things I'd usually go with a >GE: > >> key_list = list() >> for key in string : >> if key != '': >> key_list.append(key) > >Which is what the above is in disguise... > >key_list = [key for key in string if key] per above, why not combine: key_list = [key for key in string.split('0') if key] >It does the same work but is shorter and arguably more readable. -- Sent from a mobile device with K-9 Mail. Please excuse my brevity. From cs at cskk.id.au Sat Oct 24 07:38:04 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 24 Oct 2020 22:38:04 +1100 Subject: [Tutor] returning None from function definition In-Reply-To: References: Message-ID: <20201024113804.GA69777@cskk.homeip.net> On 24Oct2020 11:54, Manprit Singh wrote: >What about returning None instead of False inside Function >definition in this case ? Kipping over the prime functions, I just want to recommend against returning None instead of False. Your function returns a true/false result, so it _should_ return a Boolean, which in Python is one of the two special values True and False. It _happens_ that your programme runs using None for false, just as it would run using 0 for false, because Python falls back to a "nonzero" style test in conditions if it is not handed a Boolean (type bool). But it is very bad practice. Secondly, think about linting your programmes. Supposing you put some type annotations on your code, like this: def prime(n:int) -> bool: ... test n for primality ... If you run a linter over this code which understands type annotations, it will rightly complain about returning None, because you've asserted that this is a function returning a bool, which is the _natrual_ type for logic results. Finally, all python functions return values. When you just do a plain: return or fall off the end of a function with no explicit return statement, that returns None. Just don't do this. Cheers, Cameron Simpson From s.molnar at sbcglobal.net Sat Oct 24 08:50:21 2020 From: s.molnar at sbcglobal.net (Stephen P. Molnar) Date: Sat, 24 Oct 2020 08:50:21 -0400 Subject: [Tutor] Matplotlib.pyplot - How to Insert Computed values in Plot Legend References: <5F94230D.7070200.ref@sbcglobal.net> Message-ID: <5F94230D.7070200@sbcglobal.net> I have written a Python script to plot Linear Regression results using python-3.7.3 with matplotlib-3.3.0 on my Debian Buster platform. The script also calculates a number of statistical parameters as well as the slope (b-sub-1) and intercept (b-sub-0) of the regression line. However, there remain several problems for which I have not be able to find a solution, in spite of Google. The code for the plot legend at this point is: red_patch = mpatches.Patch(label='A = b$_1$*log(IC$_5$$_0$) - b$_0$ \nr$^2$ = ') . . . plt.legend(handles=[red_patch], loc='lower right', frameon=False) 1. How can I insert formatted values for the slope, intercept i and r-sq in the legend? 2. How can I change the blue line in the legend to the same thickness of the regression line? I would greatly appreciate assistance in resolving these problems. Thanks in advance. -- Stephen P. Molnar, Ph.D. www.molecular-modeling.net 614.312.7528 (c) Skype: smolnar1 From manpritsinghece at gmail.com Sat Oct 24 09:22:33 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 24 Oct 2020 18:52:33 +0530 Subject: [Tutor] returning None from function definition In-Reply-To: References: Message-ID: Dear Alan sir , Based on your comments, I have written it again . Hope this definition is perfectly fine . def prime(x): if x > 1: for i in range(2, int(x**0.5) + 1): if x % i == 0: return False else: return True else: return False Many many thanks for your suggestions, Regards Manprit Singh On Sat, Oct 24, 2020 at 11:54 AM Manprit Singh wrote: > Dear Sir , > > Consider a problem : > WAP a program that accepts two integers as user input from keyboard (a and > b), and then prints all prime numbers within the range(a, b+1). > > def prime(x): > if x < 2: > return None > else: > for i in range(2, int(x**0.5) + 1): > if x % i == 0: > return None > return True > > a = int(input("Enter first number")) > b = int(input("Enter second number")) > for k in range(a, b+1): > if prime(k): > print(k) > > In this program each value within the range(a, b+1) will be checked if it > is prime number or not . and if it is a prime number it will get printed. > > A second version of the function written above : > > def prime(x): > if x > 1: > for i in range(2, int(x**0.5) + 1): > if x % i == 0: > return None > else: > return True > In this definition there is no check for values below or equal 1 , > although this function will also work in the problem stated at the top, > values equals or below 1 will never be printed as prime using this function. > > So according to you, which function is more readable? keeping readability > as the main factor which function definition is more acceptable in this > case ? What about returning None instead of False inside Function > definition in this case ? > Kindly suggest if any improvement needed. > > Regards > Manprit Singh > > > From PyTutor at DancesWithMice.info Sat Oct 24 14:06:25 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sun, 25 Oct 2020 07:06:25 +1300 Subject: [Tutor] Which way is better? In-Reply-To: References: Message-ID: <1d2ee11c-cd54-eb0c-927b-931ac6c80d6b@DancesWithMice.info> On 24/10/2020 12:12, Alan Gauld via Tutor wrote: > On 23/10/2020 20:14, Chris C wrote: > >> the 2nd method? Which way is faster/better? > > Those two terms are often result in contradictory answers. > But in this case not so... > >> The purpose of the following code is to turn a string, such as >> '-4353,2339'into 2 int(), by splitting the raw string into two, > >> for n in range(len(raw_string)): >> if raw_string[n] == ',': >> first_part = raw_string[0:n] >> second_part = raw_string[n+1:] > >> # Or this? >> >> raw_string = raw_string.split(',') > > The second. > Reasons? > 1) It's shorter and easier to type > 2) It's more readable - the meaning is in the name - split > 3) It's faster because the library code is in C. > 4) The compiler will tell you if you spell it wrong > 5) It works. (the for loop breaks if there is no comma in the string!) > > The first one isn't even a good Python version. > It iterates over the string when you could use > the find() method to locate the ',' and slice based > on that. Any time you write a for loop in Python > that iterates over range(len(x)) you should think > again and check for a better solution, there usually > is one to be found. +1 taking "there usually is one to be found" a bit further: when comparing 'pythonic' approaches, two other criteria: - how will the (two items of) data be used, afterwards? - what of error conditions: zero integers, one integer/no comma, non-integer data, multiple commas, ... NB is it appropriate to call a *list* of *processed* strings "raw_string"? -- Regards =dn From breamoreboy at gmail.com Sat Oct 24 12:20:01 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Sat, 24 Oct 2020 17:20:01 +0100 Subject: [Tutor] Matplotlib.pyplot - How to Insert Computed values in Plot Legend In-Reply-To: <5F94230D.7070200@sbcglobal.net> References: <5F94230D.7070200.ref@sbcglobal.net> <5F94230D.7070200@sbcglobal.net> Message-ID: On 24/10/2020 13:50, Stephen P. Molnar wrote: > I have written a Python script to plot Linear Regression results using > python-3.7.3 with matplotlib-3.3.0 on my Debian Buster platform. > > > The script also calculates a number of statistical parameters as well as > the slope (b-sub-1) and intercept (b-sub-0) of the regression line. > However, there remain several problems for which I have not be able to > find a solution, in spite of Google. > > The code for the plot legend at this point is: > > red_patch = mpatches.Patch(label='A = b$_1$*log(IC$_5$$_0$) - b$_0$ > \nr$^2$ = ') > . > . > . > plt.legend(handles=[red_patch], loc='lower right', frameon=False) > > 1. How can I insert formatted values for the slope, intercept i and r-sq > in the legend? > 2. How can I change the blue line in the legend to the same thickness of > the regression line? > > I would greatly appreciate assistance in resolving these problems. > > Thanks in advance. > As this isn't core python I suggest that you start here https://matplotlib.org/3.3.2/contents.html Failing that try stackoverflow which has 100s if not 1,000s of matplotlib Q and As. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From manpritsinghece at gmail.com Sat Oct 24 15:22:27 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 25 Oct 2020 00:52:27 +0530 Subject: [Tutor] taking support of strings in solving numerical problems Message-ID: Dear sir , Consider a problem a problem to find sum of series of the form : a + aa + aaa + aaa like 9 + 99 + 999 + 9999 that equals 11106 I have solved this using strings as given below : def sum_ser(x, lim): # definition sum_no = 0 for i in range(lim): sum_no = sum_no + int(str(x) * (i + 1)) return sum_no sum_ser(9, 4) # call to find sum of series 9 + 99 + 999 + 9999 which gives the correct answer = 11106 Here in the for loop inside function definition, you can see i have first converted the integer x to string then multiplied this string by (i+1) and then again converted this string to integer . I have seen in various scenarios, where using strings in a numerical problem reduces the size of the program Using strings to solve numerical problems in such a way is a valid use case ? should this practise be followed in production ? Regards Manprit Singh Regards Manprit Singh From PyTutor at DancesWithMice.info Sat Oct 24 16:46:31 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sun, 25 Oct 2020 09:46:31 +1300 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: <7fde880a-ed1a-fcf1-ddb5-e719b2a7808a@DancesWithMice.info> On 25/10/2020 08:22, Manprit Singh wrote: > I have seen in various scenarios, where using strings in a numerical > problem reduces the size of the program > > Using strings to solve numerical problems in such a way is a valid use case > ? should this practise be followed in production ? Really? Examples please... -- Regards =dn From cs at cskk.id.au Sat Oct 24 18:02:47 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 25 Oct 2020 09:02:47 +1100 Subject: [Tutor] Clearing the screen from the terminal In-Reply-To: References: Message-ID: <20201024220247.GA46864@cskk.homeip.net> On 18Oct2020 20:18, Alan Gauld wrote: [...] >The "correct" way of doing screen control in a terminal >(as used by vim and the top commands etc) is to use the >curses module. Curses provides screen and cursor control >regardless of terminal type. But that introduces a >whole extra layer of complexity (along with power). >For example regular print() and input() fuctions won't >work, you need to use curses own equivalents. > >A minimal curses program to clear the screen is: > >import curses > >def main(win): # win refers to the terminal screen. > win.clear() > # your program here.... > >curses.wrapper(main) And if the OP wants a lower level approach, still in Python: import curses curses.setupterm() print(curses.tigetstr('clear_screen'), end='') # your program here.... which sidesteps the "initialise curses and prepare a full screen environment". All this one does is get curses to load the terminfo db and then queries it for the "clear_screen" sequence. I'll also take a moment to iterate my dislike of programmes which clear the screen. One has but to boot a PC and see the many screen redraws obliterating the previous "what happened" display to understand my ire. I can even be pushed to pining for the days of the paper terminal... Cheers, Cameron Simpson From cs at cskk.id.au Sat Oct 24 18:08:52 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 25 Oct 2020 09:08:52 +1100 Subject: [Tutor] a program which list ALL the errors In-Reply-To: References: Message-ID: <20201024220852.GA73513@cskk.homeip.net> On 18Oct2020 12:34, Alan Gauld wrote: >But it must be said that its an unusual strategy. >Most programs detect the first error and stop. And those programmes are user experience disasters. I hate them with a passion. I will always, given the opportunity, use the many-ifs-and-set-an-error-flag approach. Who has not tried to invokes some minorly complicated programme in several goes, fixing one thing only to trip over the next. A PITA. My most notable recent example was an environment setup script for something; it had a step where it probes for a dozne or so required peices of software, and complained and quit at the first missing one. When that logic is buried deep in a subsidiary script, the user is massively annoyed. I submitted a small patch to probe for _all_ the software, complain about each missing comonepnt, and _then_ quit. Really easy and avoids much anger in the end user. Cheers, Cameron Simpson From robertvstepp at gmail.com Sat Oct 24 18:57:12 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Sat, 24 Oct 2020 17:57:12 -0500 Subject: [Tutor] returning None from function definition In-Reply-To: References: Message-ID: <20201024225712.GF9135@Dream-Machine1> On Sat, Oct 24, 2020 at 06:52:33PM +0530, Manprit Singh wrote: > >Based on your comments, I have written it again . Hope this definition is >perfectly fine . >def prime(x): > if x > 1: > for i in range(2, int(x**0.5) + 1): > if x % i == 0: > return False > else: > return True > else: > return False One suggestion about your algorithm: Do an explicit check if the number is divisible by two before you start looping. Then loop over only the odd numbers. -- Wishing you only the best, boB Stepp From bulbman94 at gmail.com Sat Oct 24 14:57:52 2020 From: bulbman94 at gmail.com (Gerald OBrien) Date: Sat, 24 Oct 2020 13:57:52 -0500 Subject: [Tutor] Help with printing turtle Graphics Message-ID: <33F38EF4-B79E-415D-98F0-3092C5889393@gmail.com> Hello, I have a question please. First of all, I am getting old, at 74, but not out of the game yet. I am also legally, but not totally, blind. I am a bit like a guy with a brown belt in Karate; I know just enough about computers to get my butt kicked. I am using a Mac desktop computer currently that the hospital gave me about 3 years ago. I really like it. It is a bit easier for me to use rather than a Windows unit, mostly because of my limited vision. But I do access To a Windows 10 machined if needed I started using ?Turtle Graphics? and was able to do a bit of good making shapes and doodles. Here is my question, basic as it was seem: I have made a couple of things in the Turtle Graphics, using the .py suffix. It seem to me that I used to make some of these drawings and be able to PRINT THEM out on a printer. I was out of the game for a few months , while attending the VA Hospital Blind Rehab Unit in Biloxi, Mississippi. When I cam back the Python version had upgraded a number of times and I downloaded the newest version. I noticed that when I screen printed the Turtle Graphic image, it would appear on another screen, adjacent to my screen. I tried to print it, using a Printer, or save it as either a jpeg or PNG suffix and it did nothing. I was not able to take a screen shot of it and save it to the clipboard. If I tried to screen print it, everything would just go away, not to be seen again. Might you have any suggestions or ideas for an old man that really enjoys the challenge of making some of these images / drawings. My desire was to basically make a border type layer to put a photo of some of my grand children into and get printed out. No luck on any of those. I did try Goodle but not much was said about Turtle graphics, on how to start it, initially?... Thank you very much in advance for any assistance or suggestions. Sincerely, Gerald (Jerry) O?Brien Houston, Texas From alan.gauld at yahoo.co.uk Sat Oct 24 19:15:52 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 25 Oct 2020 00:15:52 +0100 Subject: [Tutor] a program which list ALL the errors In-Reply-To: <20201024220852.GA73513@cskk.homeip.net> References: <20201024220852.GA73513@cskk.homeip.net> Message-ID: On 24/10/2020 23:08, Cameron Simpson wrote: > On 18Oct2020 12:34, Alan Gauld wrote: >> But it must be said that its an unusual strategy. >> Most programs detect the first error and stop. > > And those programmes are user experience disasters. I hate them with a > passion. > When that logic is buried deep in a subsidiary script, the user is > massively annoyed. I submitted a small patch to probe for _all_ the > software, complain about each missing comonepnt, and _then_ quit. Really > easy and avoids much anger in the end user. Interesting. I absolutely hate that behaviour. Some compilers do it and its a massive pain finding the first error and fixing it then trying to find another, and another, and then discovering that fixing the first actually changed the second! It's much, much easier IMHO to fix one thing at a time. Of course the program should give useful hints as to what it is expecting up front. But not give me a raft of error messages - my poor brain can only cope with one at a time! :-0 "Beauty is in the eye..." I guess. -- 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 Sat Oct 24 19:17:34 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 25 Oct 2020 00:17:34 +0100 Subject: [Tutor] Clearing the screen from the terminal In-Reply-To: <20201024220247.GA46864@cskk.homeip.net> References: <20201024220247.GA46864@cskk.homeip.net> Message-ID: On 24/10/2020 23:02, Cameron Simpson wrote: > curses.setupterm() > print(curses.tigetstr('clear_screen'), end='') Nice one, I'd never have thought of that. I've only ever used the ti functions inside a curses program to find out if some capability is actually supported by my terminal. -- 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 Sat Oct 24 19:31:44 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 25 Oct 2020 00:31:44 +0100 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: On 24/10/2020 20:22, Manprit Singh wrote: > Consider a problem a problem to find sum of series of the form : > a + aa + aaa + aaa > def sum_ser(x, lim): # definition > sum_no = 0 > for i in range(lim): > sum_no = sum_no + int(str(x) * (i + 1)) > return sum_no > I have seen in various scenarios, where using strings in a numerical > problem reduces the size of the program > > Using strings to solve numerical problems in such a way is a valid use case > ? should this practise be followed in production ? It is valid in the few cases where it is helpful but usually using math works better. For example in your case the algorithm is simple N2 = N1*10+x Where N1 is the previous total and x is the number. As a function: def generate_nums(x,n): nums = [x] for i in range(1,n): nums.append(nums[-1]*10 +x) return nums And the sum is just a case of applying sum(): >>> sum(generate_nums(9,4)) 11106 And remember that string operations are quite slow compared to math - in addition to the two way conversions you have to create memory space, then expand that memory space. All relatively slow operations. Pure math will normally be faster. -- 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 Sat Oct 24 19:46:29 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 25 Oct 2020 00:46:29 +0100 Subject: [Tutor] Help with printing turtle Graphics In-Reply-To: <33F38EF4-B79E-415D-98F0-3092C5889393@gmail.com> References: <33F38EF4-B79E-415D-98F0-3092C5889393@gmail.com> Message-ID: On 24/10/2020 19:57, Gerald OBrien wrote: > I tried to print it, using a Printer, or save it as either a jpeg or PNG suffix I can't thin of an easy way to do this ids a window capture doesn't work. In code you can save a screen object as a postscript file but it involves some non-trivial Tkinter knowledge and functions. The turtle screen object is descended from the Tkinter canvas object which has a "Postscript(....)" method. If you feel keen read up on how to use the postscript method. You can get the screen object by calling turtle.Screen() so... scr = turtle.Screen() scr.Postscript('myturtle.ps') Should, in theory, work, but I suspect its more complex than that! Then you need to find a way to print or view a postscript file. You might need a Mac user to tell you how to 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 cs at cskk.id.au Sat Oct 24 20:58:25 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 25 Oct 2020 11:58:25 +1100 Subject: [Tutor] a program which list ALL the errors In-Reply-To: References: Message-ID: <20201025005825.GA80549@cskk.homeip.net> On 25Oct2020 00:15, Alan Gauld wrote: >On 24/10/2020 23:08, Cameron Simpson wrote: >> On 18Oct2020 12:34, Alan Gauld wrote: >>> But it must be said that its an unusual strategy. >>> Most programs detect the first error and stop. >> >> And those programmes are user experience disasters. I hate them with a >> passion. > >> When that logic is buried deep in a subsidiary script, the user is >> massively annoyed. I submitted a small patch to probe for _all_ the >> software, complain about each missing comonepnt, and _then_ quit. Really >> easy and avoids much anger in the end user. > >Interesting. I absolutely hate that behaviour. Some compilers >do it and its a massive pain finding the first error and fixing >it then trying to find another, and another, and then discovering >that fixing the first actually changed the second! It's much, >much easier IMHO to fix one thing at a time. > >Of course the program should give useful hints as to what it is >expecting up front. But not give me a raft of error messages - my poor >brain can only cope with one at a time! :-0 For a long compiler error listing, perhaps so. A good terminate which makes "jump back to the previous shell prompt" just a keystroke would help there. I think iterm can be asked to do that, for example. But for your average vaguely complicated command line invocation, I much prefer this: [~/hg/css-cloud(hg:cloud)]fleet2*2> dev cloudbackup -j 0 -A s4://foo/bah cloudbackup: -j: value < 1: 0 cloudbackup: invalid cloud_area: s4://foo/bah: no module 'cs.cloud.s4' for cloud service 's4' cloudbackup: no backup_name specified The following backup names exist: cs test cloudbackup: bad options Usage: cloudbackup [options] subcommand [...] [... full usage message here ...] over bouncing back and forth getting each option correctly tuned. Cheers, Cameron Simpson From PyTutor at DancesWithMice.info Sat Oct 24 21:27:41 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sun, 25 Oct 2020 14:27:41 +1300 Subject: [Tutor] Help with printing turtle Graphics In-Reply-To: <33F38EF4-B79E-415D-98F0-3092C5889393@gmail.com> References: <33F38EF4-B79E-415D-98F0-3092C5889393@gmail.com> Message-ID: <8e4ba4a7-8c8e-b440-25ac-b1552cc4be2e@DancesWithMice.info> On 25/10/2020 07:57, Gerald OBrien wrote: > I started using ?Turtle Graphics? and was able to do a bit of good making shapes and doodles. > > Here is my question, basic as it was seem: I have made a couple of things in the Turtle Graphics, using the .py suffix. > It seem to me that I used to make some of these drawings and be able to PRINT THEM out on a printer. I was out of the game for a few months , while attending the VA Hospital Blind Rehab Unit in Biloxi, Mississippi. When I cam back the Python version had upgraded a number of times and I downloaded the newest version. > > I noticed that when I screen printed the Turtle Graphic image, it would appear on another screen, adjacent to my screen. > I tried to print it, using a Printer, or save it as either a jpeg or PNG suffix and it did nothing. I was not able to take a screen shot of it and save it to the clipboard. We have to solve this - just going back to G-B-P would be more than enough 'punishment' for this ex-CB! Knowing nothing more than theory about 'turtles' (and their place in learning logic), some time back I attempted a 'course' in preparation to helping at a kids' activity. I thought it odd that there is no screen-print - particularly for kids who would want to 'take something home' (on paper, cf on their device). The explanation is that Python-turtle is purely about manipulating the shape/path on-screen. Plus finding a cross-platform printing-solution is difficult. During the course, we had to provide assignment results - and with their being interested in the construction details/process, I used screen-recorder software. For 'stills' I used "screenshots". (apologies: I can't recommend specific software for a Mac - my system is Linux, so I use "SimpleScreenRecorder" and "ScreenShot") The latter allows a choice between 'snapping' the whole screen, the application window, or a manually-defined area; and saves directly to a file, cf the clipboard. As examples, here's a simple play on the phrase/philosophy "it's turtles all the way down" (https://en.wikipedia.org/wiki/Turtles_all_the_way_down): https://danceswithmice.info/Py3Course/TurtlesAllTheWayDown.png https://danceswithmice.info/Py3Course/TurtlesAllTheWayDown.mp4 (no prizes for guessing where in the world I live, these days) Once you've finished playing with the 'turtle', you may like to take a look at Pygame. Pygame has a bunch of decorative methods for drawing on the screen... -- Regards =dn From PyTutor at DancesWithMice.info Sat Oct 24 21:59:48 2020 From: PyTutor at DancesWithMice.info (dn) Date: Sun, 25 Oct 2020 14:59:48 +1300 Subject: [Tutor] a program which list ALL the errors In-Reply-To: References: <20201024220852.GA73513@cskk.homeip.net> Message-ID: <700cadea-af6b-b715-0ba6-5e5f49cc053d@DancesWithMice.info> On 25/10/2020 12:15, Alan Gauld via Tutor wrote: > On 24/10/2020 23:08, Cameron Simpson wrote: >> On 18Oct2020 12:34, Alan Gauld wrote: >>> But it must be said that its an unusual strategy. >>> Most programs detect the first error and stop. >> >> And those programmes are user experience disasters. I hate them with a >> passion. > >> When that logic is buried deep in a subsidiary script, the user is >> massively annoyed. I submitted a small patch to probe for _all_ the >> software, complain about each missing comonepnt, and _then_ quit. Really >> easy and avoids much anger in the end user. > > Interesting. I absolutely hate that behaviour. Some compilers > do it and its a massive pain finding the first error and fixing > it then trying to find another, and another, and then discovering > that fixing the first actually changed the second! It's much, > much easier IMHO to fix one thing at a time. > > Of course the program should give useful hints as to what it is > expecting up front. But not give me a raft of error messages - my poor > brain can only cope with one at a time! :-0 > > "Beauty is in the eye..." I guess. Re-factoring a routine this morning, I caused pytest to 'light-up like a Christmas tree'. (yes, I appreciate that you are surprised - get over it!) As it happened, of the dozens of failing-tests, most related to the same simple typo. However, I was able to quickly scan and reject the second, third, ... of these, as 'solved'; but still pick-up a couple of others which were 'different'. If I 'fixed' the first error and then pytest-ed again, might this have been faster to reveal the 'other errors'? Possibly - would depend upon the time taken to re-test cf that required for me to read. (to restore your (mis-placed) faith in my programming abilities - the second test was a complete 'pass') I think my training/background/in-grained habit leads me to the 'show me everything - let me (try to) fix it (all) once' option. I notice that younger folk (aren't they all, these days?) have grown-up with faster machines and faster turn-around (see next paragraph) and thus have the habit of 'throwing code at the machine' to see what transpires. Maybe that is the 'beautiful eye' you mention? Back in the ?good, old days: when it cost 24-hours per "turn-around" - punching cards, submitting a source-deck, waiting, inspecting the returned print-out on that lovely, striped, lineflow stationery... We valued the compiler finding an error, and then attempting to re-start to find any further problems. The cost of correcting errors at a rate of one per run was horrendous ($ or time). Sure, sometimes the compiler's re-start embodied assumptions which led to false-negatives, but... (I assume this continues with present-day compiled languages) Same in conversation: if someone comes to me with a 'problem', I prefer to hear the 'whole story'; rather than 'solving' the first 'issue' - only to find that such solution worsens the third 'issue'! (aside from politeness, 'proper listening', ... my learning patience...) That said, I notice that pytest has an option to run a file containing multiple tests and to stop on first-error, cf my IDE's control file: set to run all the way to 'the bitter end'. So, there are clearly different preferences/scenarios! A new aphorism: "horses for courses"? -- Regards =dn From mats at wichmann.us Sat Oct 24 22:14:24 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 24 Oct 2020 20:14:24 -0600 Subject: [Tutor] a program which list ALL the errors In-Reply-To: References: <20201024220852.GA73513@cskk.homeip.net> Message-ID: <1ce1e304-57cb-5748-7778-4abb91df1825@wichmann.us> On 10/24/20 5:15 PM, Alan Gauld via Tutor wrote: > On 24/10/2020 23:08, Cameron Simpson wrote: >> On 18Oct2020 12:34, Alan Gauld wrote: >>> But it must be said that its an unusual strategy. >>> Most programs detect the first error and stop. >> >> And those programmes are user experience disasters. I hate them with a >> passion. > >> When that logic is buried deep in a subsidiary script, the user is >> massively annoyed. I submitted a small patch to probe for _all_ the >> software, complain about each missing comonepnt, and _then_ quit. Really >> easy and avoids much anger in the end user. > > Interesting. I absolutely hate that behaviour. Some compilers > do it and its a massive pain finding the first error and fixing > it then trying to find another, and another, and then discovering > that fixing the first actually changed the second! It's much, > much easier IMHO to fix one thing at a time. It really depends on the context. I've often run into this with the GNU autoconf stuff... try to configure a program, and it fails. Install missing package, retry, fails. Repeat several times. Why? In the case of an autoconf setup, the problems are likely to be missing distribution packages, and it's nice to get those all at once, rather than iterating, because you could just gang all the needed installs into one command. But I freely admit there are also times where it's bad to spew all the errors, like with compilers - often one problem will cascade through and potentially give you dozens to hundreds of fails, and there's no value to spewing those, it's better to just emit one, fix it, retry - and probably the fail list got massively smaller. From manpritsinghece at gmail.com Sat Oct 24 22:52:13 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 25 Oct 2020 08:22:13 +0530 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: Dear Sir, I again got to learn something through this mail of yours . many many thanks . Actually i usually do not prefer to involve list while my final result is to find the sum, So i have implemented your idea in the form of generator function as written below: def genfx_ser(x, lim): sum_no = x for i in range(lim): yield sum_no sum_no = (sum_no*10) + x This feels more good to me . Now reason of putting yield inside for loop is, let's say if someone tries to find the sum of series upto 0 terms by writing sum(genfx_series(9, 0)), He or she will get 0 as sum as there will be no data in the iterator returned by generator function at that time. I tested it for finding sum of series of 4 terms - 9 + 99 +999 + 9999 = 11106 by writing sum(genfx_series(9, 4)) and got the same output = 11106. Need your humble suggestions on this example using generator functions . Regards Manprit Singh On Sun, Oct 25, 2020 at 5:02 AM Alan Gauld via Tutor wrote: > On 24/10/2020 20:22, Manprit Singh wrote: > > > Consider a problem a problem to find sum of series of the form : > > a + aa + aaa + aaa > > > def sum_ser(x, lim): # definition > > sum_no = 0 > > for i in range(lim): > > sum_no = sum_no + int(str(x) * (i + 1)) > > return sum_no > > > I have seen in various scenarios, where using strings in a numerical > > problem reduces the size of the program > > > > Using strings to solve numerical problems in such a way is a valid use > case > > ? should this practise be followed in production ? > > It is valid in the few cases where it is helpful but usually > using math works better. > > For example in your case the algorithm is simple > > N2 = N1*10+x > > Where N1 is the previous total and x is the number. > As a function: > > def generate_nums(x,n): > nums = [x] > for i in range(1,n): > nums.append(nums[-1]*10 +x) > return nums > > And the sum is just a case of applying sum(): > > >>> sum(generate_nums(9,4)) > 11106 > > And remember that string operations are quite slow compared > to math - in addition to the two way conversions you have > to create memory space, then expand that memory space. > All relatively slow operations. > > Pure math will normally be faster. > > -- > 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 PyTutor at danceswithmice.info Sun Oct 25 00:49:37 2020 From: PyTutor at danceswithmice.info (dn) Date: Sun, 25 Oct 2020 17:49:37 +1300 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: <7fde880a-ed1a-fcf1-ddb5-e719b2a7808a@DancesWithMice.info> Message-ID: Perhaps the question was not sufficiently precise: what are examples of real-world, or practical use-cases for, "various scenarios, where using strings in a numerical problem reduces the size of the program"? Repeating previous requests. Please re-consider: 1 top-posting, 2 ReplyToList. On 25/10/2020 16:30, Manprit Singh wrote: > Dear Sir , > As you asked for examples, I am going to give you a simple example to > illustrate the fact > Consider a problem where i have to reverse a number : > A function definition can be written like this : > > def rev_num(x): > s = 0 > while x != 0: > ? ?x, r = divmod(x, 10) > ? ?s = s*10 + r > return s > > While if i use strings, i can write the same function as : > > def rev1_num(x): return int(str(x)[::-1]) > > Need your comments on such cases > > Regards > Manprit Singh > > On Sun, Oct 25, 2020 at 2:16 AM dn via Tutor > wrote: > > On 25/10/2020 08:22, Manprit Singh wrote: > > I have seen in various scenarios, where using strings in a numerical > > problem reduces the size of the program > > > > Using strings to solve numerical problems in such a way is a > valid use case > > ? should this practise be followed in production ? > > Really? > Examples please... > -- > Regards =dn > _______________________________________________ > Tutor maillist? - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Regards =dn From alan.gauld at yahoo.co.uk Sun Oct 25 03:59:47 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 25 Oct 2020 07:59:47 +0000 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: On 25/10/2020 02:52, Manprit Singh wrote: > def genfx_ser(x, lim): > sum_no = x > for i in range(lim): > yield sum_no > sum_no = (sum_no*10) + x > > This feels more good to me . Now reason of putting yield inside for loop > is, let's say if someone tries to find the sum of series upto 0 terms by > writing sum(genfx_series(9, 0)), He or she will get 0 as sum as there will be no > data in the iterator returned by generator function at that time. The logic on yield is good, but if the loop is not entered the user gets None returned(the default value) not 0. These are different values. You really should put a return 0 in an if test for that scenario. if lim == 0: return 0 Programming conventions suggest that should in fact be the first line of the function because its good practice to check for invalid or edge case input before handling the normal case. However a better solution, rather than handing back a number with special meaning would be to throw an exception - ValueError being the obvious choice. So the first line of the function could be: if lim <= 0: raise ValueError("lim must be greater than zero") You might like to check that x is an int too.... Or try converting it to an int. > Need your humble suggestions on this example using generator functions . It's a reasonable use case for a generator since lim could potentially be a large value. -- 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 manpritsinghece at gmail.com Sun Oct 25 04:38:26 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sun, 25 Oct 2020 14:08:26 +0530 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: Dear Sir, While working on your suggestions and doing experiments on interpreter, I found an unexpected behaviour as follows : >>> def genfx_ser(x, lim): sum_no = x for i in range(lim): yield sum_no sum_no = (sum_no*10) + x >>> genfx_ser >>> genfx_ser(9, "a") In the second function call , see the second argument is "a", which is being passed to formal parameter lim in function definition, must create an error , since range cannot accept a non integer value, but still function call is returning a generator object. Is it a bug ? Similarly i tried for some other values as given below : >>> genfx_ser(9, 0) That again returned a generator object with a second argument to the call equals 0 . Kindly put some light on it Regards Manprit Singh On Sun, Oct 25, 2020 at 1:30 PM Alan Gauld via Tutor wrote: > On 25/10/2020 02:52, Manprit Singh wrote: > > > def genfx_ser(x, lim): > > sum_no = x > > for i in range(lim): > > yield sum_no > > sum_no = (sum_no*10) + x > > > > This feels more good to me . Now reason of putting yield inside for loop > > is, let's say if someone tries to find the sum of series upto 0 terms by > > writing sum(genfx_series(9, 0)), He or she will get 0 as sum as there > will be no > > data in the iterator returned by generator function at that time. > > The logic on yield is good, but if the loop is not entered > the user gets None returned(the default value) not 0. > These are different values. > > You really should put a return 0 in an if test for that scenario. > > if lim == 0: return 0 > > Programming conventions suggest that should in fact be the first > line of the function because its good practice to check for > invalid or edge case input before handling the normal case. > > However a better solution, rather than handing back a number > with special meaning would be to throw an exception - ValueError > being the obvious choice. So the first line of the function > could be: > > if lim <= 0: raise ValueError("lim must be greater than zero") > > You might like to check that x is an int too.... Or try > converting it to an int. > > > Need your humble suggestions on this example using generator functions . > > It's a reasonable use case for a generator since lim could potentially > be a large value. > > -- > 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 oscar.j.benjamin at gmail.com Sun Oct 25 07:10:30 2020 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 25 Oct 2020 11:10:30 +0000 Subject: [Tutor] a program which list ALL the errors In-Reply-To: <1ce1e304-57cb-5748-7778-4abb91df1825@wichmann.us> References: <20201024220852.GA73513@cskk.homeip.net> <1ce1e304-57cb-5748-7778-4abb91df1825@wichmann.us> Message-ID: On Sun, 25 Oct 2020 at 02:15, Mats Wichmann wrote: > > On 10/24/20 5:15 PM, Alan Gauld via Tutor wrote: > > On 24/10/2020 23:08, Cameron Simpson wrote: > >> On 18Oct2020 12:34, Alan Gauld wrote: > >>> But it must be said that its an unusual strategy. > >>> Most programs detect the first error and stop. > >> > >> And those programmes are user experience disasters. I hate them with a > >> passion. > > > >> When that logic is buried deep in a subsidiary script, the user is > >> massively annoyed. I submitted a small patch to probe for _all_ the > >> software, complain about each missing comonepnt, and _then_ quit. Really > >> easy and avoids much anger in the end user. > > > > Interesting. I absolutely hate that behaviour. Some compilers > > do it and its a massive pain finding the first error and fixing > > it then trying to find another, and another, and then discovering > > that fixing the first actually changed the second! It's much, > > much easier IMHO to fix one thing at a time. > > It really depends on the context. > > I've often run into this with the GNU autoconf stuff... try to configure > a program, and it fails. Install missing package, retry, fails. Repeat > several times. Why? In the case of an autoconf setup, the problems are > likely to be missing distribution packages, and it's nice to get those > all at once, rather than iterating, because you could just gang all the > needed installs into one command. But I freely admit there are also > times where it's bad to spew all the errors, like with compilers - often > one problem will cascade through and potentially give you dozens to > hundreds of fails, and there's no value to spewing those, it's better to > just emit one, fix it, retry - and probably the fail list got massively > smaller. I think an important factor in this is whether or not you can give accurate error messages for independent failures. Having experienced teaching new programmers in both C and Python I find Python's "stop at the first error" behaviour much better than the C compiler. It shows you one error at a time along with a (relatively) helpful explanation of the error. A typical C compiler might give hundreds of mostly distracting error messages because of e.g. a single missed semicolon. More importantly only the first error message about the missing semicolon (often not said in so many words) is meaningful and all of the subsequent error messages just result from the compiler itself being confused after failing to parse that one line correctly. Another factor though is the time taken to run the whole process and see the failures. A complicated C build might take many minutes to run so being able to see all the error messages in one go could save some time in the process. Over the past week I've been trying to fix up the sympy release script so that I can release version 1.7. The release script runs in a docker container that always pulls from the current HEAD of the release branch on github. That means that if something goes wrong then to fix it you need to issue a pull request, wait for CI to complete, merge that and then rerun the script and wait for all the tests to run again in the docker container. Altogether that means that a single edit-and-retry takes 5 hours before you see the next error message. In this context it would be very helpful if I could see all of the error messages at once! On the other hand during this process one of the problems I was trying to debug was made more difficult by excessively verbose output. Building the latex docs failed in the release script. The latex output log from the failed build was 31000 lines long with the summary "missing characters". Searching the log I find sections like this: Missing character: There is no ? in font cmex10! [1 ] I spent a bunch of time fiddling around trying to specify the encoding or find a version of the font containing this character. After some fiddling I realise that the actual error message that I should have been extracting from the log is this: LaTeX Warning: Command \LaTeX invalid in math mode on input line 88. LaTeX Warning: Command \TeX invalid in math mode on input line 88. ! You can't use `\spacefactor' in math mode. \@->\spacefactor \@m {} l.88 \(\mathrm{\LaTeX} \) printing by running \sphinxcode{\sphinxupquote{init... Sorry, but I'm not programmed to handle this case; I'll just pretend that you didn't ask for it. If you're in the wrong mode, you might be able to return to the right one by typing `I}' or `I$' or `I\par'. Missing character: There is no ? in font cmex10! [1 ] So what has happened here is that the latex compiler realised \LaTeX was invalid and then replaced it with \TeX and then realised that that was also invalid. Then the compiler *apologised* and decided to "pretend" I didn't ask for "it" and inserted some gibberish including ? (most likely in latin1 rather than utf8) and then it failed because the font didn't have a character for ?. The fix is redefining the \LaTeX macro and has nothing to do with ? or the fonts or anything else. The whole process could have been a lot quicker if the last line of the log output was simply: LaTeX Error: Command \LaTeX invalid in math mode on input line 88. -- Oscar From cranky.frankie at gmail.com Sun Oct 25 07:29:06 2020 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Sun, 25 Oct 2020 07:29:06 -0400 Subject: [Tutor] Clearing the screen from the terminal In-Reply-To: References: <20201024220247.GA46864@cskk.homeip.net> Message-ID: Agreed about negative aspects of clearing the screen. But there is a reason. I'm doing version 1 of this program as terminal based, yet still Model View Controller. My hope is that, once it works in the terminal, I can then move the View part to PySimplegui without too much trouble. So those screen redraws will turn into GUI lists that get refreshed. Frank L. "Cranky Frankie" Palmeri, Risible Riding Raconteur & Writer WORK Hard - PLAY Hard - READ Hard - THINK Hard On Sat, Oct 24, 2020 at 7:20 PM Alan Gauld via Tutor wrote: > On 24/10/2020 23:02, Cameron Simpson wrote: > > > curses.setupterm() > > print(curses.tigetstr('clear_screen'), end='') > > Nice one, I'd never have thought of that. > I've only ever used the ti functions inside a curses program to > find out if some capability is actually supported by my terminal. > > -- > 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 alan.gauld at yahoo.co.uk Sun Oct 25 08:26:08 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 25 Oct 2020 12:26:08 +0000 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: On 25/10/2020 08:38, Manprit Singh wrote: >>>> genfx_ser(9, "a") > > > In the second function call , see the second argument is "a", which is > being passed to formal parameter lim in function definition, must create > an error , since range cannot accept a non integer value, but still > function call is returning a generator object. This is one of the differences between a generator and a function. You can assign the generator to a variable then iterate over it. Its only when you start the iteration that the code actually gets executed and the error raised. So for example: >>> def f(x,n): nums = x for i in range(n): yield nums nums = nums*10 + x >>> f(9,3) >>> list(f(9,3)) [9, 99, 999] >>> f(9,'a') >>> list(f(9,'a')) Traceback (most recent call last): File "", line 1, in list(f(9,'a')) File "", line 3, in f for i in range(n): TypeError: 'str' object cannot be interpreted as an integer >>> You could have multiple sequences stored in variables and then call whichever sequence is required depending on user input. But they are all based on the same generator function. > Is it a bug ? No, its a feature! :-) -- 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 ayeshanarangx at gmail.com Sun Oct 25 06:04:22 2020 From: ayeshanarangx at gmail.com (ayesha narang) Date: Sun, 25 Oct 2020 15:34:22 +0530 Subject: [Tutor] Problem in terminal Message-ID: <002BEDC6-4E2F-441D-8A53-19843FF38B6E@gmail.com> Hello, I am a beginner currently learning how to use python. I am using Atom- the editor (atom.io ), where I have written some programs and saved in a folder. However, when I try to find this folder in my terminal, it isn?t visible, as seen in the screenshot below. Please help me out with this and tell me what the problem is. Looking forward toy our response. From alan.gauld at yahoo.co.uk Sun Oct 25 09:20:16 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 25 Oct 2020 13:20:16 +0000 Subject: [Tutor] Problem in terminal In-Reply-To: <002BEDC6-4E2F-441D-8A53-19843FF38B6E@gmail.com> References: <002BEDC6-4E2F-441D-8A53-19843FF38B6E@gmail.com> Message-ID: On 25/10/2020 10:04, ayesha narang wrote: > Hello, I am a beginner currently learning how to use python. > I am using Atom- the editor (atom.io ), where I have written some programs and saved in a folder. > However, when I try to find this folder in my terminal, it isn?t visible, OK, we'll need a bit more information. What OS are you using? What folder are you specifying when you save the file? > as seen in the screenshot below. This is a text only list so any binary attachments get stripped by the server for security. Can you send a cut n paste of the terminal output in the body of you mail message please? -- 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 cs at cskk.id.au Sun Oct 25 21:32:20 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 26 Oct 2020 12:32:20 +1100 Subject: [Tutor] Clearing the screen from the terminal In-Reply-To: References: Message-ID: <20201026013220.GA98915@cskk.homeip.net> On 25Oct2020 07:29, Cranky Frankie wrote: >Agreed about negative aspects of clearing the screen. But there is a >reason. I'm doing version 1 of this program as terminal based, yet still >Model View Controller. My hope is that, once it works in the terminal, I >can then move the View part to PySimplegui without too much trouble. So >those screen redraws will turn into GUI lists that get refreshed. Then you probably want Alan's approach, and use curses. You can write MVC style with it, and should aid the shift to PySimplegui later (not to mention maybe supporting mixed mode, where you can run in terminal mode if there is no GUI, such as when sshed into a host). I think Alan even has an introductory document for going this way. Cheers, Cameron Simpson From manpritsinghece at gmail.com Sun Oct 25 22:15:58 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Mon, 26 Oct 2020 07:45:58 +0530 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: Dear Sir, Thanks for explaining. So if fx(a, b) is a call to a generator function, where both a & b needs to be an integer, calling fx(a, "b") will raise an error when we are actually executing it (like doing sum(fx(a, "b"))), not at the time of assigning this call to a variable . This is clear to me . But still i raise objection, according to me if i am calling and then executing ser_gen(a, b) for any integer value less than 1 , for the below written generator function definition, it must provide an empty iterable, the definition is given below: def ser_gen(no, order): f_no = no for i in range(order): yield f_no f_no = f_no*10 + no all(ser_gen(9, -3)) Returns True that says, there is an empty iterable inside all( ) Regards Manprit Singh if this function On Sun, Oct 25, 2020 at 5:56 PM Alan Gauld via Tutor wrote: > On 25/10/2020 08:38, Manprit Singh wrote: > > >>>> genfx_ser(9, "a") > > > > > > In the second function call , see the second argument is "a", which is > > being passed to formal parameter lim in function definition, must > create > > an error , since range cannot accept a non integer value, but still > > function call is returning a generator object. > > This is one of the differences between a generator and a function. > You can assign the generator to a variable then iterate over it. > Its only when you start the iteration that the code actually gets > executed and the error raised. > > So for example: > > >>> def f(x,n): > nums = x > for i in range(n): > yield nums > nums = nums*10 + x > > > >>> f(9,3) > > >>> list(f(9,3)) > [9, 99, 999] > >>> f(9,'a') > > >>> list(f(9,'a')) > Traceback (most recent call last): > File "", line 1, in > list(f(9,'a')) > File "", line 3, in f > for i in range(n): > TypeError: 'str' object cannot be interpreted as an integer > >>> > > You could have multiple sequences stored in variables > and then call whichever sequence is required depending > on user input. But they are all based on the same > generator function. > > > Is it a bug ? > > No, its a feature! :-) > > -- > 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 cs at cskk.id.au Mon Oct 26 00:55:26 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 26 Oct 2020 15:55:26 +1100 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: <20201026045526.GA68220@cskk.homeip.net> On 26Oct2020 07:45, Manprit Singh wrote: >But still i raise objection, according to me if i am calling and then >executing ser_gen(a, b) for any integer value less than 1 , for the below >written generator function definition, it must provide an empty iterable, >the definition is given below: > >def ser_gen(no, order): > f_no = no > for i in range(order): > yield f_no > f_no = f_no*10 + no > >all(ser_gen(9, -3)) Returns True that says, there is an empty iterable >inside all( ) Returns True for me, too. Which is expected behaviour. It is not clear to me what your objection is about. Cheers, Cameron Simpson From ireneprajay at gmail.com Sun Oct 25 20:26:28 2020 From: ireneprajay at gmail.com (Baptista Albert) Date: Sun, 25 Oct 2020 19:26:28 -0500 Subject: [Tutor] Flask-Python Beginner Message-ID: Hi, I doing a small project by myself on building a resume parser. I wrote the Python script and it works just fine with the document path hardcoded in it. I am not trying to convert into an API using flask and am facing a lot of issues, resumeparser2.py: import os import docx2txt import spacy from spacy.matcher import Matcher from pyresparser import ResumeParser import pandas as pd import re from flask import Flask, request from flask_restful import Resource, Api import nltk from nltk.corpus import stopwords STOPWORDS = set(stopwords.words('english')) app = Flask(__name__) api= Api(app) #@app.route('/resumeparser2', methods=['GET']) #extracting data from docx class resparse: def resumeparser2(self) : doc_path=(r"C:\U sers\Ajay Charles\Downloads\Baptista Albert - BA resume.docx") temp = docx2txt.process(doc_path) text = [line.replace('\t', ' ') for line in temp.split('\n') if line] return_text= ' '.join(text) nlp = spacy.load('en_core_web_sm') nlp_text = nlp(return_text) for chunk in nlp_text.noun_chunks: word_chunk = (chunk.text) matcher = Matcher(nlp.vocab) #extracting Full name pattern = [{'POS':'PROPN'},{'POS':"PROPN"},{'POS':'PROPN'},{'POS': 'PROPN'}] matcher.add('NAME',None, pattern) matches = matcher(nlp_text) for match_id, start, end in matches: span = nlp_text[start:end] return(span) break phone = re.findall(re.compile(r'\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\( \d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}'), return_text) for ph_num in phone: return(ph_num) email1 = re.findall(r"([^@|\s]+@[^@]+\.[^@|\s]+)" , return_text) for email in email1: return (email) address = re.findall(re.compile(r'Alabama|AL|Alaska|AK|Arizona|AZ| Arkansas|AR|California|CA|Colorado|CO|Connecticut|CT|Delaware|DE|Florida|FL| Georgia|GA|Hawaii|HI|Idaho|ID|Illinois|IL|Indiana|IN|Iowa|IA|Kansas|KS| Kentucky|KY|Louisiana|LA|Maine|ME|Maryland|MD|Massachusetts|MA|Michigan|MI| Minnesota|MN|Mississippi|MS|Missouri|MO|Montana|MT|Nebraska|NE|Nevada|NV| New Hampshire|NH|New Jersey|NJ|New Mexico|NM|New York|NY|North Carolina|NC| North Dakota|ND|Ohio|OH|Oklahoma|OK|Oregon|OR|Pennsylvania|PA|Rhode Island| RI|South Carolina|SC|South Dakota|SD|Tennessee|TN|Texas|TX|Utah|UT|Vermont| VT|Virginia|VA|Washington|WA|West Virginia|WV|Wisconsin|WI|Wyoming|WY' ),return_text) for addr in address: return(addr) break #resumeparser2() api.add_resource(resparse,'/resumeparser2') #def get_tasks(): # return resumeparser2() if __name__ == '__main__': app.run() Errors: PS C:\Users\Ajay Charles\Downloads\Python\PythonProjects> & C:/Python38/python.exe "c:/Users/Ajay Charles/Downloads/Python/PythonProjects/resumeparser2.py" Traceback (most recent call last): File "c:/Users/Ajay Charles/Downloads/Python/PythonProjects/resumeparser2.py", line 58, in api.add_resource(resparse,'/resumeparser2') File "C:\Users\Ajay Charles\AppData\Roaming\Python\Python38\site-packages\flask_restful\__init__.py", line 392, in add_resource self._register_view(self.app, resource, *urls, **kwargs) File "C:\Users\Ajay Charles\AppData\Roaming\Python\Python38\site-packages\flask_restful\__init__.py", line 432, in _register_view resource_func = self.output(resource.as_view(endpoint, *resource_class_args, AttributeError: type object 'resparse' has no attribute 'as_view' Please do let me know where I am going wrong. -- Baptista Albert From alan.gauld at yahoo.co.uk Mon Oct 26 04:00:17 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 26 Oct 2020 08:00:17 +0000 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: On 26/10/2020 02:15, Manprit Singh wrote: > def ser_gen(no, order): > f_no = no > for i in range(order): > yield f_no > f_no = f_no*10 + no > > all(ser_gen(9, -3)) Returns True that says, there is an empty iterable > inside all( ) OK, I confess that surprised me as I expected the "faulty" ser_gen to return none since it falls off the bottom of the function. But it seems a generator raises StopIteration when that happens: >>> list(ser_gen(9,3)) [9, 99, 999] >>> list(ser_gen(9,-3)) [] >>> next(ser_gen(9,-3)) Traceback (most recent call last): File "", line 1, in next(ser_gen(9,-3)) StopIteration And that in turn results in all() and list() seeing an empty sequence. This should be in the language reference document under generator functions but I haven't gone looking for it... An exercise for the reader? However, the real takeaway from this is that you should check for invalid input at the start of your functions. And ensure that there are no default exists in a function that should return something. If you defined the function as: def ser_gen(no, order): no,order = int(no),int(order) if order <= 0: raise ValueError("order must be > 0") f_no = no for i in range(order): yield f_no f_no = f_no*10 + no else: raise StopIteration # make explicit There would be no surprises and there would be useful errors. -- 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 Mon Oct 26 04:03:42 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 26 Oct 2020 08:03:42 +0000 Subject: [Tutor] Clearing the screen from the terminal In-Reply-To: <20201026013220.GA98915@cskk.homeip.net> References: <20201026013220.GA98915@cskk.homeip.net> Message-ID: On 26/10/2020 01:32, Cameron Simpson wrote: > Then you probably want Alan's approach, and use curses. You can write > MVC style with it, and should aid the shift to PySimplegui later (not to > mention maybe supporting mixed mode, where you can run in terminal mode > if there is no GUI, such as when sshed into a host). > > I think Alan even has an introductory document for going this way. :-) It just so happens... I'm on the cusp of publishing this somewhere accessible, but I can send you (the OP) the latest draft if you are interested. It includes a section giving a full case study on writing an MVC style application using curses. (A kind of simple spreadsheet.) -- 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 Mon Oct 26 04:06:31 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 26 Oct 2020 08:06:31 +0000 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: <20201026045526.GA68220@cskk.homeip.net> References: <20201026045526.GA68220@cskk.homeip.net> Message-ID: On 26/10/2020 04:55, Cameron Simpson wrote: >> def ser_gen(no, order): >> f_no = no >> for i in range(order): >> yield f_no >> f_no = f_no*10 + no >> >> all(ser_gen(9, -3)) Returns True that says, there is an empty iterable >> inside all( ) > > Returns True for me, too. Which is expected behaviour. > > It is not clear to me what your objection is about. To be honest it surprised me too. I expected the function to fall off the bottom and return none. But in fact it raises a StopIteration instead, which all() interprets as an empty sequence. -- 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 Mon Oct 26 04:14:00 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 26 Oct 2020 08:14:00 +0000 Subject: [Tutor] Flask-Python Beginner In-Reply-To: References: Message-ID: On 26/10/2020 00:26, Baptista Albert wrote: > Hi, > > I doing a small project by myself on building a resume parser. I wrote the > Python script and it works just fine with the document path hardcoded in it. > > I am not trying to convert into an API using flask and am facing a lot o> issues, I've used Flask a couple of times and it should be good for your purpose. But in common with other frameworks you need to bend your code to its rules. > app = Flask(__name__) > api= Api(app) > #@app.route('/resumeparser2', methods=['GET']) > > #extracting data from docx > > class resparse: > > def resumeparser2(self) : > > > api.add_resource(resparse,'/resumeparser2') > > Errors: > > PS C:\Users\Ajay Charles\Downloads\Python\PythonProjects> & > C:/Python38/python.exe "c:/Users/Ajay > Charles/Downloads/Python/PythonProjects/resumeparser2.py" > Traceback (most recent call last): > File "c:/Users/Ajay > Charles/Downloads/Python/PythonProjects/resumeparser2.py", line 58, in > > api.add_resource(resparse,'/resumeparser2') > AttributeError: type object 'resparse' has no attribute 'as_view' The error is quite correctly telling you that your resparse object does not have an attribute as_view. in fact resparse is a class, I suspect it should be an instance? And it should either be a descendant of some flask class or it should provide an interface that includes the methods that Flask will call, in this case as_view() as a minimum. (It may be that you are missing a decorator somewhere, as I recall flask uses a lot of decorators to add its own methods to things) But you'll need to check the Flask docs to find out. -- 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 manpritsinghece at gmail.com Mon Oct 26 05:23:59 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Mon, 26 Oct 2020 14:53:59 +0530 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: <20201026045526.GA68220@cskk.homeip.net> Message-ID: Dear Sir, So from the series of mails on this topic, i have learned following facts , supported with experiment given below : >>> def ser_gen(no, order): f_no = no for i in range(order): yield f_no f_no = f_no*10 + no >>> next(ser_gen(9, "A")) # execution of generator function call with an undesired value of second argument ("A") in function call Traceback (most recent call last): File "", line 1, in next(ser_gen(9, "A")) File "", line 3, in ser_gen for i in range(order): TypeError: 'str' object cannot be interpreted as an integer >>> next(ser_gen(9, -3)) # execution of generator function call with an undesired value of second argument (-3) in function call Traceback (most recent call last): File "", line 1, in next(ser_gen(9, -3)) StopIteration >>> 1) In the first execution of the function call, since "A" is string , and range cannot accept a string, hence Type error is generated . 2) In the second execution of the function call, since -3 is negative integer, the for loop never got executed, The function has returned an empty iterator, this is proved with the fact that next( ) has caused StopIteration . Just need to know if you agree with these two points. And finally a mechanism is needed in the program to deal with these unexpected behaviours - like exception handling . Regards Manprit Singh On Mon, Oct 26, 2020 at 1:40 PM Alan Gauld via Tutor wrote: > On 26/10/2020 04:55, Cameron Simpson wrote: > > >> def ser_gen(no, order): > >> f_no = no > >> for i in range(order): > >> yield f_no > >> f_no = f_no*10 + no > >> > >> all(ser_gen(9, -3)) Returns True that says, there is an empty > iterable > >> inside all( ) > > > > Returns True for me, too. Which is expected behaviour. > > > > It is not clear to me what your objection is about. > > To be honest it surprised me too. I expected the function to fall > off the bottom and return none. But in fact it raises a > StopIteration instead, which all() interprets as an empty sequence. > > -- > 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 cs at cskk.id.au Mon Oct 26 05:35:54 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 26 Oct 2020 20:35:54 +1100 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: <20201026093554.GA90714@cskk.homeip.net> On 26Oct2020 08:06, Alan Gauld wrote: >On 26/10/2020 04:55, Cameron Simpson wrote: >>> def ser_gen(no, order): >>> f_no = no >>> for i in range(order): >>> yield f_no >>> f_no = f_no*10 + no >>> >>> all(ser_gen(9, -3)) Returns True that says, there is an empty iterable >>> inside all( ) >> >> Returns True for me, too. Which is expected behaviour. >> >> It is not clear to me what your objection is about. > >To be honest it surprised me too. I expected the function to fall >off the bottom and return none. But in fact it raises a >StopIteration instead, which all() interprets as an empty sequence. It didn't surprise me. It is just end of execution of a generator function. This is why I couldn't see what Manprit is concerned about. Cheers, Cameron Simpson From cs at cskk.id.au Mon Oct 26 05:47:48 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 26 Oct 2020 20:47:48 +1100 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: <20201026094748.GA3509@cskk.homeip.net> On 26Oct2020 14:53, Manprit Singh wrote: >So from the series of mails on this topic, i have learned following facts , >supported with experiment given below : >>>> def ser_gen(no, order): > f_no = no > for i in range(order): > yield f_no > f_no = f_no*10 + no > >>>> next(ser_gen(9, "A")) # execution of generator >function call with an undesired value of second argument ("A") in function >call >Traceback (most recent call last): > File "", line 1, in > next(ser_gen(9, "A")) > File "", line 3, in ser_gen > for i in range(order): >TypeError: 'str' object cannot be interpreted as an integer >>>> next(ser_gen(9, -3)) # execution of generator >function call with an undesired value of second argument (-3) in function >call >Traceback (most recent call last): > File "", line 1, in > next(ser_gen(9, -3)) >StopIteration >>>> > >1) In the first execution of the function call, since "A" is string , and >range cannot accept a string, hence Type error is generated . Yes. >2) In the second execution of the function call, since -3 is negative >integer, the for loop never got executed, The function has returned an >empty iterator, this is proved with the fact that next( ) has caused >StopIteration . Yes. Keep in mind that the function doesn't run at all until you first call next(). So the calling code doesn't know the iterator is empty until it tries to use it. Neither does the ser_gen function - it doesn't even reach the start of the for loop until you first call next(). >And finally a mechanism is needed in the program to deal with these >unexpected behaviours - like exception handling . Yes and no. Exceptions are just that - an indication of exceptional circumstances. And you'll also notice that calling next() on a generator which no longer has anything to yield raises StopIteration. The rule of thumb for exceptions is to only can those you know how to handle - that way the unexpected get out and provide you a good stack trace of where things went wrong. Otherwise you just end up hiding bugs. StopIteration is a little unusual. _Every_ generator raises StopIteration when you ask for the next value if there is no next value. But the commonest way to iterate is with a for loop. Look at this: for f_no in ser_gen(9, 5): print(f_no) This will yield 5 values, and then next time the for-loop seeks the next value, the generator raises StopIteration. And the for-loop expects that: it exits the loop when that exception is raised. The logic is like this: g = ser_gen(9, 5) # returns the generator while True: try: f_no = next(g) except StopIteration: break print(f_no) but more readable. Cheers, Cameron Simpson From PyTutor at DancesWithMice.info Mon Oct 26 06:09:57 2020 From: PyTutor at DancesWithMice.info (dn) Date: Mon, 26 Oct 2020 23:09:57 +1300 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: <20201026093554.GA90714@cskk.homeip.net> References: <20201026093554.GA90714@cskk.homeip.net> Message-ID: <937d90ca-bdf3-7910-55c7-f84d687311b2@DancesWithMice.info> On 26/10/2020 22:35, Cameron Simpson wrote: > On 26Oct2020 08:06, Alan Gauld wrote: >> On 26/10/2020 04:55, Cameron Simpson wrote: >>>> def ser_gen(no, order): >>>> f_no = no >>>> for i in range(order): >>>> yield f_no >>>> f_no = f_no*10 + no >>>> >>>> all(ser_gen(9, -3)) Returns True that says, there is an empty iterable >>>> inside all( ) >>> >>> Returns True for me, too. Which is expected behaviour. >>> >>> It is not clear to me what your objection is about. >> >> To be honest it surprised me too. I expected the function to fall >> off the bottom and return none. But in fact it raises a >> StopIteration instead, which all() interprets as an empty sequence. > > It didn't surprise me. It is just end of execution of a generator function. > This is why I couldn't see what Manprit is concerned about. Obtaining same result to original code, but is the generator called correctly? >>> def ser_gen(no, order): ... f_no = no ... for i in range(order): ... yield f_no ... f_no = f_no*10 + no ... >>> all(ser_gen(9, -3)) True ### What is really going-on? ### Simplifying: >>> print( ser_gen( 9, -3 ) ) ### Even if the arguments are acceptable: >>> print(ser_gen(9, 3)) Is the presence of an object 'truthy', hence the all() result? -- Regards =dn From manpritsinghece at gmail.com Mon Oct 26 06:18:36 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Mon, 26 Oct 2020 15:48:36 +0530 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: <937d90ca-bdf3-7910-55c7-f84d687311b2@DancesWithMice.info> References: <20201026093554.GA90714@cskk.homeip.net> <937d90ca-bdf3-7910-55c7-f84d687311b2@DancesWithMice.info> Message-ID: Hi all, See all(iterable) will return True if iterable is empty also . Regards Manprit Singh On Mon, Oct 26, 2020 at 3:40 PM dn via Tutor wrote: > On 26/10/2020 22:35, Cameron Simpson wrote: > > On 26Oct2020 08:06, Alan Gauld wrote: > >> On 26/10/2020 04:55, Cameron Simpson wrote: > >>>> def ser_gen(no, order): > >>>> f_no = no > >>>> for i in range(order): > >>>> yield f_no > >>>> f_no = f_no*10 + no > >>>> > >>>> all(ser_gen(9, -3)) Returns True that says, there is an empty > iterable > >>>> inside all( ) > >>> > >>> Returns True for me, too. Which is expected behaviour. > >>> > >>> It is not clear to me what your objection is about. > >> > >> To be honest it surprised me too. I expected the function to fall > >> off the bottom and return none. But in fact it raises a > >> StopIteration instead, which all() interprets as an empty sequence. > > > > It didn't surprise me. It is just end of execution of a generator > function. > > This is why I couldn't see what Manprit is concerned about. > > > Obtaining same result to original code, but is the generator called > correctly? > > >>> def ser_gen(no, order): > ... f_no = no > ... for i in range(order): > ... yield f_no > ... f_no = f_no*10 + no > ... > >>> all(ser_gen(9, -3)) > > True > > > ### What is really going-on? > ### Simplifying: > > >>> print( ser_gen( 9, -3 ) ) > > > ### Even if the arguments are acceptable: > > >>> print(ser_gen(9, 3)) > > > Is the presence of an object 'truthy', hence the all() result? > -- > Regards =dn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From cranky.frankie at gmail.com Mon Oct 26 06:22:59 2020 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 26 Oct 2020 06:22:59 -0400 Subject: [Tutor] Clearing the screen from the terminal In-Reply-To: References: <20201026013220.GA98915@cskk.homeip.net> Message-ID: Please post the document when you get a chance. I'm sure we'd all love to see it. Thanks. Frank L. "Cranky Frankie" Palmeri, Risible Riding Raconteur & Writer WORK Hard - PLAY Hard - READ Hard - THINK Hard On Mon, Oct 26, 2020 at 4:05 AM Alan Gauld via Tutor wrote: > On 26/10/2020 01:32, Cameron Simpson wrote: > > > Then you probably want Alan's approach, and use curses. You can write > > MVC style with it, and should aid the shift to PySimplegui later (not to > > mention maybe supporting mixed mode, where you can run in terminal mode > > if there is no GUI, such as when sshed into a host). > > > > I think Alan even has an introductory document for going this way. > > :-) > > It just so happens... I'm on the cusp of publishing this somewhere > accessible, but I can send you (the OP) the latest draft if you are > interested. It includes a section giving a full case study on > writing an MVC style application using curses. (A kind of simple > spreadsheet.) > > > -- > 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 alan.gauld at yahoo.co.uk Mon Oct 26 07:04:21 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 26 Oct 2020 11:04:21 +0000 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: <20201026045526.GA68220@cskk.homeip.net> Message-ID: On 26/10/2020 09:23, Manprit Singh wrote: >>>> next(ser_gen(9, "A")) # execution of generator > TypeError: 'str' object cannot be interpreted as an integer >>>> next(ser_gen(9, -3)) # execution of generator > StopIteration >>>> > > 1) In the first execution of the function call, since "A" is string , and > range cannot accept a string, hence Type error is generated . > 2) In the second execution of the function call, since -3 is negative > integer, the for loop never got executed, The function has returned an > empty iterator, this is proved with the fact that next( ) has caused > StopIteration . Yes, that is correct. > And finally a mechanism is needed in the program to deal with these > unexpected behaviours - like exception handling . Yes, the user of the function should handle the exceptions if possible. But the writer of the function - you - should test for and raise any errors that may cause unexpected problems. That's why, in my version, I added the int() conversions(which will raise Value or type errors for invalid input). And raised a ValueError for zero/negative second values. You could of course catch those internally and return an empty list which would mean the function always returned an iterator of some sort, or you could raise StopIteration for all errors which would have a similar impact. But then the user would be blissfully unaware of their invalid data issues and that could cause worse problems later. It's better to raise accurate and descriptive errors as early as possible. -- 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 cs at cskk.id.au Mon Oct 26 18:12:08 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Tue, 27 Oct 2020 09:12:08 +1100 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: Message-ID: <20201026221208.GA27651@cskk.homeip.net> On 26Oct2020 15:48, Manprit Singh wrote: >See all(iterable) will return True if iterable is empty also . Yes. You may find it helpful to think of all() as testing for failure: any item which is false. An empty iterable has no false elements, so all() returns True. Cheers, Cameron Simpson From bouncingcats at gmail.com Mon Oct 26 23:02:05 2020 From: bouncingcats at gmail.com (David) Date: Tue, 27 Oct 2020 14:02:05 +1100 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: <20201026221208.GA27651@cskk.homeip.net> References: <20201026221208.GA27651@cskk.homeip.net> Message-ID: On Tue, 27 Oct 2020 at 09:13, Cameron Simpson wrote: > Yes. You may find it helpful to think of all() as testing for failure: > any item which is false. An empty iterable has no false elements, so > all() returns True. And this is why Python tutors never ask their students if they have done all() of their homework. From tcm2118 at columbia.edu Mon Oct 26 23:12:49 2020 From: tcm2118 at columbia.edu (T. M.) Date: Mon, 26 Oct 2020 21:12:49 -0600 Subject: [Tutor] taking support of strings in solving numerical problems In-Reply-To: References: <20201026221208.GA27651@cskk.homeip.net> Message-ID: Hahaha On Mon, Oct 26, 2020 at 9:03 PM David wrote: > On Tue, 27 Oct 2020 at 09:13, Cameron Simpson wrote: > > > Yes. You may find it helpful to think of all() as testing for failure: > > any item which is false. An empty iterable has no false elements, so > > all() returns True. > > And this is why Python tutors never ask their students if they have done > all() of their homework. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- 1(505)701-9323 From alan.gauld at yahoo.co.uk Tue Oct 27 13:50:19 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 27 Oct 2020 17:50:19 +0000 Subject: [Tutor] Something weird on tutor References: <7c5f7f7d-adc0-dd15-cc33-9e8574896446.ref@yahoo.co.uk> Message-ID: <7c5f7f7d-adc0-dd15-cc33-9e8574896446@yahoo.co.uk> Something weird is happening I'm getting dozens of bounce messages resulting in folks being disabled on the tutor list. Approximately half the members are now disabled! It looks like some kind of DoS attack may be triggering it. But if you stop getting tutor mails check your subscription settings, mail may be turned off, if so try turning it on. If that doesn't work let me know please. Meantime I'll try to find out what's happening! -- 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 0007sd at gmail.com Tue Oct 27 15:37:40 2020 From: 0007sd at gmail.com (Steven Douglas) Date: Tue, 27 Oct 2020 15:37:40 -0400 Subject: [Tutor] Re-Project Vector Datasets Message-ID: I am writing a script that re-projects vector datasets in a folder. From this, it will then create a script tool. The final script tool will have only two textboxes for input. The first will be to input the target data folder and the second calls for a shape file or featureclass that calls for the target projection dataset. In short, it will re-project the shapefile vector datasets in the folder to match the target dataset's projection. ***************** The script will not contain any hard-coded values such as dataset, path, or projection names. Here's what I've got so far (error mentioned afterwards below): import arcpy #set up the paths targetFC = "C:\\GISData\\CountyLines.shp" folderEnvironment = "C:\\GISData" #get spatial reference for the target feature class targetDescribe = arcpy.Describe(targetFC) targetSR = targetDescribe.SpatialReference targetSRName = targetSR.Name # Get a list of my feature classes arcpy.env.workspace = folderEnvironment listOfFCs = arcpy.ListFeatureClasses() #Loop through the list of FCs for currentFC in listOfFCs: #Read the spatial reference of the current one currentFCDescribe = arcpy.Describe(currentFC) currentFCSR = currentFCDescribe.SpatialReference currentFCSRName = currentFCSR.Name if currentFCSRName != targetSRName: print ("Spatial references don't match") else: print ("Spatial references do match") if currentFCSRName == targetSRName: else: # Determine the new output feature class path and name outCS = currentFC[:-4] +"_projected.shp" arcpy.Project_management(currentFC, outCS, targetSR) rootName = currentFC[:-4] print (rootName) print (rootName +"_projected.shp") ***************** Error: IndentationError: expected an Indented block -- on line 36 (the last "else:" It's not working. Please help! From Chukwunonso.Oranyeli at ssfs.org Tue Oct 27 19:15:08 2020 From: Chukwunonso.Oranyeli at ssfs.org (Chukwunonso Oranyeli) Date: Tue, 27 Oct 2020 23:15:08 +0000 Subject: [Tutor] (no subject) Message-ID: Hello, I have been using python for a while and I have a question for my code. How do I write a program that returns a multiplication table of a number up to 12. For example multiplication_table(6) would return "6 12 18 24 30 36 42 48 54 60 66 72 " From alan.gauld at yahoo.co.uk Tue Oct 27 21:01:58 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 28 Oct 2020 01:01:58 +0000 Subject: [Tutor] Re-Project Vector Datasets In-Reply-To: References: Message-ID: On 27/10/2020 19:37, Steven Douglas wrote: > if currentFCSRName == targetSRName: > > else: There is no body after the if so Python sees the else as being in the wrong place. If you must have an empty body use 'pass': if boolean_expression: pass else: # go for it... > Error: IndentationError: expected an Indented block -- on line 36 (the > last "else:" But usually you can invert the boolean logic to put what is in the else part into the if part. So in your example if not (currentFCSRName == targetSRName): # put the old 'else' code here # no else needed... OR if you prefer: if currentFCSRName != targetSRName: # put the old 'else' code here # no else needed... -- 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 Oct 27 21:05:15 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 28 Oct 2020 01:05:15 +0000 Subject: [Tutor] Multiplication table was: Re: (no subject) In-Reply-To: References: Message-ID: Please always put a meaningful subject line in the message. On 27/10/2020 23:15, Chukwunonso Oranyeli via Tutor wrote: > Hello, I have been using python for a while and I have a question for my code. > How do I write a program that returns a multiplication table of a number up to 12. For example > > multiplication_table(6) would return > > "6 12 18 24 30 36 42 48 54 60 66 72 " This smells a bit like homework which we don't do. But we can give hints. So I'll give you a hint. Look in the loops section of my tutorial(link below) -- 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 mistershilai at gmail.com Wed Oct 28 11:41:03 2020 From: mistershilai at gmail.com (Elliot Lee) Date: Wed, 28 Oct 2020 11:41:03 -0400 Subject: [Tutor] Pip Issue Message-ID: I think this is probably just a beginner?s issue and should be able to be fixed quickly, I?m just not sure how to do it. I was watching a tutorial about hosting a Discord Python bot on Heroku, but I?ve hit a problem where I can?t use the command ?pip install pipreqs?. ? This error results: ? I searched online for answers and it asked me to look for Python on the C local disk, but I cannot find it in there. I know I have Python installed, so I assumed I had to move my folder (with material for the bot) into that folder in order to access pip commands. What am I doing wrong? ? Thanks. ? Sent from [1]Mail for Windows 10 ? References Visible links 1. https://go.microsoft.com/fwlink/?LinkId=550986 From samira.schadt at gmail.com Wed Oct 28 13:37:15 2020 From: samira.schadt at gmail.com (Samira Schadt) Date: Wed, 28 Oct 2020 13:37:15 -0400 Subject: [Tutor] How to import a module Message-ID: <427F627F-BEA1-48DB-8613-D787C08B1DE7@gmail.com> Dear tutor, I am trying to import a file (actually a class that is used in a file), however it tells me it cannot find it. Sent from my iPhone From alan.gauld at yahoo.co.uk Wed Oct 28 17:23:44 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 28 Oct 2020 21:23:44 +0000 Subject: [Tutor] How to import a module In-Reply-To: <427F627F-BEA1-48DB-8613-D787C08B1DE7@gmail.com> References: <427F627F-BEA1-48DB-8613-D787C08B1DE7@gmail.com> Message-ID: On 28/10/2020 17:37, Samira Schadt wrote: > Dear tutor, > I am trying to import a file ... it tells me it cannot find it. Never summarise an error, always post the entire error message, it is full of useful details. Also if you have a problem with code show us the code, don't make us guess. If your class, MyClass is in a file called MyModule.py then you should be able to import the class with from MyModule import MyClass Note no '.py' after the file name. If thats what you are doing and you still get an error then we need to see the detail. -- 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 breamoreboy at gmail.com Wed Oct 28 17:24:42 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Wed, 28 Oct 2020 21:24:42 +0000 Subject: [Tutor] Pip Issue In-Reply-To: References: Message-ID: On 28/10/2020 15:41, Elliot Lee wrote: > I think this is probably just a beginner?s issue and should be able to be > fixed quickly, I?m just not sure how to do it. I was watching a tutorial > about hosting a Discord Python bot on Heroku, but I?ve hit a problem where > I can?t use the command ?pip install pipreqs?. > > This error results: > Looks as if you've put up an attachment which gets stripped by this mailing list so please cut and paste the full traceback. > I searched online for answers and it asked me to look for Python on the C > local disk, but I cannot find it in there. I know I have Python installed, > so I assumed I had to move my folder (with material for the bot) into that > folder in order to access pip commands. What am I doing wrong? > Please see this https://docs.python.org/3/installing/index.html#work-with-multiple-versions-of-python-installed-in-parallel for how to run pip on windows. > Thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at gmail.com Wed Oct 28 17:30:08 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Wed, 28 Oct 2020 21:30:08 +0000 Subject: [Tutor] How to import a module In-Reply-To: <427F627F-BEA1-48DB-8613-D787C08B1DE7@gmail.com> References: <427F627F-BEA1-48DB-8613-D787C08B1DE7@gmail.com> Message-ID: On 28/10/2020 17:37, Samira Schadt wrote: > Dear tutor, > I am trying to import a file (actually a class that is used in a file), however it tells me it cannot find it. > Please start here https://docs.python.org/3/install/index.html#modifying-python-s-search-path -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From sergio_r at mail.com Thu Oct 29 12:37:24 2020 From: sergio_r at mail.com (Sergio Rojas) Date: Thu, 29 Oct 2020 17:37:24 +0100 Subject: [Tutor] Python (one variable) Equation Solver Message-ID: Hell folks, ?? A Python (one variable) Equation Solver is available at ?? [1]http://sergior.pythonanywhere.com/ ? ?? It will be there for a few months as the server delete it ?? after a while. In any case, one could ?? us http://pythonanywhere.com to try ?? python web application via flask. ? Regards, ? Sergio ? References Visible links 1. http://sergior.pythonanywhere.com/ From manpritsinghece at gmail.com Thu Oct 29 22:52:24 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 30 Oct 2020 08:22:24 +0530 Subject: [Tutor] Confusion about definition of proper subset in python set Message-ID: Dear sir , Consider explanation given about set < other in python official documentation Test whether the set is a proper subset of *other*, that is, set <= other and set != other. This confuses me actually. set <= other and set != other , how it is possible at same time ? As far as i know, if S is a set and ss is its proper subset, then ss is strictly contained in S and necessarily excludes at least one member of S. Need some light on it. Regards Manprit Singh From PyTutor at DancesWithMice.info Thu Oct 29 23:29:53 2020 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 30 Oct 2020 16:29:53 +1300 Subject: [Tutor] Confusion about definition of proper subset in python set In-Reply-To: References: Message-ID: <15d08ec5-5634-fdc4-b404-c70c0a3feded@DancesWithMice.info> On 30/10/2020 15:52, Manprit Singh wrote: > Dear sir , > > Consider explanation given about set < other in python official > documentation > > Test whether the set is a proper subset of *other*, that is, set <= other > and set != other. > > This confuses me actually. > > set <= other and set != other , how it is possible at same time ? > > As far as i know, if S is a set and ss is its proper subset, then ss is > strictly contained in S and necessarily excludes at least one member of S. > > Need some light on it. Create some sample set-data including identical sets, exclusive sets, and super- plus sub-sets. Run tests in the REPL, and show us how you have proven the above, or otherwise... -- Regards =dn From tcm2118 at columbia.edu Thu Oct 29 23:02:39 2020 From: tcm2118 at columbia.edu (T. M.) Date: Thu, 29 Oct 2020 21:02:39 -0600 Subject: [Tutor] Confusion about definition of proper subset in python set In-Reply-To: References: Message-ID: Same On Thursday, October 29, 2020, Manprit Singh wrote: > Dear sir , > > Consider explanation given about set < other in python official > documentation > > Test whether the set is a proper subset of *other*, that is, set <= other > and set != other. > > This confuses me actually. > > set <= other and set != other , how it is possible at same time ? > > As far as i know, if S is a set and ss is its proper subset, then ss is > strictly contained in S and necessarily excludes at least one member of S. > > Need some light on it. > > Regards > Manprit Singh > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- 1(505)701-9323 From alan.gauld at yahoo.co.uk Fri Oct 30 05:00:02 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 30 Oct 2020 09:00:02 +0000 Subject: [Tutor] Confusion about definition of proper subset in python set In-Reply-To: References: Message-ID: On 30/10/2020 02:52, Manprit Singh wrote: > Test whether the set is a proper subset of *other*, that is, set <= other > and set != other. > > This confuses me actually. > > set <= other and set != other , how it is possible at same time ? Very easily. S = {1,2,3} ss = {1} Now ss is a subset of S. But ss is not equal to S. Therefore ss is a proper subset of S. What is confusing you? > As far as i know, if S is a set and ss is its proper subset, then ss is > strictly contained in S and necessarily excludes at least one member of S. That is correct and exactly what the documentation says. -- 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 manpritsinghece at gmail.com Fri Oct 30 11:23:21 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 30 Oct 2020 20:53:21 +0530 Subject: [Tutor] program to find index of every occurrence of a particular word in a string Message-ID: Dear sir , Consider a string st1 = "I am a boy, i am an engineer, i am a genius" i have to find the index of every occurrence word "am" in the string st1. i have written a program below: st1 = "I am a boy, i am an engineer, i am a genius" w ="am" for i in range(len(st1)): if st1.find(w, i, i + len(w)) != -1: print(i) need to know, if this problem can be done in a more clean way ? Kindly give some hints so that i can rewrite it in a more clean and clear way . Regards Manprit Singh From manpritsinghece at gmail.com Fri Oct 30 12:27:10 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 30 Oct 2020 21:57:10 +0530 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: Dear sir , Consider this code for this problem : st1 = "I am a boy, i am an engineer, i am a genius" w ="am" for i in range(st1.rfind(w)+1): if st1[i:i+len(w)] == w: print(i) Regards Manprit Singh On Fri, Oct 30, 2020 at 8:53 PM Manprit Singh wrote: > Dear sir , > > Consider a string > st1 = "I am a boy, i am an engineer, i am a genius" > > i have to find the index of every occurrence word "am" in the string st1. > i have written a program below: > > st1 = "I am a boy, i am an engineer, i am a genius" > w ="am" > for i in range(len(st1)): > if st1.find(w, i, i + len(w)) != -1: > print(i) > need to know, if this problem can be done in a more clean way ? Kindly > give some hints so that i can rewrite it in a more clean and clear way . > > Regards > Manprit Singh > From manpritsinghece at gmail.com Fri Oct 30 12:55:51 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Fri, 30 Oct 2020 22:25:51 +0530 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: Dear sir , Have tried one more and found it quite good : st1 = "I am a boy, i am an engineer, i am a genius" w ="am" ge = (i for i in range(st1.rfind(w) + 1) if st1.startswith(w, i)) print(*ge) Regards Manprit singh On Fri, Oct 30, 2020 at 9:57 PM Manprit Singh wrote: > Dear sir , > Consider this code for this problem : > st1 = "I am a boy, i am an engineer, i am a genius" > w ="am" > for i in range(st1.rfind(w)+1): > if st1[i:i+len(w)] == w: > print(i) > > Regards > Manprit Singh > > On Fri, Oct 30, 2020 at 8:53 PM Manprit Singh > wrote: > >> Dear sir , >> >> Consider a string >> st1 = "I am a boy, i am an engineer, i am a genius" >> >> i have to find the index of every occurrence word "am" in the string st1. >> i have written a program below: >> >> st1 = "I am a boy, i am an engineer, i am a genius" >> w ="am" >> for i in range(len(st1)): >> if st1.find(w, i, i + len(w)) != -1: >> print(i) >> need to know, if this problem can be done in a more clean way ? Kindly >> give some hints so that i can rewrite it in a more clean and clear way . >> >> Regards >> Manprit Singh >> > From breamoreboy at gmail.com Fri Oct 30 11:41:00 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 30 Oct 2020 15:41:00 +0000 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: On 30/10/2020 15:23, Manprit Singh wrote: > Dear sir , > > Consider a string > st1 = "I am a boy, i am an engineer, i am a genius" > > i have to find the index of every occurrence word "am" in the string st1. i > have written a program below: > > st1 = "I am a boy, i am an engineer, i am a genius" > w ="am" > for i in range(len(st1)): > if st1.find(w, i, i + len(w)) != -1: > print(i) > need to know, if this problem can be done in a more clean way ? Kindly give > some hints so that i can rewrite it in a more clean and clear way . I suggest that you rewrite it so that it works, e.g. in a string like "spam spam spam" it will find all of the "am"s. Then rewrite it again, starting by getting rid of the 'range(len' which is almost always a code smell in python. > > Regards > Manprit Singh > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at yahoo.co.uk Fri Oct 30 16:17:43 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 30 Oct 2020 20:17:43 +0000 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: On 30/10/2020 15:23, Manprit Singh wrote: > st1 = "I am a boy, i am an engineer, i am a genius" > > i have to find the index of every occurrence word "am" in the string st1. i > have written a program below: > need to know, if this problem can be done in a more clean way ? Kindly give > some hints so that i can rewrite it in a more clean and clear way . You want to keep searching until thee are no more occurences. Sounds like a while loop rater than a for... >>> st1 = "I am a boy, i am an engineer, i am a genius" >>> help(st1.find) Help on built-in function find: find(...) method of builtins.str instance S.find(sub[, start[, end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. >>> n = 0 >>> while n != -1: n = st1.find('am', n+1) if n != -1: print(n) 2 14 32 >>> -- 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 cs at cskk.id.au Fri Oct 30 17:28:36 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 31 Oct 2020 08:28:36 +1100 Subject: [Tutor] Confusion about definition of proper subset in python set In-Reply-To: References: Message-ID: <20201030212836.GA55881@cskk.homeip.net> On 30Oct2020 09:00, Alan Gauld wrote: >On 30/10/2020 02:52, Manprit Singh wrote: >> Test whether the set is a proper subset of *other*, that is, set <= >> other and set != other. >> >> This confuses me actually. >> >> set <= other and set != other , how it is possible at same time ? > >Very easily. I think Manprit Singh has confused "subset" (set <= other) and proper subset (set < other). Well, not confused, because he's clearly well aware of the distinction. But confused about the docs. He's correctly pointing out that being a proper subset excludes the "=" part of "<=". But I can't find anything in the documentation talking specificly about "proper subsets", which are themselves a proper subset of subsets in general. The docs only talk about "subsets", which is what issubset() tests, along with the <= operator between sets. Manprit: where in the docs did you find the term "proper subset"? I can't see it. You're correct about the definition, but as far as I can see the documents don't bother with that. >> Test whether the set is a proper subset of *other*, that is, set <= >> other and set != other. Is this a task request from a tutorial? If so, it likely exists because the definitions of sets in Python do not directly address this, and this is an exercise to _construct_ a "proper subset" test _from_ the facilities available in the language. Which is easy. Cheers, Cameron Simpson From robertvstepp at gmail.com Fri Oct 30 18:14:23 2020 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 30 Oct 2020 17:14:23 -0500 Subject: [Tutor] Confusion about definition of proper subset in python set In-Reply-To: <20201030212836.GA55881@cskk.homeip.net> References: <20201030212836.GA55881@cskk.homeip.net> Message-ID: <20201030221423.GM9135@Dream-Machine1> On Sat, Oct 31, 2020 at 08:28:36AM +1100, Cameron Simpson wrote: >On 30Oct2020 09:00, Alan Gauld wrote: >>On 30/10/2020 02:52, Manprit Singh wrote: >>> Test whether the set is a proper subset of *other*, that is, set <= >>> other and set != other. >>> >>> This confuses me actually. >>> >>> set <= other and set != other , how it is possible at same time ? >> >>Very easily. > >I think Manprit Singh has confused "subset" (set <= other) and proper >subset (set < other). Well, not confused, because he's clearly well >aware of the distinction. But confused about the docs. > >He's correctly pointing out that being a proper subset excludes the "=" >part of "<=". But I can't find anything in the documentation talking >specificly about "proper subsets", which are themselves a proper subset >of subsets in general. > >The docs only talk about "subsets", which is what issubset() tests, >along with the <= operator between sets. > >Manprit: where in the docs did you find the term "proper subset"? I >can't see it. I think that he is referring to: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ issubset(other) set <= other Test whether every element in the set is in other. set < other Test whether the set is a proper subset of other, that is, set <= other and set != other. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -- Wishing you only the best, boB Stepp From manpritsinghece at gmail.com Fri Oct 30 19:35:45 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 31 Oct 2020 05:05:45 +0530 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: Dear Sir, Any pacific reason for writing n+1 inside n = st1.find('am', n+1), or you have just written it because the first position of "am" is not index 0, it is after index 0 . Regards Manprit Singh On Sat, Oct 31, 2020 at 1:47 AM Alan Gauld via Tutor wrote: > On 30/10/2020 15:23, Manprit Singh wrote: > > > st1 = "I am a boy, i am an engineer, i am a genius" > > > > i have to find the index of every occurrence word "am" in the string > st1. i > > have written a program below: > > > > need to know, if this problem can be done in a more clean way ? Kindly > give > > some hints so that i can rewrite it in a more clean and clear way . > > You want to keep searching until thee are no more occurences. > Sounds like a while loop rater than a for... > > >>> st1 = "I am a boy, i am an engineer, i am a genius" > >>> help(st1.find) > Help on built-in function find: > > find(...) method of builtins.str instance > S.find(sub[, start[, end]]) -> int > > Return the lowest index in S where substring sub is found, > such that sub is contained within S[start:end]. Optional > arguments start and end are interpreted as in slice notation. > > Return -1 on failure. > > >>> n = 0 > >>> while n != -1: > n = st1.find('am', n+1) > if n != -1: print(n) > > > 2 > 14 > 32 > >>> > > > -- > 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 cs at cskk.id.au Fri Oct 30 19:35:55 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sat, 31 Oct 2020 10:35:55 +1100 Subject: [Tutor] Confusion about definition of proper subset in python set In-Reply-To: <20201030221423.GM9135@Dream-Machine1> References: <20201030221423.GM9135@Dream-Machine1> Message-ID: <20201030233555.GA67601@cskk.homeip.net> On 30Oct2020 17:14, boB Stepp wrote: >I think that he is referring to: > >++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ >issubset(other) >set <= other >Test whether every element in the set is in other. > >set < other >Test whether the set is a proper subset of other, that is, set <= other >and set != other. Hmm, yes. It is even the text he cites. Manprit, the second definition says that the two conditions hold ("<= and !="). It does not imply that it is possible for these two conditions to hold: "= and !=". They didn't write "< and !=" because "<" is what that entry is defining. Cheers, Cameron Simpson From breamoreboy at gmail.com Fri Oct 30 14:40:52 2020 From: breamoreboy at gmail.com (Mark Lawrence) Date: Fri, 30 Oct 2020 18:40:52 +0000 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: On 30/10/2020 16:55, Manprit Singh wrote: Do you ever take a blind bit of notice of what gets said on this list? You've been asked repeatedly *NOT* to top post yet you still do it. Worse yet your code still doesn't work correctly as it still finds "am" in "spam". > Dear sir , > Have tried one more and found it quite good : > > st1 = "I am a boy, i am an engineer, i am a genius" > w ="am" > > ge = (i for i in range(st1.rfind(w) + 1) if st1.startswith(w, i)) > print(*ge) > > Regards > Manprit singh > -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at yahoo.co.uk Fri Oct 30 20:05:55 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 31 Oct 2020 00:05:55 +0000 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: On 30/10/2020 23:35, Manprit Singh wrote: > Dear Sir, > > Any pacific reason for writing n+1 inside n = st1.find('am', n+1), or you > have just written it because the first position of "am" is not index 0, it > is after index 0 . There is actually a bug because my code would miss the first 'am' if it started at 0. But the n+1 is because find returns the index of there 'a' If we don't increment it on the next find() call it will return the same value each time. >>>>> st1 = "I am a boy, i am an engineer, i am a genius" >>>>> n = -1 found = False >>>>> while not found >> n = st1.find('am', n+1) >> if n == -1: found = True else: print(n) Should fix the bug. However, Mark has raised another issue, which is that the code is only searching for 'am' not ensuring that 'am' is a word. For that things get more complex and I'd probably resort to a regex... And in that case we can use findall() to get all the occurrences in a single 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 manpritsinghece at gmail.com Fri Oct 30 20:44:52 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 31 Oct 2020 06:14:52 +0530 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: Dear sir , Can't we write it in this way : st1 = "I am a boy, i am an engineer, i am a genius" n = 0 while True: n = st1.find('am', n) if n != -1: print(n) elif n == -1: break n = n + 1 Regards Manprit Singh On Sat, Oct 31, 2020 at 5:41 AM Alan Gauld via Tutor wrote: > On 30/10/2020 23:35, Manprit Singh wrote: > > Dear Sir, > > > > Any pacific reason for writing n+1 inside n = st1.find('am', n+1), or > you > > have just written it because the first position of "am" is not index 0, > it > > is after index 0 . > > There is actually a bug because my code would miss the first > 'am' if it started at 0. > > But the n+1 is because find returns the index of there 'a' > If we don't increment it on the next find() call it will return > the same value each time. > > >>>>> st1 = "I am a boy, i am an engineer, i am a genius" > > >>>>> n = -1 > found = False > >>>>> while not found > >> n = st1.find('am', n+1) > >> if n == -1: found = True > else: print(n) > > Should fix the bug. > > However, Mark has raised another issue, which is that the code > is only searching for 'am' not ensuring that 'am' is a word. > For that things get more complex and I'd probably resort > to a regex... And in that case we can use findall() to > get all the occurrences in a single 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 > > > _______________________________________________ > 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 Fri Oct 30 21:08:07 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 31 Oct 2020 01:08:07 +0000 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: On 31/10/2020 00:44, Manprit Singh wrote: > Dear sir , > > Can't we write it in this way : > st1 = "I am a boy, i am an engineer, i am a genius" > n = 0 > while True: > n = st1.find('am', n) > if n != -1: > print(n) > elif n == -1: > break > n = n + 1 Sure you can that's just inverting the logic. And since it saves a variable its probably preferable. In fact, you don't need the elif, a simple else will suffice. And of course the last line would more idiomatically be n += 1 But it still doesn't address Mark's point about not identifying 'am' as a separate word... Which was explicitly stated as a requirement in your original post: "...to find the index of every occurrence *word* "am" ..." -- 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 manpritsinghece at gmail.com Fri Oct 30 21:38:04 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 31 Oct 2020 07:08:04 +0530 Subject: [Tutor] Regular User defined functions Vs Generator functions Message-ID: Dear sir , I have a question , why not to prefer generator functions instead of regular user defined functions, where i have problem like as that given below : I have to write a function that can return index of each and every occurrence of substring w in string st1, st1 & w given below: st1 = "I am a boy, i am an engineer, i am a genius" w = "am" If i have to write a function to solve this problem, i feel generator function is more good( as compared to regular user defined function), that i have written below : def ind_word(st, w): n = 0 while True: n = st.find(w, n) if n != -1: yield n else: break n += 1 st1 = "I am a boy, i am an engineer, i am a genius" w = "am" print(*ind_word(st1, w)) will give result 2 14 32 Need your suggestions. Regards Manprit Singh From manpritsinghece at gmail.com Fri Oct 30 21:48:13 2020 From: manpritsinghece at gmail.com (Manprit Singh) Date: Sat, 31 Oct 2020 07:18:13 +0530 Subject: [Tutor] program to find index of every occurrence of a particular word in a string In-Reply-To: References: Message-ID: Dear Sir, My actual problem was to find the index of each and every occurrence of substring "am" in the string st1 that is solved. So now what Mark has pointed out and you have suggested to involve regular expressions, this has become a good exercise for me. Let me come up with an imperfect solution, that I will share with you in the next mail . Thanking Mark for this opportunity. Regards Manprit Singh On Sat, Oct 31, 2020 at 6:38 AM Alan Gauld via Tutor wrote: > On 31/10/2020 00:44, Manprit Singh wrote: > > Dear sir , > > > > Can't we write it in this way : > > st1 = "I am a boy, i am an engineer, i am a genius" > > n = 0 > > while True: > > n = st1.find('am', n) > > if n != -1: > > print(n) > > elif n == -1: > > break > > n = n + 1 > > Sure you can that's just inverting the logic. > And since it saves a variable its probably preferable. > > In fact, you don't need the elif, a simple else will suffice. > And of course the last line would more idiomatically be > > n += 1 > > But it still doesn't address Mark's point about not > identifying 'am' as a separate word... Which was > explicitly stated as a requirement in your original > post: > > "...to find the index of every occurrence *word* "am" ..." > > -- > 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 alan.gauld at yahoo.co.uk Sat Oct 31 04:50:52 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 31 Oct 2020 08:50:52 +0000 Subject: [Tutor] Regular User defined functions Vs Generator functions In-Reply-To: References: Message-ID: On 31/10/2020 01:38, Manprit Singh wrote: > I have a question , why not to prefer generator functions instead of > regular user defined functions, where i have problem like as that given > below : Any function that returns a potentially long sequence of values is probably better written as a generator. It's just that from habit most folks use return. It's easy enough to convert a regular function to a generator if it turns out that performance needs it. But there's absolutely nothing wrong with doing it from the beginning. There may be a slight performance overhead in using a generator where there are very low numbers of return values, but it's minimal and as in any performance assessment you'd need to measure it to determine whether the list or generator approach worked best. > def ind_word(st, w): > n = 0 > while True: > n = st.find(w, n) > if n != -1: > yield n > else: > break > n += 1 -- 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 babugaur123 at gmail.com Sat Oct 31 10:50:25 2020 From: babugaur123 at gmail.com (VISHAL GAUR) Date: Sat, 31 Oct 2020 20:20:25 +0530 Subject: [Tutor] help Message-ID: Please tell me some suggestions for this problem, I have tried this code but it is not giving me the correct output..... *Problem*: Use Python to calculate how many different passwords can be formed with 6 lower case English letters. For a 1 letter password, there would be 26 possibilities. For a 2 letter password, each letter is independent of the other, so there would be 26 times 26 possibilities. Using this information, print the amount of possible passwords that can be formed with 6 letters. pass_proability = 1 for i in range(1,7): pass_proability = pass_proability * i * 26 # print(pass_proability) print(pass_proability) *Please consider the environment before printing this e-mail. Paper is made out of trees. Conserve, Reduce, Re-use, Renew and Recycle !* *Thank you* *?Good decisions come from experience, and experience comes from bad decisions.?* From alan.gauld at yahoo.co.uk Sat Oct 31 12:19:18 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 31 Oct 2020 16:19:18 +0000 Subject: [Tutor] help In-Reply-To: References: Message-ID: On 31/10/2020 14:50, VISHAL GAUR wrote: > Please tell me some suggestions for this problem, I have tried this code > but it is not giving me the correct output... It might help if you told us what output it was giving and why you believe it is wrong. > *Problem*: Use Python to calculate how many different passwords can be > formed with 6 lower case English letters. For a 1 letter password, there > would be 26 possibilities. For a 2 letter password, each letter is > independent of the other, so there would be 26 times 26 possibilities. So lets tabulate that: 1 place -> 26 2 places -> 26*26 3 places -> 26*26*26 4 places -> 26*26*26*26 etc... > pass_probability = 1 > for i in range(1,7): > pass_probability = pass_probability * i * 26 What does your for loop do? It sets i to 1,2,3,4,5,6. So the calculations go: pass_probability = 1 i = 1 pass_probability = 1 * 1 * 26 -> 26 # ok so far i = 2 pass_probability = 26 * 2 * 26 -> 1352 # broken already! i = 3 pass_probability = 1352 * 3 * 26 ... Can you see where its going wrong? There are at least 2 ways to fix this. Hint: One of them does not even require a for loop! -- 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 Sat Oct 31 13:54:04 2020 From: mats at wichmann.us (Mats Wichmann) Date: Sat, 31 Oct 2020 11:54:04 -0600 Subject: [Tutor] Regular User defined functions Vs Generator functions In-Reply-To: References: Message-ID: On 10/31/20 2:50 AM, Alan Gauld via Tutor wrote: > On 31/10/2020 01:38, Manprit Singh wrote: > >> I have a question , why not to prefer generator functions instead of >> regular user defined functions, where i have problem like as that given >> below : > > Any function that returns a potentially long sequence of values > is probably better written as a generator. It's just that from habit > most folks use return. It's easy enough to convert a regular > function to a generator if it turns out that performance needs > it. But there's absolutely nothing wrong with doing it from > the beginning. > > There may be a slight performance overhead in using a generator > where there are very low numbers of return values, but it's > minimal and as in any performance assessment you'd need to > measure it to determine whether the list or generator > approach worked best. It may be a false economy to even worry about it, but my tendency is if the caller is going to immediately consume the entire result of the function, and there's potentially a large number of values, then there's not really any point in having it be a generator, you don't realize any of the savings and you pay the cost of function setup/call for each value. That's really kind of stupid on the surface, you shouldn't decide on the implementation of a function based on usage pattern of one frequent caller, since that's breaking the separation of purpose that the function should give you, but the thing I'm spending most of my time on does have some performance issues, so.... From alan.gauld at yahoo.co.uk Sat Oct 31 19:41:35 2020 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 31 Oct 2020 23:41:35 +0000 Subject: [Tutor] Regular User defined functions Vs Generator functions In-Reply-To: References: Message-ID: On 31/10/2020 17:54, Mats Wichmann wrote: > the caller is going to immediately consume the entire result of the > function, and there's potentially a large number of values, then there's > not really any point in having it be a generator, Yes but its hard to predict those ud cases. On the other side if the client may not consume all the values and break on finding the Nth item or one that matches some criteria then a generator makes perfect sense for large data sets. There is no single, simple answer. You need to understand the requirements and for 90% of the time it won't make much practical 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 cs at cskk.id.au Sat Oct 31 21:00:08 2020 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 1 Nov 2020 12:00:08 +1100 Subject: [Tutor] Regular User defined functions Vs Generator functions In-Reply-To: References: Message-ID: <20201101010008.GA84245@cskk.homeip.net> On 31Oct2020 23:41, Alan Gauld wrote: >On 31/10/2020 17:54, Mats Wichmann wrote: >> the caller is going to immediately consume the entire result of the >> function, and there's potentially a large number of values, then there's >> not really any point in having it be a generator, > >Yes but its hard to predict those ud cases. > >On the other side if the client may not consume all the >values and break on finding the Nth item or one that matches >some criteria then a generator makes perfect sense for >large data sets. > >There is no single, simple answer. You need to understand >the requirements and for 90% of the time it won't make much >practical difference! Yes, but there's a big caveat. Make sure the docstring says "returns an iterable". Every so often I come down on the generator side of this choice, but call it expecting to get a sequence or other collection such as a set. But what I store is an unexecuted generator instance. Badness ensues later in the programme. Cheers, Cameron Simpson