480 likes | 556 Views
Welcome to the 12,756th meeting of CC Lab 2007!. This week we will push ahead with Python. We will get a little more in depth with lists, text handling (strings), and files. Things get serious.
E N D
This week we will push ahead with Python. We will get a little more in depth with lists, text handling (strings), and files.Things get serious.
This will involve searching and sorting, and text manipulation. These are basic building blocks of programming.Many algorithms use some form of searching and/or sorting to solve problems.
This will be a hands on session. As we work through examples, a good idea is to pair up and discuss results (in front of the terminal).(Especially if you don’t have a laptop.)
You’ll have homework assignments the next few weeks. These need to be handed in or demonstrated in class. They will be graded.
It is very important that you get used to typing these things in via the terminal. Get comfortable interacting with Python. You’ll learn more.
This said, you will get sick of typing lines into the terminal, so start using and executing Python files (*.py). It is much faster to test your code that way.
Also, sometimes if you cut and paste from the PPT (this presentation), the text will give you errors. This is due to devious invisible characters.
Finally, Sven (who wrote this presentation) makes mistakes. If you find a mistake, tell him-- he will blast it to everyone.He tested everything here, but he was half asleep at the time.
Please open up two pdf docs on the CC Lab site:“Dive Into Python” (by Mark Pilgrim)“How to Think Like a (Python) Programmer” (by Allen Downey)
Specifically, for more on today’s lessons, please read chapters 8, 9, and 10 from the Downey (“Strings”, “Case study: word play”, and “Lists”)
Lists in Python are the equivalent of arrays in other programming languages. Lists are a 'workhorse ' variable type in Python (meaning you can use them for practically anything).
Let’s start by reviewing defining and accessing lists (from the command line):>>> list1 = [‘1’, 'QQQ', 'freggle', 'z', 'woubie'] >>> list1[’1', ’QQQ', ’freggle', 'z', ’woubie'] >>> list1[0] ’1' >>> list1[4] ’woubie'(Remember, the first element in a list is number '0'.)
Your can access elements in lists using negative numbers:>>> list1 = [‘1’, 'QQQ', 'freggle', 'z ', 'woubie'] >>> list1[’1', ’QQQ', ’freggle', 'z', ’woubie'] >>> list1[-1] ’woubie' >>> list1[-4] ’QQQ'What would>>>list1[-9] give you?
You have to get used to providing for errors in your program (user input, programmer’s mistakes, whatever).What happens to your program when something unexpected happens?
Adding and deleting elements to/from lists can happen in several ways:>>> list1.append('foo')>>> list1.insert(3,'bar')>>> list1.extend(['baz','bop'])>>> list1.remove('bop')Now, open Python and work through creating and accessing lists, and figure out how each of the above commands work…
You can search from a list using:>>> list1.index('z')>>> 'z' in list1 “index” returns the first occurrence of an item in a list, or an error if it isn’t there. “in” returns a true or false.
You can “slice” (create a subset of) a list using:>>> list1[1:4]>>> list1[-3:2] There is a shorthand for slicing: >>> list1[:4]>>> list1[-3:] Mess around with these commands.
You can use operators on a list (+,-,*).Now, create two lists (of five elements each), and try the following:>>> list1 + list2>>> list1[2:4] * 3>>> list2 += [‘newelement’] Print out the results.Fool around with the lists for long enough to understand how to manipulate them using operators.
You can sort a list using:>>> list1.sort()>>> print list1Note that the sorting happens “inline”. Once a list is sorted, it stays sorted, so be careful with that!
A string is a sequence of characters. You can access the characters one at a time with the bracket operator: >>> cooldude = ‘sven’>>> letter = cooldude[2]>>> letter‘e’
“len” is a built-in function that returns the number of characters in a string:>>> bitterman = len(cooldude) >>> cooldude[bitterman - 1]‘n’
A lot of computations involve processing a string one character at a time. Often they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal.
One way to write a traversal is with a “while” statement:count = 0 while count < len(cooldude): output = cooldude[count] print output count = count + 1
Note a basic difference between the way lists are created, and the way strings are created:List:>>> list1 = ['1', 'QQQ', 'freggle', 'z ', 'woubie']String:>>> cooldude = 'sven'
This difference is important. You can change lists, but strings are “immutable” (they create new copies of themselves when you operate on them).
String “methods”: These are different string functions built into Python. There are a lot of them. We’ll start today with just a few (lower, upper, split, index, replace, count)
String comparison The comparison operators work on strings. To see if two strings are equal:>>> if word == ‘flimsy’: print ‘We are out of gas!’or>>> if word1[i] != word2[j]: print ‘You fool, log out now!’
String comparison (cont.) You can also use comparison operators to check alphabetical order: if word < 'banana': print 'Your word, ' + word + ', comes before banana.' elif word > 'banana': print 'Your word, ' + word + ', comes after banana.' else: print 'Yes, we have no bananas!'(example from ThinkPP, page 86)
One thing to remember:In Python, all uppercase letters come before lowercase. So convert everything to lowercase before doing comparisons >>> word_original = ‘FLAMBOYANT’>>> word_new = word_original.lower() >>> print new_word flamboyant
You’ll find the text for William Shakespeare’s 27th sonnet on the CC Lab site (“WS_27.txt”).This is a plain text file with line breaks. Download it and use it to fool around in the following exercises. You’ll need to make sure it’s in the local directory you are working in.
Obviously users aren’t going to enter large amounts of text at the command line.We need to be able to read from files. In Python, we can use:>>> file_in = open(‘WS_27.txt’)This creates a “file object” for us, which we can manipulate to our heart’s content (“file_in” is just a variable name).
Try this out, using the Shakespeare, and add a command to read one line:>>> file_in = open(‘WS_27.txt’)>>> file_in.readline()‘Weary with toil, I haste me to my bed,\r\n’The sequence “\r\n” represents two whitespace characters, a carriage return and a newline, that separate this word from the next.
We can get rid of these characters by using the string method‘strip’>>> file_in = open(‘WS_27.txt’)>>> ourline = file_in.readline()>>> ourline_stripped = ourline.strip()>>> print ourline_strippedWeary with toil, I haste me to my bed,The file object keeps track of where it is in the file, so if you call readline again, you get the next line.
Let’s try a couple of other string methods:>>> file_in = open(‘WS_27.txt’)>>> ourline = file_in.readline()>>> ourline_changed = ourline.replace(‘toil’,’spoil’)>>> ourline = ourline_changed.replace('haste me to','have lost')>>> print ourlineWeary with spoil, I have lost my bed,Next try:>>> ourline.index(‘Weary’) What do you get? Why?
Here's another string method to try: >>> ourline.split(' ') What do you get? Why?
Up ‘til now, we have simply opened a file to read it. Sometimes we will need to create and write to a new file:>>> file_to_write = open(’newfile.txt',"w")>>> file_to_write.writelines("Slim pickings are the mode!")>>> file_to_write.close()Don’t do this to an existing file; you will erase it! If you want to work with an existing file, use: >>> file_to_edit = open(’filename.txt',”a")
Now take the file you just created, open it and add another line. Then save it:>>> file_to_append = open(’newfile.txt',"a")>>> file_to_append.writelines(“Double trouble is the bubble!")>>> file_to_append.close()
It will take some getting used to these various Python string and file manipulation methods. This has just been an introduction.
Your homework for this week is in a PDF file on the CC Lab site. It consists of four problems. You should hand your code into your instructor in paper form, and also be prepared to demonstrate (run) your solutions to the problems. The homework is due next week.Now let’s go over the homework…
The homework problems may seem a bit ridiculous. The intent is to get you used to writing to and from files, checking for errors, and manipulating, searching, and sorting text with ease.It will take some time and patience.
Homework Problem #1:Write a program that asks the user for a sentence of text input of at least four words. Make sure the user enters at least four words. Provide feedback if they don’t.Output the number of characters and number of words in the sentence the user enters, then print the sentence out backwards, and call the user a fool. Exit the program.
Homework Problem #2: Write a program that opens Shakespeare’s sonnet #27, puts all of the words in alphabetical order, and prints out the results to the screen, one word per line. Save the results to a new file. Check for the existence of the file before saving-- if it exists, append appropriate text to the filename.
Homework Problem #3: Write a program that opens Shakespeare’s sonnet #27 and does the following:Upon each occurrence of the word “my”, add in parentheses the number of the occurrence. After the last line of the sonnet, add a line stating:“There were x occurrences of the word “my” in this sonnet, far too many!” (where x is a number)Save the resulting text under a new file name, checking as in problem #2 for the existence of the file and renaming as appropriate.
Homework Problem #4:Write a program that asks the user to write a number (in text), one through nine. Depending on what the user enters, respond with additional instructions (unique for each number). The additional instructions should request that the user type in a specific three word phrase (different for each number).Check all user entries for correctness, and provide feedback upon user errors. Exit the program after the user succeeds.