Re: [Tutor] Learning Regular Expressions
Thanks Alan I noticed that I was using some double ' to encircle some things and some single ' for apostrophes in contractionsand fixed those...but apparently since you could run it, that part didn't matter. The problem was ultimately caused by a stray ''' which was a fragment of me messing with things trying to fix them and it slipped down my screen and was hidden from me when I would look at the script! Thanks for double checking me. :) On 05/30/2016 03:07 PM, Alan Gauld via Tutor wrote: On 30/05/16 18:21, dirkjso...@gmail.com wrote: I moved my notes that contained any '\'s to a different python file. However, if we run it, we get the error I was having. Here's the script: Runs fine for me. Can you run it using the python command line interpreter rather than IDLE? Do you still get errors? If so cut n paste the full error to the list. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Learning Regular Expressions
Running Linux Mint The YouTube Sentdex Video tutor I am following. He is working in Python3.4 and I am running Python3.4.3 He's demonstrating some Regular Expressions which I wanted to test out. On these test scripts, for future referrence, I have been putting my notes in Tripple Quotes and naming the scripts descriptively to be able to find them again, when I need to review. However, this time, when I copied in a simple script below my RE notes, and ran it from IDLE (and from Console) I got the following error: SyntaxError: EOF while scanning triple-quoted string literal Now, there was also a tripple-quoted string I had set a variable to in my script...so I thought it was the active part of the script! But eventually, through the process of elimination, I discovered the scripted worked great without the notes! I'd like to know what it is in the below Tripple-Quoted section that is causing me this problem...if anyone recognizes. In IDLE's script file..._it's all colored green_, which I thought meant Python was going to ignore everything between the tripple-quotes! But if I run just the below portion of the script in it's own file, I get the same While Scanning Tripple-Quotes error. #!/usr/bin/env python3 ''' Regular Expressions - or at least some Identifiers: \d any number \D anything but a number (digit) \s space \S anything but a space \w any character \W anything but a character . any character (or even a period itself if you use \.) except for a newline a search for just the letter 'a' \b the white space around words Modifiers {x}we are expecting "x" number of something {1, 3} we're expecting 1-3 in length of something -, so for digits we write \d{1-3} + means Match 1 or more ? means Match 0 or 1 * Match 0 or more $ Match the end of a string ^ Match the beginning of a string | Match either or - so you might write \d{1-3} | \w{5-6} [ ] a range or "variance" such as [A-Z] or [A-Za-z] Cap 1st letter followed by lower case or [1-5a-qA-Z] starts with a number inclusive of 1-5 then lower case letter then followed by any Cap letter! :) White Space Characters (may not be seen): \n new line \s space \t tab \e escape \f form feed \r return DON'T FORGET!: . + * ? [ ] $ ^ ( ) { } | \ if you really want to use these, you must escape them '\' ''' Thanks for your thoughts! --Terry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Starships -- object of type 'int' has no len()
Thanks Japhy Bartlett! [[0] for i in range(5)] Works! I converted to fit into my routine as: lens = [[] for i in range(len(catalog2[0]))] the new statement for row in catalog2: for col, item in enumerate(row): lens[col].append(len(item)) lens = [max(col) for col in lens] print(lens) My result is: [6, 17, 5, 9, 12, 7, 0, 0, 0] THAT IS THE CORRECT ANSWER! Perfect! Peter Otten Thanks! Those work also! Danny Yoo Thanks for the Documentation on creating multidimensioned lists! Interesting read! And now I know why my first attempts to get multi-dimensions from an equation failed. Alan Gauld YUP! lens = [ [] for n in catalog2[0] ] Works! --And greatly simplifies how I first constructed this! Thanks! Thanks Everyone! This gets me going again ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Starships -- object of type 'int' has no len()
Alan Gauld Hi! We are not quite out of the woods on this last example you gave me. It now seems to be complaining that it doesn't want to append an integer to the list or that this isn't the place to use '.append' -- I am probably interpreting it's complaint wrong: Python 3.3 If I run this last piece of code that we just added 'enumerate(row)' to: lens = [0] * len(catalog2[0]) for row in catalog2: for col, item in enumerate(row): print(col, item, len(item)) lens[col].append(len(item)) lens = [max(col) for col in lens] My result is: 0 Drives 6 my print statement result Traceback (most recent call last): File /home/justme/1a_Computer_Related/Python/scripts/scratch.py, line 43, in module lens[col].append(len(item)) AttributeError: 'int' object has no attribute 'append' While messing with the above problem, I found myself thinking (almost always a mistake on my part) that the '.append' extension doesn't need the list pre-formatted any more than a simple lens= [], since .append has the ability to expand the list anyway, which would let the number of columns be more easily expanded later in life by the programmer simply adding a column of data to the table, so I tried- lens = [] for row in catalog2: for col, item in enumerate(row): print(col, item, len(item)) lens[col].append(len(item)) lens = [max(col) for col in lens] But my result says otherwise: 0 Drives 6 Traceback (most recent call last): File /home/justme/1a_Computer_Related/Python/scripts/scratch.py, line 45, in module lens[col].append(len(item)) IndexError: list index out of range ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Starships -- object of type 'int' has no len()
Marc, my understanding is, is that: lens[col].append(len(item)) -should be building a mirror image of my list of lists called catalog2, which currently has 9 columns by x number of rows, and that we are plugging into these positions, the sizes of all the elements in that block of data. If that is true, then lens[col] is creating lists which contain the sizes of the elements in that particular column. So, I completely don't understand why we would eliminate the positioning of which list we are referencing in lens by saying: lens.append(len(item)) It seems to me that, that statement would put the entire block of element sizes into one list, and the next MAX statement would then yield only a single number, which would be the largest size element it encounted in the whole of catalog2! Or am I really missing the boat here? :) Thanks for your thoughts! --Terry On 08/20/2014 02:26 PM, Marc Tompkins wrote: On Aug 20, 2014 12:07 PM, Terry--gmail terry.kemme...@gmail.com mailto:terry.kemme...@gmail.com wrote: Alan Gauld Hi! We are not quite out of the woods on this last example you gave me. It now seems to be complaining that it doesn't want to append an integer to the list or that this isn't the place to use '.append' -- I am probably interpreting it's complaint wrong: Python 3.3 If I run this last piece of code that we just added 'enumerate(row)' to: lens = [0] * len(catalog2[0]) for row in catalog2: for col, item in enumerate(row): print(col, item, len(item)) lens[col].append(len(item)) lens = [max(col) for col in lens] My result is: 0 Drives 6 my print statement result Traceback (most recent call last): File /home/justme/1a_Computer_Related/Python/scripts/scratch.py, line 43, in module lens[col].append(len(item)) AttributeError: 'int' object has no attribute 'append' Once again you're confusing the list with its contents. lens is a list; lens[col] is an integer. lens.append(whatever) should do the trick. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Starships -- object of type 'int' has no len()
Hi Marc Tompkins! You are absolutely right that lens = [0] * len(catalog2[0]) Just creates a list of integers! Here is what happened, my original method of finding the maximum element sizes in the 9 x ? block of data held in catalog2, only needed a final list of integers to contain it. However, as everyone helped me make my routine more pythonic, things evolved, but we always used the same beginning formatting statement until Alan Gauld gave me, as a last example, a different way to do the same thing, but he left out, I think, a matching formatting statement, and I ASSUMED WE WERE STILL USING THE OLD ONE. You drew my eyes to it. So, I replaced the above statement with this line: lens = [[], [], [], [], [], [], [],[], []] So, trying that: lens = [[], [], [], [], [], [], [],[], []] for row in catalog2: for col, item in enumerate(row): lens[col].append(len(item)) lens = [max(col) for col in lens] print(lens) My result is: [6, 17, 5, 9, 12, 7, 0, 0, 0] THAT IS CORRECT! IT WORKS!!! But, when I try to automate the formatting of lens so that my data block can easily be changed in the originating table: lens = [[]] * len(catalog2[0]) for row in catalog2: for col, item in enumerate(row): lens[col].append(len(item)) lens = [max(col) for col in lens] print(lens) My result is: [17, 17, 17, 17, 17, 17, 17, 17, 17] THAT IS NOT CORRECT! I haven't figured out what the difference is between the two formatting statementsbut it appears to be profound! Ha! And the MAX statement that I was referring to that you couldn't see was the last line where the column lists were used to find the maximum size of each column of sizes and change lens to a single list of integers: lens = [max(col) for col in lens] --Terry IT WORKS! I just don't know how to automatically format lens with enough [] like I was able to tell On 08/20/2014 02:56 PM, Marc Tompkins wrote: On Wed, Aug 20, 2014 at 1:38 PM, Terry--gmail terry.kemme...@gmail.com wrote: Marc, my understanding is, is that: lens[col].append(len(item)) -should be building a mirror image of my list of lists called catalog2, which currently has 9 columns by x number of rows, and that we are plugging into these positions, the sizes of all the elements in that block of data. What's important is how you defined lens: lens = [0] * len(catalog2[0]) That's a list of integers, as far as I can tell without running it (I'm away from an interpreter at the moment.) So no, you cannot do lens[col].append(whatever), because - as the error message said - 'int' object has no attribute 'append'. There might be some misunderstanding about what list.append(whatever) does - it adds whatever to the end of list. It does NOT assign values to elements that already exist; to do that, you need to do assignment by index. So maybe this is what you're looking for?: lens[col] = len(item) So, I completely don't understand why we would eliminate the positioning of which list we are referencing in lens by saying: lens.append(len(item)) It seems to me that, that statement would put the entire block of element sizes into one list, and the next MAX statement would then yield only a single number, which would be the largest size element it encounted in the whole of catalog2! Or am I really missing the boat here? :) lens.append(len(item)) will append a single integer to lens. I'm afraid I don't quite follow the bit about the next MAX statement, as I've lost the thread of what your larger project is trying to accomplish... In any case, max() _should_ only return a single number, no? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Starships -- object of type 'int' has no len()
The down side of setting the python.org domain to be mailed to as plain text, appears to be that Thunderbirdy has changed all my email to plain text, instead of just the email going to this domainwhich is weird. Leam Hall: I have just one additional function to create in the User Design section where the the user designs his own starship, to complete, before I move on to the Alien Design section where the computer semi-intelligently and randomly designs the unknown Alien ship we are going to meet out in interstellar space. That will be in 1 dimensional space to start with. You can either try to run away, charge right in and try to match relative direction and speed, or sweep in and fly right past the enemy blasting away at it. As the program gets worked out, I will alter for more dimensionseventually, as I learn graphics. Right now, it is about the combat against an unknown enemy of unknown strength and capabilities. I figure it's a fun way to acquire pythonic skills and manage to remember all the commands possible. It's what I did when I first learned BASIC. So...it's going to be traditional with me... If you want, and if it doesn't violate any rules for this mailing list, I could post the User Design section for you to look over to see what my basic concepts are, just after I add and test this last section. Ultimately, I want this design section to be really easy to add additional capabilities to later and it is sort of written for the most part that way right nowalthough necessity also requires some custom filtering for different catagories of parts - like, you can only purchase one Hull for your ship! ( :) I probably wouldn't try to learn my techniques thoughmy python skills and vocabulary are a real work in progress and I read so much that I am forgetting what I have read. And I have no doubt I have probably broken pythonic rules and slaughtered proper methodology to high heaven in the layout and implementation. Ha Ha Ha) But this section does workat least until I discover a bug in some untested possible combination of choices. The way I broke it was by adding additional functions. Just let me know if you want me to post it for you to look over. DaveA: The bare 'except' was a throw away. By bare 'except' I am assuming you mean without defining the type of error 'except' is to act upon? try: something except ValueError: do something -Or does bare 'except' mean something else? Alan Guald: I have been trying out the different ways you suggested for doing this, and have ran into a problem on making the very last one work. I stuck a print statement in it to help, but I am not sure what the error statement is telling me: for row in catalog2: print(row) for col, item in row: lens[col].append(len(item)) lens = [max(col) for col in lens] and I get the following error in 'for col, item in row:' 'ValueError: too many values to unpack (expected 2)': I don't see why it would possibly say there are too many values to unpack or why it would expect only 2! Also, the list comprehension you have used on the final line reminds me that I would really like to understand comprehensions better. Is there some info on the Internet that starts very basic concerning comprehensions and explains step by step in complexity how they are structured and what the computer is doing? Just looking at the code setting there inside the list brackets and know what the output is going to be, reminds me of a programmed cell of a spreadsheetkind of. Mark Tompkins: Does (x) have Buddha-nature? In college, in a Psychology of Communications class, I spent a lot of time studying, writing about, and contemplating The Is-ness of IS! Does that count? I hand typed all of the above code in, except the error portion. This is pasted from Ninja-IDE and it comes out in smaller letters and is impossible to make larger... for row in catalog2: for col, item in row: lens[col].append(len(item)) lens = [max(col) for col in lens] Mark Lawrence gave me the idea to copy from Ninja-IDE to gedit and then copied it from gedit here: (actually I saved it in gedit and then re-grabbed it with gedit ) for row in catalog2: print(row) for col, item in row: lens[col].append(len(item)) lens = [max(col) for col in lens] Boy! It looks far better on my page than the straight Ninja-ide paste above! And it is now manipulatable, I can enlarge and shrink it...whereas, the Ninja paste resists things like trying to delete the extra lines of white space below it and I have even saw it collapse to flat right before my eyes! So, I guess the best route is to paste from Ninja to gedit and then to my emailassuming this is good on your end. On 08/19/2014 02:29 PM, Marc Tompkins wrote: On Tue, Aug 19, 2014 at 1:04 PM, Mark Lawrence breamore...@yahoo.co.uk wrote: I'm not aware of any problem with Thunderbird or any
[Tutor] Building Starships -- object of type 'int' has no len()
WOW! There is a lot of help on this mailing list! I want to thank everyone for their valuable input! Thanks! (I am working my way through the replies.) Sorry about the HTML. I think I have it turned off now in Thunderbirdy for this address. If so, then what follows should not be flat. If it is flat, please tell me. The problem portion of the program now works, as I have corrected where my strings were getting converted to integers. However, if it is OK. I'd like to discuss and ask a few questions on a few things that have been brought up. Mark: You commented on the non-Pythonic nature of my program. HA HA HA! I don't doubt it! I am coming from a BASIC background based on line numbers and GOTO and GOSUB statements, and when I read this book on Python I am sure I understood it in terms of that old BASIC. Hence, my nested FOR statements have been laid out in layers as I did it in this Python program because that is how I envisioned those statements through BASIC eyes. BUT, they might also have looked something like: 30 FORX=1TOZ:FORC=1TOE:do something here:NEXTE:NEXTZ The fact is, I am VERY interested in acquiring that 'Pythonic' view you mention and I have encountered that term bandied about on the Internet, but have come away confused as to exactly what Pythonic Thinking really is! The writers seem to take it for granted I know. I don't. After all, the way I laid the code out in my program is actually functional. So, I am really curious about the benefit of a Pythonic Way, and what it looks and reads like... Is their a Pythonic Table anywhere on the Internet, where various possible coding methods in Python are contrasted to the real Pythonic Way? -So I can examine and study the contrasted structure to understand what the Pythonic Structure is accomplishing? (Maybe I am asking the wrong question here.) I must confess that I had, when first writing the code to discover the maximum size of each column for later print to screen, searched the Internet for a python statement or an import of some kind that I could simply hand my block of data to, and have it come back with the maximum sizes of the columns. (Yes. I'm an optimist! :) ). But, I did find the below piece of code which sounded like it was doing what I wanted, so I tested it and then integrated into my program: lens = [max(map(len, col)) for col in zip(*catalog2)] It worked great! So I kept it (as a thing of utter beauty) as I was awed by it. -until I started getting that syntactic error pointing to that line. The problem is, I didn't understand the commands within the above statement (max, map, zip, and the * usage) and how they were interactively accomplishing things (the statement was utterly over my head at this juncture), and when it came to debugging, after a few embedded print statements failed to tip me off to the problem and the bug persisted, I kept suspecting the statement..so I decided to replace the above code with something that was very familiar and understandable to me (albeit, not a thing of pythonic beauty): lens = [0] * len(catalog2[0]) for line_number in range(len(catalog2)): for col in range(len(catalog2[line_number])): if lens[col] len(catalog2[line_number][col]): lens[col] = len(catalog2[line_number][col]) -And was surprised to discover the same bug persisted! The situation buffaloed me into thinking there was something about the language I was not comprehending in this section, when the actual problem, as we discovered, was elsewhere.some of the string data had been converted to integers, and thus expecting a string instead of an integer, I got the Type Error. But I am now very curious to see how this same coding would be accomplished in a Pythonic Way, so, letting the statement you gave me redefine the entire flow of thought in that area of code-- catalog2 = [ [Drives, Type, Price, Max Speed, Energy Drain, Rq-Crew, , , ], [Drives, Solar Sail, 3, 1, None, 2, , , ], [Drives, Bussard Ramjet, 10, 7, 2, 3, , , ], [Drives, Fusion, 70, 15, 5, 8, , , ], [Drives, Matter-Antimatter, 1500, 145, 15, 13, , , ], [Drives, Warp Drive, 2500, 250, 45, 17, , , ], ] We want to find the maximum size for each column-- lens = [0] * len(catalog2[0]) for line_number, row in enumerate(catalog2): for col, item in enumerate(row): if lens[col] len(item): lens[col] = len(item) print(lens) [6, 17, 5, 9, 12, 7, 0, 0, 0] -that is the correct answer. Did I do this correctly? Or, was there a way to compact it more? What have we gained? We have grabbed the entire row of data, and then looped through it without setting indexes when referring to the parts of each line...thus less clutter. Did we do this because there is less overhead generated as we sweep through the data? It is the same number of lines, BUT there is less typing in most of the lines. Do we anticipate an execution speed increase doing it this way also? Or have we altered the
Re: [Tutor] Building Starships -- object of type 'int' has no len()
I found another place in Thunderbirdy to set 'plain text'. This is a test. Does the below code look correct now? --And did I reply correctly this time? (Reply-All and keep only tutor@python.org address...) for line_number, row in enumerate(catalog2): for col, item in enumerate(row): if lens[col] len(item): lens[col] = len(item) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Starships -- object of type 'int' has no len()
I'm copy and pasting from Ninja-IDE, which I thought was created specifically to do python programming...so I never checked to see if it needs to have the tab set to enter 4 spaces, as it appeared visually to be doing that. But, I don't remember whether I used their tab or manually typed 4 spaces. SO, I have typed the lines below in manually: for line_number, row in enumerate(catalog2): for col, item in enumerate(row): if lens[col] len(item): lens[col] = len(item) How's that? --Terry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Building Starships -- object of type 'int' has no len()
Python 3.3 This has something to do with the nature of FOR statements and IF statements, and I am sure it must be a simple mistake...but I seem to be stumped. I am writing a starship encounter program as my first real python programwhere the user gets a random amount of credits to design his own ship and the computer also gets a random number of credits to spend and designs it's own ship, and then they go into combat against each other. This is part of the design phase for the user. The user has picked one category of the catalog, such as: Hulls, Drives, Shields, Weapons, Personnel, etc catalog and catalog2 are lists of lists: [[],[],[]] OK. So, my program has scanned the master catalog for a particular chosen category and has built catalog2 containing all the parts of that one category and their associated differences (rows), and now I want to print it out as a menu for the user to pick what part to add of this particular category to his ship. But first, so that I can pretty print the menu items and their associated capabilities to the screen in nice uniform columns, I need to know the maximum size of what is going to be printed in each column on the screen in advance, so I do the below learning scan through catagory2 and I build the simple list 'lens' to contain the max size of each column. As I run the program, this works perfectly for every NEW category the user picks, and the rows of associated data are printed just like I want...*UNTIL the user chooses to buy a second part from a category he has already visited*, and at that point things error out. Below is the problem code and the error: lens = [] # pre-format the list called lens for maximum number of columns contained in catalog2 lens = [0] * len(catalog2[0]) # map the largest sizes of each column into list 'lens' col, line_number = 0, 0 for line_number in range(len(catalog2)): for col in range(len(catalog2[line_number])): *if lens[col] len(catalog2[line_number][col]):* lens[col] = len(catalog2[line_number][col]) Traceback (most recent call last): File encounter.py, line 379, in module myship = designShip(credits, myship) File encounter.py, line 354, in designShip hull, myship, credits, section = nicePrint(hull, credits, myship, catalog, section) File encounter.py, line 199, in nicePrint if lens[col] len(catalog2[line_number][col]): TypeError: *object of type 'int' has no len()* I don't get it. This code does the same job, again and again successfully as I proceed to pick new categories. Why would it care if I want to go over the same ground more than once??? It seems to me that the FOR STATEMENT automatically zeros the counters 'col' and line_number' when it starts counting, but why would it suddenly choke because of going over old territory??? In trying to debug i have checked catalog2 and it's data is present and intact. I added the line 'col, line_number = 0, 0' in the sequence of events although I don't see why it would be needed, and evidently it isn't needed because the problem persists. What's left to check? I really want to buy more guns and bombs and armor! But the program seems to be on the side of gun control!!! :) Thanks for your thoughts and suggestions! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Building Starships -- object of type 'int' has no len()
Thanks for your response JL. I added the following Exception to the code snippet: for line_number in range(len(catalog2)): for col in range(len(catalog2[line_number])): try: if lens[col] len(catalog2[line_number][col]): lens[col] = len(catalog2[line_number][col]) except TypeError: print(catalog2) print(col #: , col) print(line_number, line_number) print(catalog2 col content: , catalog2[line_number][col]) print(catalog2 col content TYPE: , type(catalog2[line_number][col])) exit() Below is the exception printout. I ordered the catalog2 printout portion to be more readable: [['Drives', 'Type', 'Price', 'Max Speed', 'Energy Drain', 'Rq-Crew', '', '', ''], ['Drives', 'Solar Sail', 3, 1, 'None', 2, '', '', ''], here's the problem ['Drives', 'Bussard Ramjet', '10', '7', '2', '3', '', '', ''], ['Drives', 'Fusion', '70', '15', '5', '8', '', '', ''], ['Drives', 'Matter-Antimatter', '1500', '145', '15', '13', '', '', ''], ['Drives', 'Warp Drive', '2500', '250', '45', '17', '', '', '']] col #: 2 line_number 1 catalog2 col content: 3 catalog2 col content TYPE: class 'int' Hmmm. It appears that when I bought a Solar Sail the first time through, my code has altered my master Catalog away from holding strings to holding integers for that particular row-record, which is why when I return to a particular category to make a second purchase, the code errors out when it hits the integers that are suppose to be strings. You know, for some reason, it just never sank into my thick skull that the integer 3 doesn't have a length. I just proved that to myself on the python commandline. It's just that my eyes see the number 3 displayed on the screen and my blond brain automatically counts it as occupying 1 space in the printout and thinks it's length is 1which is why the texts say to use str() on integers and floats in mixed printouts, I guess. Thanks! I guess the above code is actually fine. Now, I just need to discover how and where I am somehow altering the master catalog where everything is suppose to be contained in strings. The problem with that is, I don't think there is any code to mess with the master catalog. I create catalog2 from scans of catalog each time another category is picked. And I store the chosen parts, after a quantity has been selected, in a list called myship. So, the problem must be where I do the quanity calculation, as that is done in integer form before the new row is added to myship. So, I will start there as I suspect I didn't switch it back to strings when I altered the catalog2 row, just before I appended it to myship. Thanks for putting me back on track! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor