Re: [Tutor] Regex/Raw String confusion
> On Aug 3, 2016, at 20:54, Jim Byrnes wrote: > > Is the second example a special case? > > phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') > mo = phoneNumRegex.search('My phone number is: (415) 555-4242.') > print(mo.group(1)) > print() > print(mo.group(2)) > > I ask because it produces the same results with or without the ' r '. No, it’s not a special case. The backslashes in this case are a way to simplify what could otherwise be very unwieldy. There are several of these character groups (called special sequences in the documentation). For example, \s means any whitespace character, \w means any alphanumeric or underscore, \d means any digit, etc. You can look them up in the docs: https://docs.python.org/2/library/re.html — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] data storage question
> Based on both replies I got, JSON is what I will use. > > I do need the keys in the dictionary to be numerals, specifically they are > integers. > > I believe after I load a stored pt_table, I can use this script to convert > the keys back to integers. > > pt_table = dict((int(key), value) for key, value in pt_table.items()) > > Please correct me if there is something wrong with that or if there's > something else I should now about converting the keys to ints after reading > the stored data. Hi Colby, Yes, this looks ok to me. I think we can also express it as a dictionary comprehension. (https://docs.python.org/3/tutorial/datastructures.html#dictionaries) pt_table = {int(key): value for key, value in pt_table.items()} I think the dictionary comprehension approach is slightly more idiomatic, but what you've got looks ok too. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex/Raw String confusion
On 08/03/2016 06:21 PM, Alan Gauld via Tutor wrote: On 03/08/16 20:49, Jim Byrnes wrote: Regular Expressions he talks about the python escape character being a '\' and regex using alot of backslashes. In effect there are two levels of escape character, python and the regex processor. Unfortunately they both use backslash! Python applies its level of escape first then passes the modified string to the regex engine which processes the remaining regex escapes. It is confusing and one reason you should avoid complex regexes if possible. by putting an r before the first quote of the string value, you can mark the string as a raw sting, which does not escape characters. This avoids python trying to process the escapes. The raw string is then passed to the regex which will process the backslash escapes that it recognises. A couple of pages later he talks about parentheses having special meaning in regex and what to do if they are in your text. In this case, you need to escape the ( and ) characters with a backslash. The \( and \) escape characters in the raw string passed to re.compile() will match actual parenthesis characters. These are regex escape characters. If you did not have the r in front you would need to double escape them: \\( and \\) So by using the raw string you avoid the initial layer of escaping by the python interpreter and only need to worry about the regex parser - which is more than enough for anyone to worry about! Ok thanks. The book did not mention 2 levels of escaping. With what you told me in mind I reread that section and the book may have hinted at it but I would have never realized it without knowing what you just said. Is the second example a special case? phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') mo = phoneNumRegex.search('My phone number is: (415) 555-4242.') print(mo.group(1)) print() print(mo.group(2)) I ask because it produces the same results with or without the ' r '. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex/Raw String confusion
On 03/08/16 20:49, Jim Byrnes wrote: > Regular Expressions he talks about the python escape character being a > '\' and regex using alot of backslashes. In effect there are two levels of escape character, python and the regex processor. Unfortunately they both use backslash! Python applies its level of escape first then passes the modified string to the regex engine which processes the remaining regex escapes. It is confusing and one reason you should avoid complex regexes if possible. > by putting an r before the first quote of the string value, you can > mark the string as a raw sting, which does not escape characters. This avoids python trying to process the escapes. The raw string is then passed to the regex which will process the backslash escapes that it recognises. > A couple of pages later he talks about parentheses having special > meaning in regex and what to do if they are in your text. > > In this case, you need to escape the ( and ) characters with a > backslash. The \( and \) escape characters in the raw string passed to > re.compile() will match actual parenthesis characters. These are regex escape characters. If you did not have the r in front you would need to double escape them: \\( and \\) So by using the raw string you avoid the initial layer of escaping by the python interpreter and only need to worry about the regex parser - which is more than enough for anyone to worry about! -- 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@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Assignment
On 03/08/16 18:58, Justin Korn via Tutor wrote: > This is what I have so far: OK, This is starting to look a bit random. You need to slow down and work through what is happening in each method and especially what data is being passed around where. At the moment it makes no sense whatsoever. > def load_file(): > with open("warehouse_data.txt") as infile: > for line in infile: > data = process_line(line) Where is process_line defined? And what happens to data? At the moment its a local variable that disappears when load_file terminates. > class Order(): > def __init__(self, order_number): > self.order_number = order_number > > def add_item(): > order = [] > order.append() What do you think this does? It takes no input values and appends nothing(*) to a list that is deleted at the end of the function. I'm pretty certain that's not what you want. (*) In fact append will error because it needs an input value. > def sort_key(): > all_keys = [] > for item in self.order_number: > all_keys.append(item.sort_key()) > return min(all_keys) You are looping over self.order_number. What kind of data is order_number? What kind of data will item be? Does item have a sort_key() method? Also neither function has a self parameter so will not be usable methods of the class. > class LineItem(): > def __init__(self, orderNumber, partNumber, quantityNumber, aisleNumber, > shelfNumber, binNumber): > self.orderNumber = orderNumber > self.partNumber = partNumber > self.quantityNumber = quantityNumber > self.aisleNumber = aisleNumber > self.shelfNumber = shelfNumber > self.binNumber = binNumber > > def sort_key(): > p = (self.aisleNumber, self.shelfNumber, self.binNumber) > for i in p: > p.sort(i.sort_key()) > return(self.aisleNumber, self.shelfNumber * -1, self.binNumber) Look at what the loop is doing. It iterates over three values and tries to sort the tuple p based on a sort_key method of each value. But do those values have a sort_key() method?. And does sorting p achieve anything? I assume you didn't try running this code since it would result in errors. You need to sort out the data types and use them consistently. -- 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@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Assignment
To whom it may concern, I need someone to make changes to the following assignment: XYZ Corporation sells products online. The company has a large warehouse in which it stores its inventory of products. Orders are picked, packed and shipped from the warehouse. XYZ Corporation has contracted with you to write a program that will minimize the number of steps that the staff in the warehouse (called ODA's) take in picking the products ordered by customers. The information you will need to complete this assignment are in the following files: Specifications: CTIM285_Summer_2016_FinalExam.pdf Warehouse Map: WarehouseImage.pdf Data for Analysis: warehouse_data_final_exam_Python.txt Data for Analysis is saved in this order on each line of the file: [orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber] This is what I have so far: def load_file(): with open("warehouse_data.txt") as infile: for line in infile: data = process_line(line) class Order(): def __init__(self, order_number): self.order_number = order_number def add_item(): order = [] order.append() def sort_key(): all_keys = [] for item in self.order_number: all_keys.append(item.sort_key()) return min(all_keys) class LineItem(): def __init__(self, orderNumber, partNumber, quantityNumber, aisleNumber, shelfNumber, binNumber): self.orderNumber = orderNumber self.partNumber = partNumber self.quantityNumber = quantityNumber self.aisleNumber = aisleNumber self.shelfNumber = shelfNumber self.binNumber = binNumber def sort_key(): p = (self.aisleNumber, self.shelfNumber, self.binNumber) for i in p: p.sort(i.sort_key()) return(self.aisleNumber, self.shelfNumber * -1, self.binNumber) def __str__(self): return("{} {} {} {} {} {}".format(self.aisleNumber, self.shelfNumber, self.binNumber, self.orderNumber, self.partNumber, self.quantityNumber)) Thanks, Justin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Regex/Raw String confusion
I am reading Automate The Boring Stuff With Python. In the chapter on Regular Expressions he talks about the python escape character being a '\' and regex using alot of backslashes. Then he says, However, by putting an r before the first quote of the string value, you can mark the string as a raw sting, which does not escape characters. He give this example: import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phoneNumRegex.search('My number is 415-555-4242.') print('Phone number found: ' + mo.group()) A couple of pages later he talks about parentheses having special meaning in regex and what to do if they are in your text. In this case, you need to escape the ( and ) characters with a backslash. The \( and \) escape characters in the raw string passed to re.compile() will match actual parenthesis characters. import re phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') mo = phoneNumRegex.search('My phone number is: (415) 555-4242.') print(mo.group(1)) print() print(mo.group(2)) Both examples work, but one place he says you can't escape raw strings and the other he says you can. What am I missing here? Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Django SQLite data as Pie chart
On 03/08/16 12:25, Trevor H wrote: > I am trying to create a website that could dynamically get data > ... but I'm not sure about how I would go plotting the data > into a pie chart ... There are basically three ways to tackle this. 1) Create the chart as an image on the server and then upload it as a link from the HTML web page. You could include an image map to give a basic form of user interaction with the data. The image can be created using libraries such as Pillow or matplotlib or even the humble turtle. 2) Create the chart as an SVG graphic on the server and upload to the browser as part of the HTML for display. You can associate click events with Javascript functions to provide interaction. 3) Make the raw data available on the server4 and get a Javascript function in the HTML to fetch it as needed and generate the imagery directly in the browsers DOM. (I believe there are JS libraries to assist in this but I've never used them) They are arranged in order of simplicity. They are also arranged in reverse order from the point of flexibility and user interaction. As ever, it's a trade off. -- 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@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Django SQLite data as Pie chart
Hi all, I am trying to create a website that could dynamically get data from an SQLite3 database and create it into a website. I know how to install Django, tell it to use an existing database (in setting.py) but I'm not sure about how I would go plotting the data into a pie chart from here on? The values under the tables get populated with a PHP script that gets the information needed to analyse. Example of the tables is as follows: Name: Oses Sqlite3: create table oses (id integer primary key, name text) Hope someone would be able to shine some light on this for me. Thanks TJ Sent from my iPhone ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] data storage question
> Date: Tue, 2 Aug 2016 12:14:04 +1000 > From: st...@pearwood.info > To: tutor@python.org > Subject: Re: [Tutor] data storage question > > On Mon, Aug 01, 2016 at 04:47:32PM -0400, Colby Christensen wrote: > >> I'm a novice programmer. I have a decent understanding of algorithms >> but I don't have a lot of computer science/software engineering >> experience. As a way to help me learn, I've begun a coordinate >> geometry program similar to the COGO program developed years ago at >> MIT. Currently, I store the points in a dictionary in the format >> point_number : [North, East]. I eventually will add a Z component to >> the points and possibly a description after I get enough of the >> horizontal geometry worked through. I would like to be able to save >> the point table so that I can have multiple projects. > > For external storage, you have lots of options. Two very common or > popular suitable standards are JSON or PList. > > Suppose you have a point table: > > pt_table = {25: [30.1, 42.5, 2.8, 'The Shire'], > 37: [17.2, 67.2, 11.6, 'Mt Doom'], > 84: [124.0, 93.8, 65.2, 'Rivendell'], > } > > I can save that table out to a JSON file, then read it back in, like > this: > > py> import json > py> with open('/tmp/data.json', 'w') as f: # save to table to disk > ... json.dump(pt_table, f) > ... > py> with open('/tmp/data.json', 'r') as f: # read it back in > ... new_table = json.load(f) > ... > py> print new_table > {u'25': [30.1, 42.5, 2.8, u'The Shire'], u'37': [17.2, 67.2, 11.6, u'Mt > Doom'], u'84': [124.0, 93.8, 65.2, u'Rivendell']} > > > You'll see that the JSON format has made two changes to the point table: > > (1) All strings are Unicode strings instead of "byte strings" (sometimes > called "ASCII strings"). > > (2) The keys were numbers (25, 37, 84) but have now been turned into > Unicode strings too. Based on both replies I got, JSON is what I will use. I do need the keys in the dictionary to be numerals, specifically they are integers. I believe after I load a stored pt_table, I can use this script to convert the keys back to integers. pt_table = dict((int(key), value) for key, value in pt_table.items()) Please correct me if there is something wrong with that or if there's something else I should now about converting the keys to ints after reading the stored data. Thanks for your input! > > We can advise you how to deal with these changes. Nevertheless, JSON is > probably the most common standard used today, and you can see how easy > the writing and reading of the data is. > > Here is an alternative: Plists. Like JSON, Plist requires the keys to be > strings, but unlike JSON, it won't convert them for you. So you have to > use strings in the first place, or write a quick converter: > > py> pt_table = dict((str(key), value) for key, value in > pt_table.items()) > py> print pt_table > {'25': [30.1, 42.5, 2.8, 'The Shire'], '37': [17.2, 67.2, 11.6, 'Mt > Doom'], '84': [124.0, 93.8, 65.2, 'Rivendell']} > > > Notice that now the keys (which were numbers) are now strings. Now we > can write to a plist, and read it back: > > py> plistlib.writePlist(pt_table, '/tmp/data.plist') > py> new_table = plistlib.readPlist('/tmp/data.plist') > py> new_table == pt_table > True > > > Again, if you need to work with numeric keys, there are ways to work > around that. > > If anything is unclear, please feel free to ask questions on the mailing > list, and somebody will try to answer them. > > > -- > Steve > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Assignment
On 03/08/16 06:34, Justin Korn via Tutor wrote: > Data for Analysis is saved in this order on each line of the file: > [orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber] > > > This is what I have so far: > > infile = open("warehouse_data.txt", "r") > > class Order(): > def __init__(self, order_number, line_items): > self.order_number = order_number > line_items = line_items You use self for the order_number but not for the line_items? Also, are you really planning on building a collection of line items per order before you create the order? Or might it be better to create the order for the first identified line item and then add() subsequent line items as you find them? Just a thought... > class LineItem(): > def __init__(self, orderNumber, partNumber, quantityNumber, aisleNumber, > shelfNumber, binNumber): > self.orderNumber = orderNumber > self.partNumber = partNumber > self.quantityNumber = quantityNumber > self.aisleNumber = aisleNumber > self.shelfNumber = shelfNumber > binNumber = binNumber And similarly you do not use self for bin_number In each case the values without self will be thrown away when the __init__() method exits. Other than that issue it's a fair start in that you now have two classes that can be used to store the data in the file. Your next step is presumably to read the file into objects of these classes. Finally, I'm guessing you'll want to sort the line items into groups based on their location so that the warehouse pickers don't need to visit the same area twice. I'm not clear whether that should be limited per order or to all the line items per batch and the collected items assembled into orders later. I'm assuming that the items are picked by order... but the assignment doesn't seem to specify. -- 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@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Assignment
To whom it may concern, I need help creating a program for the following assignment: XYZ Corporation sells products online. The company has a large warehouse in which it stores its inventory of products. Orders are picked, packed and shipped from the warehouse. XYZ Corporation has contracted with you to write a program that will minimize the number of steps that the staff in the warehouse (called ODA's) take in picking the products ordered by customers. The information you will need to complete this assignment are in the following files: Specifications: CTIM285_Summer_2016_FinalExam.pdf Warehouse Map: WarehouseImage.pdf Data for Analysis: warehouse_data_final_exam_Python.txt Data for Analysis is saved in this order on each line of the file: [orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber] This is what I have so far: infile = open("warehouse_data.txt", "r") class Order(): def __init__(self, order_number, line_items): self.order_number = order_number line_items = line_items class LineItem(): def __init__(self, orderNumber, partNumber, quantityNumber, aisleNumber, shelfNumber, binNumber): self.orderNumber = orderNumber self.partNumber = partNumber self.quantityNumber = quantityNumber self.aisleNumber = aisleNumber self.shelfNumber = shelfNumber binNumber = binNumber Thanks, Justin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variables
>I'm trying to write a program w/ python that runs once a day and every time it >does it adds 20 to a variable. How do I do this so it doesn't reset the >variable to the original value every time I run it? You can output the value to a file? Then re-read the file once a day and assign that value to the variable. This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problem with code interating thri a list
Chris Clifton via Tutor wrote: > I have been practicing with strings. Splitting them, joining them, > changing case. All has been going well but came across a exercise in one > of the code practice sites that has you changing the case of different > characters in a string. Anything in upper case is converted to lower case > and anything in lower case is converted to upper. The solution I have > created seems to work but I have not been able to figure out how to join > the string back together. String I'm using is "This Is A Test!" to be > changed to "tHIS iS a tEST!". You'll learn more if you try to understand the approaches shown in Danny's and Alan's posts, but there is also a ready-to-use string method: >>> "This Is A Test!".swapcase() 'tHIS iS a tEST!' I have no idea where you'd need such a method other than to "cheat" in exercises like the one you saw... There is also a method to make arbitrary replacements that is much more useful for solving real-world problems: >>> replacements = str.maketrans({"Ü": "Ue", "ü": "ue"}) >>> "Übel wütet der Gürtelwürger!".translate(replacements) 'Uebel wuetet der Guertelwuerger!' >>> import string >>> swap = str.maketrans(string.ascii_uppercase + string.ascii_lowercase, string.ascii_lowercase + string.ascii_uppercase) >>> "This Is A Test!".translate(swap) 'tHIS iS a tEST!' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor