From alan.gauld at yahoo.co.uk Thu Apr 1 16:14:58 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 1 Apr 2021 21:14:58 +0100 Subject: [Tutor] python In-Reply-To: <910A7BFA-3E60-4199-BD98-AE872534BC0D@hxcore.ol> References: <910A7BFA-3E60-4199-BD98-AE872534BC0D@hxcore.ol> Message-ID: On 01/04/2021 01:36, Shaid wrote: > Write a function that take s a list of numbers as input and returns the > sum of the numbers in the list . What do you need help with? Do you know how to write a function? Do you know how to specify a list as an input parameter? Do you know how to sum the numbers in a list? Do you know how to return a value from a function? Do you know how to test a function to prove it works? -- 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 lorainelindsay21 at gmail.com Thu Apr 1 15:22:03 2021 From: lorainelindsay21 at gmail.com (Loraine Lindsay) Date: Thu, 1 Apr 2021 15:22:03 -0400 Subject: [Tutor] python In-Reply-To: <12e2c36d-072e-ea1f-de4a-26606b1da80a@wichmann.us> References: <12e2c36d-072e-ea1f-de4a-26606b1da80a@wichmann.us> Message-ID: <244DD20C-2656-4B85-AB6F-C835C46A4C26@gmail.com> Loraine Lindsay > On Mar 31, 2021, at 8:55 PM, Mats Wichmann wrote: > > ?On 3/31/21 6:36 PM, Shaid wrote: >> Write a function that take s a list of numbers as input and returns the >> sum of the numbers in the list . > > And are you going to try? Yes > > From leamhall at gmail.com Fri Apr 2 11:35:17 2021 From: leamhall at gmail.com (Leam Hall) Date: Fri, 2 Apr 2021 11:35:17 -0400 Subject: [Tutor] More About Minimum Skills Message-ID: Sorry I missed the "Minimum Skills" thread before. It's one of my favorite topics. I am not John Sonmez, nor do I get any revenue from recommending his stuff. If you check out "simpleprogrammer.com", he has a couple of free courses. I think one gives you access to a very useful spreadsheet of minimum technical skills. It's been a while. However, John's real recommendation is to learn the basics and then start reading good code. Alan has a Projects book out, and can probably name several other open source projects that exemplify Pythonic coding. Read that code. Read PEP 8. Most importantly, code. Find stuff you want to do and code. It'll be lousy code, but it will be *your* lousy code. Having code helps your brain learn, and having code lets you get feedback from really skilled people. Jump on codewars.com and start coding there, too. Leam -- Site Reliability Engineer (reuel.net/resume) Chronicler: The Domici War (domiciwar.net) General Ne'er-do-well (github.com/LeamHall) From cjbenz310 at gmail.com Fri Apr 2 23:11:55 2021 From: cjbenz310 at gmail.com (Caleb Benz) Date: Fri, 2 Apr 2021 23:11:55 -0400 Subject: [Tutor] Help With A Program Message-ID: <086E1C67-C683-401E-B58C-C4C838156F89@gmail.com> Hello there! I am currently writing a program that takes an integer, n, from a user, and outputs all of the prime numbers up to and including n. I have written the following code, and am not sure where I am going wrong. For some reason, my program isn?t responding to the fact that x is going up 1 each time, and therefore isn?t working. Here is the code: def generatePrimes(): n=int(input('Enter a number:')) integer_list=list(range(2,(n+1))) result=[2,3] x=1 for i in range(2,(n+1)): x=x+1 if i==(((6*x)-1) or ((6*x)+1)): result.append(i) print(result) generatePrimes() Please let me know where I?m going wrong, and how I can fix this! Thanks, Caleb From alan.gauld at yahoo.co.uk Sat Apr 3 03:54:34 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 3 Apr 2021 08:54:34 +0100 Subject: [Tutor] Help With A Program In-Reply-To: <086E1C67-C683-401E-B58C-C4C838156F89@gmail.com> References: <086E1C67-C683-401E-B58C-C4C838156F89@gmail.com> Message-ID: On 03/04/2021 04:11, Caleb Benz wrote: > I am currently writing a program that takes an integer, n, > from a user, and outputs all of the prime numbers up to > and including n. When you are trying to debug a program its often a good idea to walk through the program writing down the variable values as you go. Lets try that for your program assuming a first input value of 1. We'll look at n,x and result... > def generatePrimes(): > n=int(input('Enter a number:')) > integer_list=list(range(2,(n+1))) > result=[2,3] > x=1 At this [oint n = 1, x = 1 result - [2,3] > for i in range(2,(n+1> x=x+1 No n = 1, x = 2, result = [2,3] and i = 2 > if i==(((6*x)-1) or ((6*x)+1)): This line doesn't do what you think it does, lets plug in our values... if 2 == (11 or 13): 'or' is a boolean operator so always returns True or False. But things are really a lot more complicated than that unfortunately. Python considers anything non-zero to be True. And the or operator is lazy so it returns the first value that it finds True (there could be many values) and does not bother calculating the rest. So in your case it calculates 11, sees it is True and returns that value. The second part is only ever calculated if the first part is zero. Which will never happen in your code. So really we have if 2 == 11 Which is false > result.append(i) > print(result) So it prints [2,3] Which is wrong because n was 1... Let's try again with a value of n == 5 def generatePrimes(): n=int(input('Enter a number:')) integer_list=list(range(2,(n+1))) result=[2,3] x=1 n = 5, x = 1, result = [2,3] for i in range(2,(n+1)): x=x+1 if i==(((6*x)-1) or ((6*x)+1)): i = 2 n = 5, x = 2, result = [2,3] if 2 == 11 is False i = 3 n = 5, x = 3, result = [2,3] if 3 == 17 is False i=4 n = 5, x = 4, result = [2,3] if 2 == 23 is False i = 5 n = 5, x = 5, result = [2,3] if 2 == 29 is False That's the end of the for loop result.append(i) print(result) result = [2,3] I'm not sure how you think that function is working out primes. Try working through it line by line with other values. It isn't working because your algorithm is broke. You don't use integer_list anywhere. x is the same value as i. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Sun Apr 4 20:29:54 2021 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 4 Apr 2021 19:29:54 -0500 Subject: [Tutor] OT (but relevant): Contrasting articles on asking good questions. Message-ID: I think most people have at least scanned this article: http://www.catb.org/~esr/faqs/smart-questions.html by Eric Raymond. But I just read the following article: https://jvns.ca/blog/good-questions/ by Julia Evans, and, I must say, I found it more helpful in its tone and content. Perhaps a data point for why increasing diversity amongst programmers is important? Just stirring the pot... ~(:>)) -- Wishing you only the best, boB Stepp From mats at wichmann.us Sun Apr 4 21:24:23 2021 From: mats at wichmann.us (Mats Wichmann) Date: Sun, 04 Apr 2021 19:24:23 -0600 Subject: [Tutor] OT (but relevant): Contrasting articles on asking good questions. In-Reply-To: References: Message-ID: <3FC4A407-0FE8-4314-8F3A-FEF6380D4FBF@wichmann.us> On April 4, 2021 6:29:54 PM MDT, boB Stepp wrote: >I think most people have at least scanned this article: > >http://www.catb.org/~esr/faqs/smart-questions.html > >by Eric Raymond. > >But I just read the following article: > >https://jvns.ca/blog/good-questions/ > >by Julia Evans, and, I must say, I found it more helpful in its tone >and >content. Perhaps a data point for why increasing diversity amongst >programmers is important? > >Just stirring the pot... ~(:>)) naah, there's not really much difference here. the goal isn't necessarily to ask questions that are easy to answer, what if your question exposes something complicated? that's absolutely fine, the goal is to not ask questions that can't be answered at all because so much context is missing. "I'm unable to Foo. Tell me how to fix it." -- Sent from a mobile device with K-9 Mail. Please excuse my brevity. From alexkleider at gmail.com Sun Apr 4 22:18:03 2021 From: alexkleider at gmail.com (Alex Kleider) Date: Sun, 4 Apr 2021 19:18:03 -0700 Subject: [Tutor] OT (but relevant): Contrasting articles on asking good questions. In-Reply-To: References: Message-ID: it was co-authored (with Rick Moen) (FYI) cheers, a On Sun, Apr 4, 2021 at 5:31 PM boB Stepp wrote: > I think most people have at least scanned this article: > > http://www.catb.org/~esr/faqs/smart-questions.html > > by Eric Raymond. > > But I just read the following article: > > https://jvns.ca/blog/good-questions/ > > by Julia Evans, and, I must say, I found it more helpful in its tone and > content. Perhaps a data point for why increasing diversity amongst > programmers is important? > > Just stirring the pot... ~(:>)) > > -- > Wishing you only the best, > > boB Stepp > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From joao.oliveira at ufob.edu.br Thu Apr 8 13:43:30 2021 From: joao.oliveira at ufob.edu.br (Joao Carlos Silva de Oliveira Matos) Date: Thu, 8 Apr 2021 14:43:30 -0300 Subject: [Tutor] Simple Regex Message-ID: Hello everyone, I have to parse a regex for the first time. I have this path: *C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv.* I want to retrieve the name of the folder between "Downloads\" and "\filename". How do I do this? -- Jo?o Carlos Silva de Oliveira Matos Bolsista de Inova??o e Tecnologia PROFNIT - Centro das Humanidades - UFOB Mat. 2020100150 From PyTutor at DancesWithMice.info Thu Apr 8 16:25:44 2021 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 9 Apr 2021 08:25:44 +1200 Subject: [Tutor] Simple Regex In-Reply-To: References: Message-ID: <231b25ce-abdd-a6fe-f440-4316f25d3696@DancesWithMice.info> On 09/04/2021 05.43, Joao Carlos Silva de Oliveira Matos via Tutor wrote: > Hello everyone, > > I have to parse a regex for the first time. I have this path: > *C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv.* > > I want to retrieve the name of the folder between "Downloads\" and > "\filename". > > How do I do this? Does pathlib, from the Python Standard Library help? https://docs.python.org/3/library/pathlib.html?highlight=pathlib#module-pathlib -- Regards, =dn From alan.gauld at yahoo.co.uk Thu Apr 8 16:26:05 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 8 Apr 2021 21:26:05 +0100 Subject: [Tutor] Simple Regex In-Reply-To: References: Message-ID: On 08/04/2021 18:43, Joao Carlos Silva de Oliveira Matos via Tutor wrote: > I have to parse a regex for the first time. I have this path: > *C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv.* No you don;t. You should hardly ever need regex to work with paths. Use the os.path module instead. > I want to retrieve the name of the folder between "Downloads\" and > "\filename". os.path.dirname() removes the filename os.path.split() returns the first and last parts of a path So import os.path p = r"C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv" dir = os.split(os.path.dirname(p))[1] Should get what you want. If the number of folders is always the same you could even use a simple string.split: dir = p.split('\')[4] But os.path takes care of path separators on different platforms so is the preferred solution for portability. -- 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 Apr 8 16:32:55 2021 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 9 Apr 2021 08:32:55 +1200 Subject: [Tutor] Simple Regex In-Reply-To: <231b25ce-abdd-a6fe-f440-4316f25d3696@DancesWithMice.info> References: <231b25ce-abdd-a6fe-f440-4316f25d3696@DancesWithMice.info> Message-ID: On 09/04/2021 08.25, dn via Tutor wrote: > On 09/04/2021 05.43, Joao Carlos Silva de Oliveira Matos via Tutor wrote: >> Hello everyone, >> >> I have to parse a regex for the first time. I have this path: >> *C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv.* >> >> I want to retrieve the name of the folder between "Downloads\" and >> "\filename". >> >> How do I do this? > > > Does pathlib, from the Python Standard Library help? > https://docs.python.org/3/library/pathlib.html?highlight=pathlib#module-pathlib In the ?good, old days, we used combinations of the os and sys libraries. So, if you are reading code, you may see constructs of such. - these days the preference is for the above. https://docs.python.org/3/library/os.html https://docs.python.org/3/library/os.path.html -- Regards, =dn From PyTutor at DancesWithMice.info Thu Apr 8 16:40:09 2021 From: PyTutor at DancesWithMice.info (dn) Date: Fri, 9 Apr 2021 08:40:09 +1200 Subject: [Tutor] Simple Regex In-Reply-To: References: Message-ID: On 09/04/2021 08.26, Alan Gauld via Tutor wrote: > On 08/04/2021 18:43, Joao Carlos Silva de Oliveira Matos via Tutor wrote: > >> I have to parse a regex for the first time. I have this path: >> *C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv.* > > No you don;t. You should hardly ever need regex to work with paths. > Use the os.path module instead. > >> I want to retrieve the name of the folder between "Downloads\" and >> "\filename". > > os.path.dirname() removes the filename > os.path.split() returns the first and last parts of a path > > > So > > import os.path > > p = r"C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv" > > dir = os.split(os.path.dirname(p))[1] > > Should get what you want. > > If the number of folders is always the same you could even > use a simple string.split: > > dir = p.split('\')[4] > > But os.path takes care of path separators on different platforms > so is the preferred solution for portability. Per earlier comments, this is where previous-experience takes me too. Alternatively (following earlier web.ref), could use the 'common factor' approach to remove the "C:\Users\user\Downloads\" constant-component from view, and os.path.split() from there. -- Regards, =dn From mats at wichmann.us Thu Apr 8 17:23:47 2021 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 8 Apr 2021 15:23:47 -0600 Subject: [Tutor] Simple Regex In-Reply-To: References: Message-ID: <854a1406-40fa-4f8c-efbb-7e6308209aa7@wichmann.us> On 4/8/21 2:40 PM, dn via Tutor wrote: > On 09/04/2021 08.26, Alan Gauld via Tutor wrote: >> On 08/04/2021 18:43, Joao Carlos Silva de Oliveira Matos via Tutor wrote: >> >>> I have to parse a regex for the first time. I have this path: >>> *C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv.* >> >> No you don;t. You should hardly ever need regex to work with paths. >> Use the os.path module instead. >> >>> I want to retrieve the name of the folder between "Downloads\" and >>> "\filename". >> >> os.path.dirname() removes the filename >> os.path.split() returns the first and last parts of a path Maybe you can work with this: >>> from pathlib import PureWindowsPath >>> p = PureWindowsPath(r'C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv') >>> p.parts ('C:\\', 'Users', 'user', 'Downloads', '4324234534254325', '4324234534254325_213.csv') >>> p.parent PureWindowsPath('C:/Users/user/Downloads/4324234534254325') >>> p.name '4324234534254325_213.csv' >>> From alan.gauld at yahoo.co.uk Thu Apr 8 18:56:18 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 8 Apr 2021 23:56:18 +0100 Subject: [Tutor] Simple Regex In-Reply-To: <854a1406-40fa-4f8c-efbb-7e6308209aa7@wichmann.us> References: <854a1406-40fa-4f8c-efbb-7e6308209aa7@wichmann.us> Message-ID: On 08/04/2021 22:23, Mats Wichmann wrote: > Maybe you can work with this: > > > >>> from pathlib import PureWindowsPath > >>> p = > PureWindowsPath(r'C:\Users\user\Downloads\4324234534254325\4324234534254325_213.csv') > >>> p.parts > ('C:\\', 'Users', 'user', 'Downloads', '4324234534254325', > '4324234534254325_213.csv') > >>> p.parent > PureWindowsPath('C:/Users/user/Downloads/4324234534254325') > >>> p.name > '4324234534254325_213.csv' > >>> Looks like I need to spend some time with pathlib. The last time I looked at it (Python 3.3?) it was only marked as a candidate for the standard lib and subject to change, so I looked no further. I assume by now its a fixture? -- 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 Thu Apr 8 19:17:26 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Fri, 9 Apr 2021 09:17:26 +1000 Subject: [Tutor] Simple Regex In-Reply-To: References: Message-ID: On 08Apr2021 23:56, Alan Gauld wrote: >Looks like I need to spend some time with pathlib. >The last time I looked at it (Python 3.3?) it was only marked >as a candidate for the standard lib and subject to change, >so I looked no further. I assume by now its a fixture? Yes indeed. It is quite nice. Amongst other things, we're using it to parse Windows paths on a UNIX host, works like a charm. Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Wed Apr 14 13:18:20 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 14 Apr 2021 18:18:20 +0100 Subject: [Tutor] Ann: New Python curses book. In-Reply-To: <877432ad-057a-5d3d-1000-13e6b6fb4154@yahoo.co.uk> References: <877432ad-057a-5d3d-1000-13e6b6fb4154@yahoo.co.uk> Message-ID: On 30/03/2021 12:07, Alan Gauld via Tutor wrote: > I've just published, in Kindle and paperback formats, > my book on "Programming curses with Python". > > https://www.amazon.co.uk/dp/B091B85B77/ I've just noticed that the kindle version has several indentation problems in the code listings. I can't do anything to fix it because it is all perfectly aligned in the Word file I submit, it's caused somewhere in the Amazon conversion process. (In fact it's possibly its OK on some Kindle devices/apps, just not the web reader I was using!) Hopefully the expected readership will be smart enough to: a) figure it out from the context and b) download the sample code which is correctly formatted. The paper version should be fine (apart from one error on p44 which has now been fixed! - Thanks to Avi Gross for spotting that one). Apologies to anyone who got stung by this. -- 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 derekrneilson at gmail.com Thu Apr 15 14:49:11 2021 From: derekrneilson at gmail.com (derek) Date: Thu, 15 Apr 2021 12:49:11 -0600 Subject: [Tutor] FW: NameError: name 'pics' is not defined Message-ID: Sent from [1]Mail for Windows 10 From: [2]derek Sent: Thursday, April 15, 2021 12:47 PM To: [3]tutor at python.org Subject: NameError: name 'pics' is not defined import numpy as np import sys import face_recognition import cv2 import os import tkinter as tk from PIL import ImageTk, Image from tkinter import * from tkinter import filedialog global pics # definitions def openFile(): pics = filedialog.askopenfilename() print(pics) # things to do # find file in pictures # loop over pictures in file name # data base SQL lite (program_name) = "Image Recognition Machine Learning Algorithm" (defwinsize) = "450x450" TitleOfOFD = "select pictures for processing" win = tk.Tk() button = Button(text=TitleOfOFD, command=openFile) canvas = Canvas(win, width=300, height=300) canvas.create_image(200, 200, anchor=NW, image=pics) button.pack() canvas.pack() win.title(program_name) win.geometry(defwinsize) win.mainloop() [4][IMG] Virus-free. [5]www.avg.com References Visible links 1. https://go.microsoft.com/fwlink/?LinkId=550986 2. mailto:derekrneilson at gmail.com 3. mailto:tutor at python.org 4. http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient 5. http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient From alan.gauld at yahoo.co.uk Thu Apr 15 18:56:17 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 15 Apr 2021 23:56:17 +0100 Subject: [Tutor] FW: NameError: name 'pics' is not defined In-Reply-To: References: Message-ID: On 15/04/2021 19:49, derek wrote: > from tkinter import filedialog > > global pics This does not do what you think it does. In fact at this point in the code I don't think it does anything! Certainly nothing useful. global is used inside a function to resolve name conflicts. To tell Python that a given name should refer to the global(ie module) scope and not be created as a local variable inside the function. It does not create the variable. > # definitions > def openFile(): > pics = filedialog.askopenfilename() And this pics is local to the function because you did not declare it global inside the function. You need to move the global line inside this function. > win = tk.Tk() > button = Button(text=TitleOfOFD, command=openFile) You need to tell the Button who its parent is otherwise it will be an orphan control. ie you need win as the first argument. > canvas = Canvas(win, width=300, height=300) > canvas.create_image(200, 200, anchor=NW, image=pics) And here you refer to a non existent pics. So presumably, this is where the error comes from. When posting always include the full error trace, it contains a lot of useful details -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Fri Apr 16 00:11:13 2021 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 15 Apr 2021 23:11:13 -0500 Subject: [Tutor] "Learn by reading code: Python standard library design decisions explained (for advanced beginners)" Message-ID: The link: https://death.andgravity.com/stdlib The article gives a curated selection of a few standard library modules that the author believes will be beneficial for the "advanced beginner" to study. In the section "How to read these" the author recommends this order of study: * Get familiar with them as a user: read the documentation, maybe play with the examples a bit. * Read the corresponding Python Enhancement Proposal (PEP). The interesting sections usually are the Abstract, Rationale, Design Decisions, Discussion, and Rejected Ideas. * Read the code; it's linked at the top of each documentation page. The libraries he recommends: dataclasses, pathlib (and compare with os.path), statistics, and, as a bonus graphlib as its discussion by the developers is especially educational. Thought I would pass this along as it might encourage fellow learners to delve into some of the Python standard library source code. Now to find some time... -- Wishing you only the best, boB Stepp From phillor9 at gmail.com Sun Apr 18 04:13:47 2021 From: phillor9 at gmail.com (Phil) Date: Sun, 18 Apr 2021 18:13:47 +1000 Subject: [Tutor] Converting bytes to a string Message-ID: I'm reading serial data from a Pi Pico and I notice that there is what looks like a small 'd' on the end of the string after decoding the byte. The data is received as b'26.3\r\n' and to convert it to a string I do the following: s = data.decode() s.strip('\r\n')? ??? ??? ??? # at this point there is a mystery character on the end of the string print(s.strip())?????????? # this strips off the small 'd' I'm wondering what the small, unprintable, 'd' is? -- Regards, Phil From cs at cskk.id.au Sun Apr 18 07:19:42 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Sun, 18 Apr 2021 21:19:42 +1000 Subject: [Tutor] Converting bytes to a string In-Reply-To: References: Message-ID: On 18Apr2021 18:13, Phil wrote: >I'm reading serial data from a Pi Pico and I notice that there is what >looks like a small 'd' on the end of the string after decoding the >byte. > >The data is received as b'26.3\r\n' and to convert it to a string I do >the following: > >s = data.decode() >s.strip('\r\n')? ??? ??? ??? # at this point there is a mystery >character on the end of the string How do you know this? What does: print(repr(s)) show? If you're doing this interactively, maybe there's some visual indicator that there's no end of line? Also note that the line above does not modify "s". Do you mean: s = s.strip('\r\n') Also be aware that this does not remove the string '\r\n' from the end of the line, it removes _all_ occurrences of any '\r' or '\n' characters from the start or end of the string. If you have a very recent Python, try s.removesuffix('\r\n'), which does remove a fixed string. >print(s.strip())?????????? # this strips off the small 'd' > >I'm wondering what the small, unprintable, 'd' is? Try printing repr(s) or repr(s.strip()). repr() is your friend for seeing exactly what value you have. I'm _guessing_ you're seeing some visual indicator of something, but I don't know what environment you're testing in. Cheers, Cameron Simpson From phillor9 at gmail.com Sun Apr 18 20:18:21 2021 From: phillor9 at gmail.com (Phil) Date: Mon, 19 Apr 2021 10:18:21 +1000 Subject: [Tutor] Converting bytes to a string In-Reply-To: References: Message-ID: <66ee47f9-1bb5-3974-cdb7-fd85c415c9a2@gmail.com> On 18/4/21 9:19 pm, Cameron Simpson wrote: Thanks Cameron for your detailed reply, I wasn't aware of either removesuffix() and repr(), I'll investigate further. The mysterious character isn't causing a problem, at the moment at least, I was just curious. -- Regards, Phil From cs at cskk.id.au Sun Apr 18 20:47:33 2021 From: cs at cskk.id.au (Cameron Simpson) Date: Mon, 19 Apr 2021 10:47:33 +1000 Subject: [Tutor] Converting bytes to a string In-Reply-To: <66ee47f9-1bb5-3974-cdb7-fd85c415c9a2@gmail.com> References: <66ee47f9-1bb5-3974-cdb7-fd85c415c9a2@gmail.com> Message-ID: On 19Apr2021 10:18, Phil wrote: >On 18/4/21 9:19 pm, Cameron Simpson wrote: >I wasn't aware of either removesuffix() and repr(), I'll investigate >further. > >The mysterious character isn't causing a problem, at the moment at >least, I was just curious. There shouldn't be an extraneous character (unless there's something in the string you've not shown: repr will help there). Cheers, Cameron Simpson From phillor9 at gmail.com Mon Apr 19 00:48:03 2021 From: phillor9 at gmail.com (Phil) Date: Mon, 19 Apr 2021 14:48:03 +1000 Subject: [Tutor] Converting bytes to a string In-Reply-To: References: <66ee47f9-1bb5-3974-cdb7-fd85c415c9a2@gmail.com> Message-ID: On 19/4/21 10:47 am, Cameron Simpson wrote: > > There shouldn't be an extraneous character (unless there's something in > the string you've not shown: repr will help there). Thanks again Cameron, I'd made a slight error, the mysterious character is on the end of the byte and doesn't appear once the byte is converted to a string. I've had a play with repr() and it's similar to, but not the same as, type() which I've used often. The removesuffix() function is included in Python 3.9 and is available from dead snake, if anyone wants to know. -- Regards, Phil From manpritsinghece at gmail.com Tue Apr 20 12:48:11 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Tue, 20 Apr 2021 22:18:11 +0530 Subject: [Tutor] removing consecutive duplicates from list Message-ID: Dear sir , Consider a list given below: lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] i need to remove consecutive duplicates from list lst: the answer must be : [2, 3, 4, 5, 3, 7, 9, 4] The code that i have written to solve it, is written below: lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] ls = lst[1:]+[object()] [x for x, y in zip(lst, ls) if x != y] The list comprehension gives the desired result. just need to know if this program can be done in a more readable and less complex way. From alan.gauld at yahoo.co.uk Tue Apr 20 13:11:53 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 20 Apr 2021 18:11:53 +0100 Subject: [Tutor] removing consecutive duplicates from list In-Reply-To: References: Message-ID: On 20/04/2021 17:48, Manprit Singh wrote: > The code that i have written to solve it, is written below: > lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] > ls = lst[1:]+[object()] > [x for x, y in zip(lst, ls) if x != y] > > The list comprehension gives the desired result. just need to know if this > program can be done in a more readable and less complex way. I'd suggest the more explicit form: >>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >>> result = [] >>> for idx,itm in enumerate(lst): if idx <= len(lst)-2 and itm == lst[idx+1]: continue result.append(itm) You could write that as a list comprehension but I think it loses readability. >>> result2 = [itm for idx,itm in enumerate(lst) if idx <= len(lst)-2 and itm != lst[idx+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 __peter__ at web.de Tue Apr 20 13:27:51 2021 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Apr 2021 19:27:51 +0200 Subject: [Tutor] removing consecutive duplicates from list In-Reply-To: References: Message-ID: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> On 20/04/2021 18:48, Manprit Singh wrote: > Consider a list given below: > lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] > i need to remove consecutive duplicates from list lst: > the answer must be : > > [2, 3, 4, 5, 3, 7, 9, 4] > > The code that i have written to solve it, is written below: > lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] > ls = lst[1:]+[object()] > [x for x, y in zip(lst, ls) if x != y] > > The list comprehension gives the desired result. just need to know if this > > program can be done in a more readable and less complex way. The itertools module has many tools that you can use to deal with problems like the above: The obvious one: >>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >>> wanted = [2, 3, 4, 5, 3, 7, 9, 4] >>> from itertools import zip_longest >>> wanted == [x for x, y in zip_longest(lst, lst[1:]) if x != y] True You may want to use islice instead of an actual slice. A variant that will continue to work if you replace the list with an iterator (e. g. a file): >>> from itertools import tee >>> a, b = tee(lst) >>> next(b) 2 >>> [x for x, y in zip_longest(a, b) if x != y] [2, 3, 4, 5, 3, 7, 9, 4] >>> wanted == _ True A conceptually different one, treating consecutive dupes as groups: >>> from itertools import groupby >>> wanted == [k for k, g in groupby(lst)] True Pick your favourite ;) From __peter__ at web.de Tue Apr 20 13:27:51 2021 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Apr 2021 19:27:51 +0200 Subject: [Tutor] removing consecutive duplicates from list In-Reply-To: References: Message-ID: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> On 20/04/2021 18:48, Manprit Singh wrote: > Consider a list given below: > lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] > i need to remove consecutive duplicates from list lst: > the answer must be : > > [2, 3, 4, 5, 3, 7, 9, 4] > > The code that i have written to solve it, is written below: > lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] > ls = lst[1:]+[object()] > [x for x, y in zip(lst, ls) if x != y] > > The list comprehension gives the desired result. just need to know if this > > program can be done in a more readable and less complex way. The itertools module has many tools that you can use to deal with problems like the above: The obvious one: >>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >>> wanted = [2, 3, 4, 5, 3, 7, 9, 4] >>> from itertools import zip_longest >>> wanted == [x for x, y in zip_longest(lst, lst[1:]) if x != y] True You may want to use islice instead of an actual slice. A variant that will continue to work if you replace the list with an iterator (e. g. a file): >>> from itertools import tee >>> a, b = tee(lst) >>> next(b) 2 >>> [x for x, y in zip_longest(a, b) if x != y] [2, 3, 4, 5, 3, 7, 9, 4] >>> wanted == _ True A conceptually different one, treating consecutive dupes as groups: >>> from itertools import groupby >>> wanted == [k for k, g in groupby(lst)] True Pick your favourite ;) From PyTutor at DancesWithMice.info Tue Apr 20 19:10:40 2021 From: PyTutor at DancesWithMice.info (dn) Date: Wed, 21 Apr 2021 11:10:40 +1200 Subject: [Tutor] removing consecutive duplicates from list In-Reply-To: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> References: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> Message-ID: On 21/04/2021 05.27, Peter Otten wrote: > On 20/04/2021 18:48, Manprit Singh wrote: > >> Consider a list given below: >> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >> i need to remove consecutive duplicates from list lst: >> the answer must be : >> >> [2, 3, 4, 5, 3, 7, 9, 4] >> >> The code that i have written to solve it, is written below: >> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >> ls = lst[1:]+[object()] >> [x for x, y in zip(lst, ls) if x != y] >> >> The list comprehension gives the desired result. just need to know if >> this >> >> program can be done in a more readable and less complex way. > The itertools module has many tools that you can use to deal with > problems like the above: ... >>>> from itertools import groupby >>>> wanted == [k for k, g in groupby(lst)] > True > > Pick your favourite ;) Whilst, admiring your (@Manprit) one-liner and @Peter's grasp of the itertools library; am imagining yellow, if not red, flags. Taking the term "less complex", let's ask: how many programmers (including yourself in six months' time) will be able to scan any of these and conclude?deduce that their objective is the removal of consecutive duplicates? At the very least, please enclose your 'brilliance' within a function, which will give it a (better than a comment) label/name, eg: def remove_consecutive_duplicates( source ): return [k for k, g in groupby(lst)] Ultimately, I favor @Alan's "explicit form" approach (shhhh! Don't tell him, else he'll fall off his chair...). Here's me dusting-off an old solution to this problem, which we used to give ComSc students - updated to (I think) v3.9+: from typing import Iterable lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] result = [2, 3, 4, 5, 3, 7, 9, 4] def remove_consecutive_duplicates( source:Iterable )->list: """Clean input iterable (containing any data-types), removing consecutive duplicates. """ cleaned = list() current_value = None for this_element in source: if this_element != current_value: cleaned.append( this_element ) current_value = this_element return cleaned print( "Correct?", result == remove_consecutive_duplicates( lst ) ) Plus: remove_consecutive_duplicates( "abba" ) == ['a', 'b', 'a'] -- Regards, =dn From manpritsinghece at gmail.com Tue Apr 20 22:38:15 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 21 Apr 2021 08:08:15 +0530 Subject: [Tutor] removing consecutive duplicates from list In-Reply-To: References: Message-ID: Dear all, I am again writing few points : I would prefer the solution given by Alan sir, as it seems easy to understand and simple, not using any extra variable, and also not using any module too like itertools. Although I would like to thank dn for his comments, in which he has strongly emphasised on enclosing solution code within a function, which is a good practise. Regards Manprit Singh On Tue, Apr 20, 2021 at 10:42 PM Alan Gauld via Tutor wrote: > On 20/04/2021 17:48, Manprit Singh wrote: > > > The code that i have written to solve it, is written below: > > lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] > > ls = lst[1:]+[object()] > > [x for x, y in zip(lst, ls) if x != y] > > > > The list comprehension gives the desired result. just need to know if > this > > program can be done in a more readable and less complex way. > > I'd suggest the more explicit form: > > >>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] > >>> result = [] > >>> for idx,itm in enumerate(lst): > if idx <= len(lst)-2 and itm == lst[idx+1]: > continue > result.append(itm) > > You could write that as a list comprehension but I think > it loses readability. > > >>> result2 = [itm for idx,itm in enumerate(lst) > if idx <= len(lst)-2 and itm != lst[idx+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 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From manpritsinghece at gmail.com Wed Apr 21 03:09:33 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 21 Apr 2021 12:39:33 +0530 Subject: [Tutor] Python program to remove a specific digit from every element of list Message-ID: Dear Sir, Consider a list lst = [333, 435, 479, 293, 536], i have to remove digit 3 from each element from this list, Along with this if a number made by all 3 is present in the list, that number has to be completely removed . the answer for list lst must be : [45, 479, 29, 56] The way i have solved it, is given below : def remove_digit(x, n): """Function that removes digit n from a number x """ ans, i = 0, 0 while x != 0: x, rem = divmod(x, 10) if rem != n: ans = ans + (rem * 10**i) i = i + 1 return ans lst = [333, 435, 479, 293, 536] ans = [remove_digit(ele, 3) for ele in lst if remove_digit(ele, 3)] print(ans) gives the desired answer as given above.Just need to know if Is there any better implementation for this problem ? assignment expression can be used in the list comprehension written above ? Regards Manprit Singh From __peter__ at web.de Wed Apr 21 03:39:01 2021 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Apr 2021 09:39:01 +0200 Subject: [Tutor] removing consecutive duplicates from list In-Reply-To: References: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> Message-ID: On 21/04/2021 01:10, dn via Tutor wrote: > On 21/04/2021 05.27, Peter Otten wrote: >> On 20/04/2021 18:48, Manprit Singh wrote: >> >>> Consider a list given below: >>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >>> i need to remove consecutive duplicates from list lst: >>> the answer must be : >>> >>> [2, 3, 4, 5, 3, 7, 9, 4] >>> >>> The code that i have written to solve it, is written below: >>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >>> ls = lst[1:]+[object()] >>> [x for x, y in zip(lst, ls) if x != y] >>> >>> The list comprehension gives the desired result. just need to know if >>> this >>> >>> program can be done in a more readable and less complex way. > > >> The itertools module has many tools that you can use to deal with >> problems like the above: > ... > >>>>> from itertools import groupby >>>>> wanted == [k for k, g in groupby(lst)] >> True >> >> Pick your favourite ;) > > > Whilst, admiring your (@Manprit) one-liner and @Peter's grasp of the > itertools library; am imagining yellow, if not red, flags. > > Taking the term "less complex", let's ask: how many programmers > (including yourself in six months' time) will be able to scan any of > these and conclude?deduce that their objective is the removal of > consecutive duplicates? > > At the very least, please enclose your 'brilliance' within a function, > which will give it a (better than a comment) label/name, eg: > > def remove_consecutive_duplicates( source ): > return [k for k, g in groupby(lst)] > > > Ultimately, I favor @Alan's "explicit form" approach (shhhh! Don't tell > him, else he'll fall off his chair...). > > Here's me dusting-off an old solution to this problem, which we used to > give ComSc students - updated to (I think) v3.9+: > > > > from typing import Iterable > > lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] > result = [2, 3, 4, 5, 3, 7, 9, 4] > > def remove_consecutive_duplicates( source:Iterable )->list: > """Clean input iterable (containing any data-types), > removing consecutive duplicates. > """ > cleaned = list() > current_value = None > for this_element in source: > if this_element != current_value: > cleaned.append( this_element ) > current_value = this_element > return cleaned > > print( "Correct?", result == remove_consecutive_duplicates( lst ) ) > > > Plus: > > remove_consecutive_duplicates( "abba" ) == ['a', 'b', 'a'] I am going to suggest you change that into a generator, like def remove_consecutive_duplicates(items): """Remove consecutive duplicates. >>> list(remove_consecutive_duplicates("")) [] >>> list(remove_consecutive_duplicates("abba")) ['a', 'b', 'a'] >>> list(remove_consecutive_duplicates( ... [1, 1.0, "x", "x", "x", "y", 2.0, 2]) ... ) [1, 'x', 'y', 2.0] >>> list(remove_consecutive_duplicates(iter("aabbbc"))) ['a', 'b', 'c'] >>> list(remove_consecutive_duplicates([None]*3)) [None] """ it = iter(items) try: prev = next(it) except StopIteration: I hate you, Chris A. ;) return yield prev for item in it: if prev != item: yield item prev = item From __peter__ at web.de Wed Apr 21 03:39:01 2021 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Apr 2021 09:39:01 +0200 Subject: [Tutor] removing consecutive duplicates from list In-Reply-To: References: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> Message-ID: On 21/04/2021 01:10, dn via Tutor wrote: > On 21/04/2021 05.27, Peter Otten wrote: >> On 20/04/2021 18:48, Manprit Singh wrote: >> >>> Consider a list given below: >>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >>> i need to remove consecutive duplicates from list lst: >>> the answer must be : >>> >>> [2, 3, 4, 5, 3, 7, 9, 4] >>> >>> The code that i have written to solve it, is written below: >>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >>> ls = lst[1:]+[object()] >>> [x for x, y in zip(lst, ls) if x != y] >>> >>> The list comprehension gives the desired result. just need to know if >>> this >>> >>> program can be done in a more readable and less complex way. > > >> The itertools module has many tools that you can use to deal with >> problems like the above: > ... > >>>>> from itertools import groupby >>>>> wanted == [k for k, g in groupby(lst)] >> True >> >> Pick your favourite ;) > > > Whilst, admiring your (@Manprit) one-liner and @Peter's grasp of the > itertools library; am imagining yellow, if not red, flags. > > Taking the term "less complex", let's ask: how many programmers > (including yourself in six months' time) will be able to scan any of > these and conclude?deduce that their objective is the removal of > consecutive duplicates? > > At the very least, please enclose your 'brilliance' within a function, > which will give it a (better than a comment) label/name, eg: > > def remove_consecutive_duplicates( source ): > return [k for k, g in groupby(lst)] > > > Ultimately, I favor @Alan's "explicit form" approach (shhhh! Don't tell > him, else he'll fall off his chair...). > > Here's me dusting-off an old solution to this problem, which we used to > give ComSc students - updated to (I think) v3.9+: > > > > from typing import Iterable > > lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] > result = [2, 3, 4, 5, 3, 7, 9, 4] > > def remove_consecutive_duplicates( source:Iterable )->list: > """Clean input iterable (containing any data-types), > removing consecutive duplicates. > """ > cleaned = list() > current_value = None > for this_element in source: > if this_element != current_value: > cleaned.append( this_element ) > current_value = this_element > return cleaned > > print( "Correct?", result == remove_consecutive_duplicates( lst ) ) > > > Plus: > > remove_consecutive_duplicates( "abba" ) == ['a', 'b', 'a'] I am going to suggest you change that into a generator, like def remove_consecutive_duplicates(items): """Remove consecutive duplicates. >>> list(remove_consecutive_duplicates("")) [] >>> list(remove_consecutive_duplicates("abba")) ['a', 'b', 'a'] >>> list(remove_consecutive_duplicates( ... [1, 1.0, "x", "x", "x", "y", 2.0, 2]) ... ) [1, 'x', 'y', 2.0] >>> list(remove_consecutive_duplicates(iter("aabbbc"))) ['a', 'b', 'c'] >>> list(remove_consecutive_duplicates([None]*3)) [None] """ it = iter(items) try: prev = next(it) except StopIteration: I hate you, Chris A. ;) return yield prev for item in it: if prev != item: yield item prev = item From alan.gauld at yahoo.co.uk Wed Apr 21 03:45:22 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 21 Apr 2021 08:45:22 +0100 Subject: [Tutor] Python program to remove a specific digit from every element of list In-Reply-To: References: Message-ID: On 21/04/2021 08:09, Manprit Singh wrote: > def remove_digit(x, n): > """Function that removes digit n from a number x """ > ans, i = 0, 0 > while x != 0: > x, rem = divmod(x, 10) > if rem != n: > ans = ans + (rem * 10**i) > i = i + 1 > return ans > > lst = [333, 435, 479, 293, 536] > ans = [remove_digit(ele, 3) for ele in lst if remove_digit(ele, 3)] > Is there any better implementation for this problem ? assignment Better? You decide. Shorter yes. >>> lst = [333, 435, 479, 293, 536] >>> res = [str(n).replace('3','') for n in lst] >>> res2 = [int(s) for s in res if s] >>> res2 [45, 479, 29, 56] >>> -- 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 Apr 21 04:48:21 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 21 Apr 2021 14:18:21 +0530 Subject: [Tutor] Python program to remove a specific digit from every element of list In-Reply-To: References: Message-ID: Dear sir, So let me tell you why I have asked this question, actually this problem is purely a numerical problem, why to solve this using strings ? why not in numerical way Regards Manprit Singh On Wed, Apr 21, 2021 at 1:16 PM Alan Gauld via Tutor wrote: > On 21/04/2021 08:09, Manprit Singh wrote: > > > def remove_digit(x, n): > > """Function that removes digit n from a number x """ > > ans, i = 0, 0 > > while x != 0: > > x, rem = divmod(x, 10) > > if rem != n: > > ans = ans + (rem * 10**i) > > i = i + 1 > > return ans > > > > lst = [333, 435, 479, 293, 536] > > ans = [remove_digit(ele, 3) for ele in lst if remove_digit(ele, 3)] > > > > Is there any better implementation for this problem ? assignment > > Better? You decide. Shorter yes. > > >>> lst = [333, 435, 479, 293, 536] > >>> res = [str(n).replace('3','') for n in lst] > >>> res2 = [int(s) for s in res if s] > >>> res2 > [45, 479, 29, 56] > >>> > > > -- > 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 Wed Apr 21 05:08:51 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 21 Apr 2021 10:08:51 +0100 Subject: [Tutor] Python program to remove a specific digit from every element of list In-Reply-To: References: Message-ID: On 21/04/2021 09:48, Manprit Singh wrote: > Dear sir, > So let me tell you why I have asked this question, actually this problem is > purely a numerical problem, why to solve this using strings ? Clearly it is not "purely a numerical problem" since it can be solved using strings. It just depends on how you look at it. Is it about removing a particular character or a particular number? Why use strings rather than numbers? Look at the length of the code for the two options. Look at the numbers of computations (each computation is a potential error). Which one is actually faster would require profiling and testing but I doubt there is much difference, especially for small data sets. For large datasets the string version will consume more memory. >>> def remove_digit(x, n): >>> """Function that removes digit n from a number x """ >>> ans, i = 0, 0 >>> while x != 0: >>> x, rem = divmod(x, 10) >>> if rem != n: >>> ans = ans + (rem * 10**i) >>> i = i + 1 >>> return ans >>> >>> lst = [333, 435, 479, 293, 536] >>> ans = [remove_digit(ele, 3) for ele in lst if remove_digit(ele, 3)] >> >> Better? You decide. Shorter yes. >> >>>>> lst = [333, 435, 479, 293, 536] >>>>> res = [str(n).replace('3','') for n in lst] >>>>> res2 = [int(s) for s in res if s] -- 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 Apr 21 05:56:24 2021 From: PyTutor at DancesWithMice.info (dn) Date: Wed, 21 Apr 2021 21:56:24 +1200 Subject: [Tutor] removing consecutive duplicates from list In-Reply-To: References: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> Message-ID: <6d61f0e3-f80f-0846-fde5-a99e50e73172@DancesWithMice.info> On 21/04/2021 19.39, Peter Otten wrote: > On 21/04/2021 01:10, dn via Tutor wrote: >> On 21/04/2021 05.27, Peter Otten wrote: >>> On 20/04/2021 18:48, Manprit Singh wrote: >>> >>>> Consider a list given below: >>>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >>>> i need to remove consecutive duplicates from list lst: >>>> the answer must be : >>>> >>>> [2, 3, 4, 5, 3, 7, 9, 4] >>>> >>>> The code that i have written to solve it, is written below: >>>> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >>>> ls = lst[1:]+[object()] >>>> [x for x, y in zip(lst, ls) if x != y] >>>> >>>> The list comprehension gives the desired result. just need to know if >>>> this >>>> >>>> program can be done in a more readable and less complex way. >> >> >>> The itertools module has many tools that you can use to deal with >>> problems like the above: >> ... >> >>>>>> from itertools import groupby >>>>>> wanted == [k for k, g in groupby(lst)] >>> True >>> >>> Pick your favourite ;) >> >> >> Whilst, admiring your (@Manprit) one-liner and @Peter's grasp of the >> itertools library; am imagining yellow, if not red, flags. >> >> Taking the term "less complex", let's ask: how many programmers >> (including yourself in six months' time) will be able to scan any of >> these and conclude?deduce that their objective is the removal of >> consecutive duplicates? >> >> At the very least, please enclose your 'brilliance' within a function, >> which will give it a (better than a comment) label/name, eg: >> >> def remove_consecutive_duplicates( source ): >> ???? return [k for k, g in groupby(lst)] >> >> >> Ultimately, I favor @Alan's "explicit form" approach (shhhh! Don't tell >> him, else he'll fall off his chair...). >> >> Here's me dusting-off an old solution to this problem, which we used to >> give ComSc students - updated to (I think) v3.9+: >> >> >> >> from typing import Iterable >> >> lst = [2, 3, 3, 4, 5, 5, 3, 7, 9, 9, 4] >> result = [2, 3, 4, 5, 3, 7, 9, 4] >> >> def remove_consecutive_duplicates( source:Iterable )->list: >> ???? """Clean input iterable (containing any data-types), >> ??????? removing consecutive duplicates. >> ???? """ >> ???? cleaned = list() >> ???? current_value = None >> ???? for this_element in source: >> ???????? if this_element != current_value: >> ???????????? cleaned.append( this_element ) >> ???????????? current_value = this_element >> ???? return cleaned >> >> print( "Correct?", result == remove_consecutive_duplicates( lst ) ) >> >> >> Plus: >> >> remove_consecutive_duplicates( "abba" ) == ['a', 'b', 'a'] > > I am going to suggest you change that into a generator, like > > def remove_consecutive_duplicates(items): > ?? """Remove consecutive duplicates. > > ?? >>> list(remove_consecutive_duplicates("")) > ?? [] > ?? >>> list(remove_consecutive_duplicates("abba")) > ?? ['a', 'b', 'a'] > ?? >>> list(remove_consecutive_duplicates( > ?? ... [1, 1.0, "x", "x", "x", "y", 2.0, 2]) > ?? ... ) > ?? [1, 'x', 'y', 2.0] > ?? >>> list(remove_consecutive_duplicates(iter("aabbbc"))) > ?? ['a', 'b', 'c'] > ?? >>> list(remove_consecutive_duplicates([None]*3)) > ?? [None] > ?? """ > ?? it = iter(items) > ?? try: > ?????? prev = next(it) > ?? except StopIteration: I hate you, Chris A. ;) > ?????? return > ?? yield prev > ?? for item in it: > ?????? if prev != item: > ?????????? yield item > ?????????? prev = item Like it! (not sure why we're beating-up Chris though) ...except that the OP seemed to want a list as the result. That said, I've adopted a policy of converting older utility-functions to generators. Thus, new extension to the question: Received-wisdom says that the generator will require less storage (although with the external/surrounding list() I'm wondering if that is true in-fact in this (rather artificial) case); but which approach executes faster? a/ appended list, b/ generator - with the surrounding list(), c/ generator - without the surrounding list(). -- Regards, =dn -- Regards, =dn From __peter__ at web.de Wed Apr 21 08:04:36 2021 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Apr 2021 14:04:36 +0200 Subject: [Tutor] [OT] Re: removing consecutive duplicates from list In-Reply-To: <6d61f0e3-f80f-0846-fde5-a99e50e73172@DancesWithMice.info> References: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> <6d61f0e3-f80f-0846-fde5-a99e50e73172@DancesWithMice.info> Message-ID: On 21/04/2021 11:56, dn via Tutor wrote: > On 21/04/2021 19.39, Peter Otten wrote: >> ?? it = iter(items) >> ?? try: >> ?????? prev = next(it) >> ?? except StopIteration: I hate you, Chris A. ;) >> ?????? return >> ?? yield prev > (not sure why we're beating-up Chris though) https://www.python.org/dev/peps/pep-0479/ Prior to that you could write the above without the try...except. From __peter__ at web.de Wed Apr 21 08:04:36 2021 From: __peter__ at web.de (Peter Otten) Date: Wed, 21 Apr 2021 14:04:36 +0200 Subject: [Tutor] [OT] Re: removing consecutive duplicates from list In-Reply-To: <6d61f0e3-f80f-0846-fde5-a99e50e73172@DancesWithMice.info> References: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> <6d61f0e3-f80f-0846-fde5-a99e50e73172@DancesWithMice.info> Message-ID: On 21/04/2021 11:56, dn via Tutor wrote: > On 21/04/2021 19.39, Peter Otten wrote: >> ?? it = iter(items) >> ?? try: >> ?????? prev = next(it) >> ?? except StopIteration: I hate you, Chris A. ;) >> ?????? return >> ?? yield prev > (not sure why we're beating-up Chris though) https://www.python.org/dev/peps/pep-0479/ Prior to that you could write the above without the try...except. From PyTutor at DancesWithMice.info Wed Apr 21 18:25:11 2021 From: PyTutor at DancesWithMice.info (dn) Date: Thu, 22 Apr 2021 10:25:11 +1200 Subject: [Tutor] [OT] Re: removing consecutive duplicates from list In-Reply-To: References: <7830dfc1-7413-d983-d699-acf1e60695b8@web.de> <6d61f0e3-f80f-0846-fde5-a99e50e73172@DancesWithMice.info> Message-ID: On 22/04/2021 00.04, Peter Otten wrote: > On 21/04/2021 11:56, dn via Tutor wrote: >> On 21/04/2021 19.39, Peter Otten wrote: > >>> ??? it = iter(items) >>> ??? try: >>> ??????? prev = next(it) >>> ??? except StopIteration: I hate you, Chris A. ;) >>> ??????? return >>> ??? yield prev > >> (not sure why we're beating-up Chris though) > > https://www.python.org/dev/peps/pep-0479/ > > Prior to that you could write the above without the try...except. I agree that in this simple/straight-line/non-nested situation, it seems unnecessary. However, when chasing errors buried within the depths of nested constructs, subtlety does seem to be the order of the day. (tools lacking differential analysis leading to actions such as chucking the computer out of a window) - and worse, the prior opening of said window lacking try...except (self-)control! NB a few days ago, New Zealand opened a COVID-free 'travel bubble' with most Australian states. Also, it will be ANZAC Day on Sunday, celebrating the brotherhood (in suffering) of Australia and New Zealand fighting for freedom. So, those of us in the North and South Islands of this country are supposed to be getting cuddly with our Koala-cousins over in 'West Island' - so I may be a little biased... -- Regards, =dn From mmssdd1920 at gmail.com Mon Apr 26 07:47:06 2021 From: mmssdd1920 at gmail.com (Msd De) Date: Mon, 26 Apr 2021 17:17:06 +0530 Subject: [Tutor] python debug Message-ID: Dear Sir, How to use nested def for two functions to integrate over a variable. The error displayed is TypeError: can't multiply sequence by non-int of type 'function Regards, M De From luigi.bibbo at unirc.it Mon Apr 26 06:41:30 2021 From: luigi.bibbo at unirc.it (Luigi =?utf-8?Q?Bibb=C3=B2?=) Date: Mon, 26 Apr 2021 12:41:30 +0200 (CEST) Subject: [Tutor] convert Keras to Onnx Message-ID: <1510472536.16419352.1619433690484.JavaMail.zimbra@unirc.it> Good morning, I need to convert pre-trained model Keras to Onnx. When I am going to convert the system replies: module 'keras' has no attribute,'_is_graph_network'. Thank you Best Regards Luigi From alan.gauld at yahoo.co.uk Mon Apr 26 09:09:08 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 26 Apr 2021 14:09:08 +0100 Subject: [Tutor] convert Keras to Onnx In-Reply-To: <1510472536.16419352.1619433690484.JavaMail.zimbra@unirc.it> References: <1510472536.16419352.1619433690484.JavaMail.zimbra@unirc.it> Message-ID: On 26/04/2021 11:41, Luigi Bibb? wrote: > Good morning, > I need to convert pre-trained model Keras to Onnx. This list is for the python core language and its standard library. This sounds like it might be SciPy related, in which case you will probably get a better response on the SciPy support forums. > When I am going to convert the system replies: > module 'keras' has no attribute,'_is_graph_network'. Please include the entire error message since it contains a lot of useful data. However, we also need to see the code producing the error. Otherwise we are just guessing. Also, if keras is not part of SciPy then a link to the module documentation might help too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Mon Apr 26 09:14:16 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 26 Apr 2021 14:14:16 +0100 Subject: [Tutor] convert Keras to Onnx In-Reply-To: References: <1510472536.16419352.1619433690484.JavaMail.zimbra@unirc.it> Message-ID: On 26/04/2021 14:09, Alan Gauld via Tutor wrote: > Also, if keras is not part of SciPy then a link to > the module documentation might help too. I did a quick Google. There is a keras mailing list: https://groups.google.com/forum/#!forum/keras-users You are probably best to ask 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 mats at wichmann.us Mon Apr 26 09:15:40 2021 From: mats at wichmann.us (Mats Wichmann) Date: Mon, 26 Apr 2021 07:15:40 -0600 Subject: [Tutor] python debug In-Reply-To: References: Message-ID: <9a4baba5-1a76-6392-e675-e7e2a6486cf2@wichmann.us> On 4/26/21 5:47 AM, Msd De wrote: > Dear Sir, > How to use nested def for two functions to integrate over a variable. > The error displayed is > TypeError: can't multiply sequence by non-int of type 'function Perhaps share the code that's causing the error? Usually the errors are pretty descriptive and this one suggests "you're doing it wrong", but we can't see how. >>> def f(): ... pass ... >>> >>> s = [1, 2, 3] >>> s * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> s * f Traceback (most recent call last): File "", line 1, in TypeError: can't multiply sequence by non-int of type 'function' Perhaps you left out the parentheses when calling your nested function? From alan.gauld at yahoo.co.uk Mon Apr 26 09:16:16 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 26 Apr 2021 14:16:16 +0100 Subject: [Tutor] python debug In-Reply-To: References: Message-ID: On 26/04/2021 12:47, Msd De wrote: > Dear Sir, > How to use nested def for two functions to integrate over a variable. > The error displayed is > TypeError: can't multiply sequence by non-int of type 'function Show us the code causing the error and the full error message. There is a lot of data in the traceback that the summary does not reveal. Also what libraries are you using to "integrate"? Finally OS and python version are usually helpful too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at gmail.com Mon Apr 26 09:16:18 2021 From: breamoreboy at gmail.com (Mark Lawrence) Date: Mon, 26 Apr 2021 14:16:18 +0100 Subject: [Tutor] python debug In-Reply-To: References: Message-ID: On 26/04/2021 12:47, Msd De wrote: > Dear Sir, > How to use nested def for two functions to integrate over a variable. > The error displayed is > TypeError: can't multiply sequence by non-int of type 'function > Regards, > M De Please give us the code that doesn't work, the full traceback and preferably also the Python and OS version. There's some smart people here but we're not mind readers :) -- 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 Mon Apr 26 11:48:24 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Mon, 26 Apr 2021 21:18:24 +0530 Subject: [Tutor] Python strings example Message-ID: Dear sir, consider a problem where I have to write a function that can return True if the string passed to the function contains at least one digit character and one alphabet character, else the function must return False. The way i am solving it is given below : def str_chk(word_tochk): dig = False alpha = False for ele in word_tochk: dig = dig or ele.isdigit() alpha = alpha or ele.isalpha() return dig and alpha st = "Abhay2" ans = str_chk(st) print(ans) returns True, which is correct as the string contains an alphabet as well as a digit character. st = "Abhay" ans = str_chk(st) print(ans) returns False . which is also correct as there is no digit character in the string now Any suggestions, if the solution can be improved . Regards Manprit Singh From __peter__ at web.de Mon Apr 26 12:22:34 2021 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 Apr 2021 18:22:34 +0200 Subject: [Tutor] Python strings example In-Reply-To: References: Message-ID: On 26/04/2021 17:48, Manprit Singh wrote: > Dear sir, > > consider a problem where I have to write a function that can return True if > the string passed to the function contains at least one digit character and > one alphabet character, else the function must return False. The way i am > solving it is given below : > def str_chk(word_tochk): > dig = False > alpha = False > for ele in word_tochk: > dig = dig or ele.isdigit() > alpha = alpha or ele.isalpha() > return dig and alpha > > > st = "Abhay2" > ans = str_chk(st) > print(ans) returns True, which is correct as the string contains an > alphabet as well as a digit character. > > st = "Abhay" > ans = str_chk(st) > print(ans) returns False . which is also correct as there is no digit > character in the string now > > Any suggestions, if the solution can be improved . I would perform the two tests separately. In the worst case you have to iterate over the string twice, but if you're lucky you only have to scan a small portion of the string. def has_digits_and_alphas(s): return ( any(c.isdigit() for c in s) and any(c.isalpha() for c in s) ) From __peter__ at web.de Mon Apr 26 12:22:34 2021 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 Apr 2021 18:22:34 +0200 Subject: [Tutor] Python strings example In-Reply-To: References: Message-ID: On 26/04/2021 17:48, Manprit Singh wrote: > Dear sir, > > consider a problem where I have to write a function that can return True if > the string passed to the function contains at least one digit character and > one alphabet character, else the function must return False. The way i am > solving it is given below : > def str_chk(word_tochk): > dig = False > alpha = False > for ele in word_tochk: > dig = dig or ele.isdigit() > alpha = alpha or ele.isalpha() > return dig and alpha > > > st = "Abhay2" > ans = str_chk(st) > print(ans) returns True, which is correct as the string contains an > alphabet as well as a digit character. > > st = "Abhay" > ans = str_chk(st) > print(ans) returns False . which is also correct as there is no digit > character in the string now > > Any suggestions, if the solution can be improved . I would perform the two tests separately. In the worst case you have to iterate over the string twice, but if you're lucky you only have to scan a small portion of the string. def has_digits_and_alphas(s): return ( any(c.isdigit() for c in s) and any(c.isalpha() for c in s) ) From ankitgupta38017 at gmail.com Mon Apr 26 12:20:19 2021 From: ankitgupta38017 at gmail.com (Ankit Gupta) Date: Mon, 26 Apr 2021 21:50:19 +0530 Subject: [Tutor] Python strings example In-Reply-To: References: Message-ID: In 2nd example you return will look something like this "return False and True" which will result in False as AND operation will only return TRUE if both value is TRUE. as I can understand you want to return TRUE if sentence contain at least one character or at least one digit or both. Therefore I will suggest to use OR instead of AND operation. Ankit Gupta. On Mon, 26 Apr, 2021, 9:19 pm Manprit Singh, wrote: > Dear sir, > > consider a problem where I have to write a function that can return True if > the string passed to the function contains at least one digit character and > one alphabet character, else the function must return False. The way i am > solving it is given below : > def str_chk(word_tochk): > dig = False > alpha = False > for ele in word_tochk: > dig = dig or ele.isdigit() > alpha = alpha or ele.isalpha() > return dig and alpha > > > st = "Abhay2" > ans = str_chk(st) > print(ans) returns True, which is correct as the string contains an > alphabet as well as a digit character. > > st = "Abhay" > ans = str_chk(st) > print(ans) returns False . which is also correct as there is no digit > character in the string now > > Any suggestions, if the solution can be improved . > > 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 Mon Apr 26 14:45:29 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 26 Apr 2021 19:45:29 +0100 Subject: [Tutor] Python strings example In-Reply-To: References: Message-ID: On 26/04/2021 17:20, Ankit Gupta wrote: > as I can understand you want to return TRUE if sentence contain at least > one character or at least one digit or both. Nope, he explicitly says he wants AND... >> the string passed to the function contains at least one digit character and >> one alphabet character, else the function must return False. So AND is the correct operator. -- 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 Apr 26 22:49:17 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Tue, 27 Apr 2021 08:19:17 +0530 Subject: [Tutor] Python strings example In-Reply-To: References: Message-ID: Dear Sir, Coming to my question again. what i want to discuss is, If you look at Peter's solution, you can see it is using two generator expressions(I mean to say there is a utilization of two for loops that increases complexity) what practices should be adopted in such cases ? the one done by Peter or the one done by me ? need your guidance. On Mon, Apr 26, 2021 at 9:18 PM Manprit Singh wrote: > Dear sir, > > consider a problem where I have to write a function that can return True > if the string passed to the function contains at least one digit character > and one alphabet character, else the function must return False. The way i > am solving it is given below : > def str_chk(word_tochk): > dig = False > alpha = False > for ele in word_tochk: > dig = dig or ele.isdigit() > alpha = alpha or ele.isalpha() > return dig and alpha > > > st = "Abhay2" > ans = str_chk(st) > print(ans) returns True, which is correct as the string contains an > alphabet as well as a digit character. > > st = "Abhay" > ans = str_chk(st) > print(ans) returns False . which is also correct as there is no digit > character in the string now > > Any suggestions, if the solution can be improved . > > Regards > Manprit Singh > > From alan.gauld at yahoo.co.uk Tue Apr 27 04:36:42 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 27 Apr 2021 09:36:42 +0100 Subject: [Tutor] Python strings example In-Reply-To: References: Message-ID: On 27/04/2021 03:49, Manprit Singh wrote: > If you look at Peter's solution, you can see it is using two generator > expressions(I mean to say there is a utilization of two for loops that > increases complexity) what practices should be adopted in such cases ? the > one done by Peter or the one done by me ? The complexity is not much different since your function has 4 assignments, one for-loop and two boolean expressions. Peter's has 2 generator expressions and one boolean expression. Peter's also has a more direct statement of the logic which makes it easier to read and understand. It is also (probably) more efficient for large strings since any() will stop at the first occurrence whereas your loop tests every character. We can avoid that in your function but only by adding yet another test: def str_chk(word_tochk): dig = False alpha = False for ele in word_tochk: dig = dig or ele.isdigit() alpha = alpha or ele.isalpha() if dig and alpha: return True return False But that then adds more complexity. -- 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 Tue Apr 27 04:47:12 2021 From: PyTutor at DancesWithMice.info (dn) Date: Tue, 27 Apr 2021 20:47:12 +1200 Subject: [Tutor] Python strings example In-Reply-To: References: Message-ID: On 27/04/2021 14.49, Manprit Singh wrote: > Coming to my question again. what i want to discuss is, > > If you look at Peter's solution, you can see it is using two generator > expressions(I mean to say there is a utilization of two for loops that > increases complexity) what practices should be adopted in such cases ? the > one done by Peter or the one done by me ? > need your guidance. Not really! IMHO there is no one, and only one, correct answer - because you must first define "correct". Both of the ideas presented are correct in terms of output-produced. What else is there? There are various ways to look at "complexity", lets take: - is it easy to read (programmer cognition) - execution efficiency (the time or other resources required) (this is not a very exact example, but I hope illustrates the point) The purpose of generators is a "lazy" production of a range. Under Python2 range( 5000 ) would require five-thousand values be stored. Under Python3 the values are only calculated and made available upon request; and thus (almost) don't have any storage requirement (we used to call this "xrange()"). Which is more "complex" - the one which requires more storage resources, or the one which seems harder for the programmer to understand? (YMMV!) In the first case, and as said before, what is acceptable depends upon your team. If you include Apprentices, then the level of complexity should be lower than if you are all Masters. Perhaps then you, ie the team conducting a Code Review, will prefer the more obvious loop to the programmatically more-succinct twin-comprehensions? Execution efficiency is easily measured in this case. (The storage-required is the length of the string. So, no 'big deal'!) You are perfectly capable of building a 'harness' to repeatedly execute a function/body-of-code and divide the number of repetitions by the time-required (or vice-versa). Again IMHO, @Peter's code is not particularly difficult to follow, so I (personally) wouldn't red-flag it - even on-behalf of others. Instead, if there are 'Apprentices' to be considered, I'd suggest it as a learning-experience... Accordingly, let's address the thought @Peter raised. Perhaps you should consider ways to compare methods (algorithms) - preferably before any code is written. Are you aware of "Big O Notation"? (web.ref below) Thinking about it, the first example code runs all the way through the string of characters. If the data is bound to fail, eg "Abhay", then we must consider every character, regardless. In your other example, "Abhay2", it is also necessary to complete a 100% review - but that is a factor of the data-chosen. (let's come back to that in a moment) Because the algorithm works logically, character-by-character through the input-string, the time required is described as "linear". Execution-time will be (basically) a factor of the number of characters in the string. This concept is sometimes written "O(n)". However, as soon as we change the data, eg to "Ab2hay", do we need to inspect every character? No! Because, in this case, by the third character we have satisfied both requirements. Now, when we consider a statistical distribution of letters and digits, we realise that it is only necessary to look at an average of half of the number of characters in the input-string, ie O( n/2 ). The twin-comprehensions will only run for as long as it takes to find the first letter, plus as long as it takes to find the first digit, (respectively). This works-out to almost the same O( n/2 ) - as observed, by definition some characters will be inspected more than once! Herewith a revision of the original code to O( n/2 ): def password_check( candidate:str )->bool: alpha_found = False digit_found = False loops = 0 for character in candidate: if character.isalpha(): alpha_found = True if character.isdigit(): digit_found = True loops += 1 if alpha_found and digit_found: break return alpha_found and digit_found, loops print( password_check( "Abhay2" ) ) print( password_check( "Abhay" ) ) print( password_check( "Ab2hay" ) ) Output:- (True, 6) (False, 5) (True, 3) Notes: You will have realised that the tuple o/p is purely to illustrate the number of loops necessary to reach approval/failure. On the subject of cognitive-complexity; please also note this 'grumpy, old, man' has refactored to use more easily-recognised names! (more readable == less complex !!!) Perhaps you could build a speed-test harness, and report results/comparisons (using a wider range of data-samples). Does this implementation offer benefits/simplicity under both headings of "complexity", ie is it both easy to read and as elegant as the twin-comprehension's efficiency? In the case of short strings like these, I have to say any efficiency-gain will be all-but negligible. However, if you were working with larger volumes of data, such tactics (algorithm classifications) come into their own! My expectation ('gut feeling') is that the C-code 'behind' the generators will execute more quickly than the code above. Care to run a three-way comparison and report-back? Thereafter, let's return to the question of "complexity" and hear what you think and why... Web.Ref: Algorithm Time Complexity and Big O Notation By Stuart Kuredjian - March 17, 2017 https://www.linux.com/training-tutorials/algorithm-time-complexity-and-big-o-notation-0/ -- Regards, =dn From manpritsinghece at gmail.com Tue Apr 27 23:12:40 2021 From: manpritsinghece at gmail.com (Manprit Singh) Date: Wed, 28 Apr 2021 08:42:40 +0530 Subject: [Tutor] Use case of assignment expression Message-ID: Dear sir , Consider an example to find the words from a given sentence having given word as prefix, program should return -1 if no such words found in the sentence. The code is written below : def word_found(string, wd): if word := [ele for ele in string.split() if ele.startswith(wd)]: return word else: return -1 st = "Anuj is a good boy" wd = "goo" ans = word_found(st, wd) print(ans) returns ['good'] that is correct st = "Anuj is a bad boy" wd = "goo" ans = word_found(st, wd) print(ans) returns -1 that is also correct. My question is regarding assignment expressions used in function definition. Is this the appropriate use of assignment expression? Need your guidance. Regards Manprit Singh From alan.gauld at yahoo.co.uk Wed Apr 28 05:22:35 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 28 Apr 2021 10:22:35 +0100 Subject: [Tutor] Use case of assignment expression In-Reply-To: References: Message-ID: On 28/04/2021 04:12, Manprit Singh wrote: > Consider an example to find the words from a given sentence having given > word as prefix, program should return -1 if no such words found in the > sentence. Thats a terrible definition of a function. Functions should return the same kind of object regardless of the outcome (if that is not possible for some reason then raise an error) the options here should therefore be: 1) return a list of matching words or an empty list 2) return the indices of matching words or -1 if no matches (or raise an IndexError) 3) return a boolean result 4) return the first matching word or the empty string. This is especially important in OOP since you want the returned object to be polymorphic and avoid any type-checking code structures. > def word_found(string, wd): > if word := [ele for ele in string.split() if ele.startswith(wd)]: > return word > else: > return -1 There is no good reason for the assignment operator here. You could just do (assuming we really have to return -1!) def word_found(string, wd): return ([ele for ele in string.split() if ele.startswith(wd)] or -1) > My question is regarding assignment expressions used in function > definition. Is this the appropriate use of assignment expression? I try to avoid assignment expressions due to a pathological fear of them from C. They are one of the most common causes of hard to find bugs in C. Python's variant is much less bug prone but my past experience is so seared into my conscious mind that I still avoid them as far as possible. Certainly in this case there is no need for it so I'd avoid 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 PyTutor at DancesWithMice.info Wed Apr 28 05:27:11 2021 From: PyTutor at DancesWithMice.info (dn) Date: Wed, 28 Apr 2021 21:27:11 +1200 Subject: [Tutor] Use case of assignment expression In-Reply-To: References: Message-ID: [earlier copy sent to OP but missed the list - apologies] On 28/04/2021 15.12, Manprit Singh wrote: > Dear sir , > > Consider an example to find the words from a given sentence having given > word as prefix, program should return -1 if no such words found in the > sentence. > > The code is written below : > > def word_found(string, wd): > if word := [ele for ele in string.split() if ele.startswith(wd)]: > return word > else: > return -1 > > st = "Anuj is a good boy" > wd = "goo" > ans = word_found(st, wd) > print(ans) returns ['good'] that is correct > > st = "Anuj is a bad boy" > wd = "goo" > ans = word_found(st, wd) > print(ans) returns -1 that is also correct. > > My question is regarding assignment expressions used in function > definition. Is this the appropriate use of assignment expression? It works! If the version of Python in-use supports assignment-expressions, what concerns do you have? (that it is being used inside a function?) Ideas and discussion at https://www.python.org/dev/peps/pep-0572/ What is of-concern is that the problem has been formulated in an old-fashioned manner - and possibly for use with other languages. "Clean code" principles describe returning a single value which has multiple meanings as a 'bad smell' (even though it is done all-the-time). [a re-statement of @Dennis' point] Python offers (at least) two further alternatives which may not have been possible in the past/in some other language: - return two values: one indicating found/not (likely a boolean), and the other the word-list - use raise and try...except to handle the not-found scenario -- Regards, =dn From akrocks889 at gmail.com Wed Apr 28 16:14:10 2021 From: akrocks889 at gmail.com (Anosh Kaniskar) Date: Thu, 29 Apr 2021 01:44:10 +0530 Subject: [Tutor] Error using Xgboost regressor Message-ID: Hi, I'm getting error when trying to fit the data into the xgboost regressor model, I hope the code is correct and didn't understand the reason for getting this error. Also before I used pca to reduce the dimensionality of the data.. and applied Multiple linear regression after this i tried performing xgboost regression model.. please make me understand what is going wrong here.. I've shared the screenshots.. Regards Anosh From alan.gauld at yahoo.co.uk Wed Apr 28 16:31:58 2021 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 28 Apr 2021 21:31:58 +0100 Subject: [Tutor] Error using Xgboost regressor In-Reply-To: References: Message-ID: On 28/04/2021 21:14, Anosh Kaniskar wrote: > I'm getting error when trying to fit the data into the xgboost regressor > model, I hope the code is correct and didn't understand the reason for > getting this error. We can't see any cde so can't comment. Its possible you sent it as an attachment, in which case the server will have stripped it for security reasons. However, this list is really for questions about the Python language and standard library. Exotic topics such as this usually have their own support forums where you will get much more experienced support. A quick Google search threw up: https://discuss.xgboost.ai/ Which seems to be pretty active. > Also before I used pca to reduce the dimensionality of the data.. > and applied Multiple linear regression after this i tried performing > xgboost regression model.. > please make me understand what is going wrong here.. I've shared the > screenshots.. As I say, binary attachments will have been stripped off for security. I've no idea what the paragraph above means but I'm sure the xgboost community will know what you need. -- 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