Text stringlengths 1 9.41k |
|---|
But
don’t forget that these are right:
t.append(x)
t = t + [x]
And these are wrong:
t.append([x]) _# WRONG!_
t = t.append(x) _# WRONG!_
t + [x] _# WRONG!_
t = t + x _# WRONG!_
Try out each of these examples in interactive mode to make sure you understand what they do. |
Notice that only the last one causes a runtime error;
the other three are legal, but they do the wrong thing.
3. |
Make copies to avoid aliasing.
If you want to use a method like sort that modifies the argument, but you
need to keep the original list as well, you can make a copy.
orig = t[:]
t.sort()
-----
In this example you could also use the built-in function sorted, which returns
a new, sorted list and leaves the original ... |
But in that case you should
avoid using sorted as a variable name!
4. |
Lists, split, and files
When we read and parse files, there are many opportunities to encounter
input that can crash our program so it is a good idea to revisit the guardian
pattern when it comes writing programs that read through a file and look
for a “needle in the haystack”.
Let’s revisit our program that is looki... |
We can use continue to skip lines that
don’t have “From” as the first word as follows:
fhand = open('mbox-short.txt')
**for line in fhand:**
words = line.split()
**if words[0] != 'From' : continue**
print(words[2])
This looks much simpler and we don’t even need to do the rstrip to remove
the newline at the end of the... |
But is it better?
python search8.py
Sat
Traceback (most recent call last):
File "search8.py", line 5, in <module>
if words[0] != 'From' : continue
IndexError: list index out of range
It kind of works and we see the day from the first line (Sat), but then the
program fails with a traceback error. |
What went wrong? |
What messed-up
data caused our elegant, clever, and very Pythonic program to fail?
You could stare at it for a long time and puzzle through it or ask someone
for help, but the quicker and smarter approach is to add a print statement.
The best place to add the print statement is right before the line where the
program ... |
So we add a print of
the variable words right before line five. |
We even add a prefix “Debug:” to
the line so we can keep our regular output separate from our debug output.
**for line in fhand:**
words = line.split()
print('Debug:', words)
**if words[0] != 'From' : continue**
print(words[2])
-----
When we run the program, a lot of output scrolls off the screen but at the
end, we... |
When the program fails, the list of words is empty [].
If we open the file in a text editor and look at the file, at that point it looks
as follows:
X-DSPAM-Result: Innocent
X-DSPAM-Processed: Sat Jan 5 09:14:16 2008
X-DSPAM-Confidence: 0.8475
X-DSPAM-Probability: 0.0000
Details: http://source.sakaiproject.org/viewsv... |
Of course there
are “zero words” on a blank line. Why didn’t we think of that when we were
writing the code? |
When the code looks for the first word (word[0]) to check
to see if it matches “From”, we get an “index out of range” error.
This of course is the perfect place to add some guardian code to avoid checking the first word if the first word is not there. |
There are many ways to
protect this code; we will choose to check the number of words we have
before we look at the first word:
fhand = open('mbox-short.txt')
count = 0
**for line in fhand:**
words = line.split()
_# print 'Debug:', words_
**if len(words) == 0 : continue**
**if words[0] != 'From' : continue**
print(wor... |
Then we added
a guardian statement that checks to see if we have zero words, and if so, we
use continue to skip to the next line in the file.
We can think of the two continue statements as helping us refine the set of
lines which are “interesting” to us and which we want to process some more.
A line which has no words... |
Our
guardian statement does make sure that the words[0] will never fail, but
perhaps it is not enough. |
When we are programming, we must always be
thinking, “What might go wrong?”
Exercise 2: Figure out which line of the above program is still not properly guarded.
See if you can construct a text file which causes the program to fail and then modify
the program so that the line is properly guarded and test it to make su... |
Instead, use a compound logical expression using the and logical operator
with a single if statement.
##### 8.15 Glossary
**aliasing A circumstance where two or more variables refer to the same object.**
**delimiter A character or string used to indicate where a string should be split.**
**element One of the values... |
An object has a type and a value.**
**reference The association between a variable and its value.**
-----
##### 8.16 Exercises
[Exercise 4: Download a copy of the file from www.pythonlearn.com/code3/romeo.txt](http://www.pythonlearn.com/code3/romeo.txt)
Write a program to open the file romeo.txt and read it line ... |
For each line,
split the line into a list of words using the split function.
For each word, check to see if the word is already in a list. |
If the word is not in
the list, add it to the list.
When the program completes, sort and print the resulting words in alphabetical
order.
Enter file: romeo.txt
['Arise', 'But', 'It', 'Juliet', 'Who', 'already',
'and', 'breaks', 'east', 'envious', 'fair', 'grief',
'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft'... |
We are interested in who sent the message, which is the second word on
the From line.
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
You will parse the From line and print out the second word for each From line,
then you will also count the number of From (not From:) lines and print out a
count at the end.
... |
Write the program to store the numbers the user enters in a list
and use the max() and min() functions to compute the maximum and minimum
numbers after the loop completes.
-----
Enter a number: 6
Enter a number: 2
Enter a number: 9
Enter a number: 3
Enter a number: 5
Enter a number: done
Maximum: 9.0
Minimum: 2.0
... |
In a list, the index positions have to
be integers; in a dictionary, the indices can be (almost) any type.
You can think of a dictionary as a mapping between a set of indices (which are
called keys) and a set of values. |
Each key maps to a value. |
The association of a
key and a value is called a key-value pair or sometimes an item.
As an example, we’ll build a dictionary that maps from English to Spanish words,
so the keys and the values are all strings.
The function dict creates a new dictionary with no items. |
Because dict is the
name of a built-in function, you should avoid using it as a variable name.
>>> eng2sp = dict()
>>> print(eng2sp)
{}
The curly brackets, {}, represent an empty dictionary. |
To add items to the dictionary, you can use square brackets:
>>> eng2sp['one'] = 'uno'
This line creates an item that maps from the key ’one’ to the value “uno”. |
If we
print the dictionary again, we see a key-value pair with a colon between the key
and value:
>>> print(eng2sp)
{'one': 'uno'}
This output format is also an input format. |
For example, you can create a new
dictionary with three items. |
But if you print eng2sp, you might be surprised:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print(eng2sp)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
-----
The order of the key-value pairs is not the same. |
In fact, if you type the same
example on your computer, you might get a different result. |
In general, the order
of items in a dictionary is unpredictable.
But that’s not a problem because the elements of a dictionary are never indexed
with integer indices. |
Instead, you use the keys to look up the corresponding values:
>>> print(eng2sp['two'])
_'dos'_
The key ’two’ always maps to the value “dos” so the order of the items doesn’t
matter.
If the key isn’t in the dictionary, you get an exception:
>>> print(eng2sp['four'])
KeyError: 'four'
The len function works on dicti... |
For lists, it
uses a linear search algorithm. As the list gets longer, the search time gets longer
in direct proportion to the length of the list. |
For dictionaries, Python uses an
algorithm called a hash table that has a remarkable property: the in operator
takes about the same amount of time no matter how many items there are in a
dictionary. |
I won’t explain why hash functions are so magical, but you can read
more about it at wikipedia.org/wiki/Hash_table.
Exercise 1: [wordlist2]
Write a program that reads the words in words.txt and stores them as keys in
a dictionary. |
It doesn’t matter what the values are. |
Then you can use the in
operator as a fast way to check whether a string is in the dictionary.
-----
##### 9.1 Dictionary as a set of counters
Suppose you are given a string and you want to count how many times each letter
appears. |
There are several ways you could do it:
1. You could create 26 variables, one for each letter of the alphabet. |
Then you
could traverse the string and, for each character, increment the corresponding
counter, probably using a chained conditional.
2. You could create a list with 26 elements. |
Then you could convert each
character to a number (using the built-in function ord), use the number as
an index into the list, and increment the appropriate counter.
3. |
You could create a dictionary with characters as keys and counters as the
corresponding values. The first time you see a character, you would add
an item to the dictionary. |
After that you would increment the value of an
existing item.
Each of these options performs the same computation, but each of them implements
that computation in a different way.
An implementation is a way of performing a computation; some implementations
are better than others. |
For example, an advantage of the dictionary implementation is that we don’t have to know ahead of time which letters appear in the string
and we only have to make room for the letters that do appear.
Here is what the code might look like:
word = 'brontosaurus'
d = dict()
**for c in word:**
**if c not in d:**
d[c] = ... |
Each time through the loop, if the character c
is not in the dictionary, we create a new item with key c and the initial value 1
(since we have seen this letter once). |
If c is already in the dictionary we increment
d[c].
Here’s the output of the program:
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
The histogram indicates that the letters ’a’ and “b” appear once; “o” appears
twice, and so on.
-----
Dictionaries have a method called get that takes a key and a... |
If the
key appears in the dictionary, get returns the corresponding value; otherwise it
returns the default value. |
For example:
>>> counts = { 'chuck' : 1, 'annie' : 42, 'jan': 100}
>>> print(counts.get('jan', 0))
100
>>> print(counts.get('tim', 0))
0
We can use get to write our histogram loop more concisely. |
Because the get
method automatically handles the case where a key is not in a dictionary, we can
reduce four lines down to one and eliminate the if statement.
word = 'brontosaurus'
d = dict()
**for c in word:**
d[c] = d.get(c,0) + 1
print(d)
The use of the get method to simplify this counting loop ends up being a ve... |
So you should take a moment and compare the loop using the if statement
and in operator with the loop using the get method. |
They do exactly the same
thing, but one is more succinct.
##### 9.2 Dictionaries and files
One of the common uses of a dictionary is to count the occurrence of words in a
file with some written text. |
Let’s start with a very simple file of words taken from
the text of Romeo and Juliet.
For the first set of examples, we will use a shortened and simplified version of
the text with no punctuation. |
Later we will work with the text of the scene with
punctuation included.
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
We will write a Python program to read through the lines of the file, break ea... |
The outer loop is reading the lines of the
file and the inner loop is iterating through each of the words on that particular
line. |
This is an example of a pattern called nested loops because one of the loops
is the outer loop and the other loop is the inner loop.
-----
Because the inner loop executes all of its iterations each time the outer loop makes
a single iteration, we think of the inner loop as iterating “more quickly” and the
outer loop... |
(the romeo.txt file is available at www.pythonlearn.com/code3/romeo.txt)](http://www.pythonlearn.com/code3/romeo.txt)
python count1.py
Enter the file name: romeo.txt
{'and': 3, 'envious': 1, 'already': 1, 'fair': 1,
'is': 3, 'through': 1, 'pale': 1, 'yonder': 1,
'what': 1, 'sun': 2, 'Who': 1, 'But': 1, 'moon': 1,
'win... |
This loop prints each key and the corresponding value:
counts = { 'chuck' : 1, 'annie' : 42, 'jan': 100}
**for key in counts:**
print(key, counts[key])
-----
Here’s what the output looks like:
jan 100
chuck 1
annie 42
Again, the keys are in no particular order.
We can use this pattern to implement the various l... |
For example if we wanted to find all the entries in a dictionary
with a value above ten, we could write the following code:
counts = { 'chuck' : 1, 'annie' : 42, 'jan': 100}
**for key in counts:**
**if counts[key] > 10 :**
print(key, counts[key])
The for loop iterates through the keys of the dictionary, so we must ... |
Here’s what the output
looks like:
jan 100
annie 42
We see only the entries with a value above 10.
If you want to print the keys in alphabetical order, you first make a list of the keys
in the dictionary using the keys method available in dictionary objects, and then
sort that list and loop through the sorted list, ... |
The actual text has lots of punctuation,
as shown below.
But, soft! |
what light through yonder window breaks?
It is the east, and Juliet is the sun.
Arise, fair sun, and kill the envious moon,
Who is already sick and pale with grief,
Since the Python split function looks for spaces and treats words as tokens separated by spaces, we would treat the words “soft!” and “soft” as different ... |
The translate is the most subtle of the methods. |
Here is the
documentation for translate:
string.translate(s, table[, deletechars])
_Delete all characters from s that are in deletechars (if present), and then translate_
_the characters using table, which must be a 256-character string giving the trans-_
_lation for each character value, indexed by its ordinal. |
If table is None, then only_
_the character deletion step is performed._
We will not specify the table but we will use the deletechars parameter to delete
all of the punctuation. |
We will even let Python tell us the list of characters that
it considers “punctuation”:
>>> import string
>>> string.punctuation
_'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'_
We make the following modifications to our program:
import string
fname = input('Enter the file name: ')
**try:**
fhand = open(fname)
**except:**
... |
Otherwise the program is unchanged. |
Note that for Python 2.5 and earlier,
translate does not accept None as the first parameter so use this code instead for
the translate call:
print a.translate(string.maketrans(' ',' '), string.punctuation
Part of learning the “Art of Python” or “Thinking Pythonically” is realizing that
Python often has built-in capab... |
Here are some suggestions for debugging large datasets:
**Scale down the input If possible, reduce the size of the dataset. |
For example**
if the program reads a text file, start with just the first 10 lines, or with the
smallest example you can find. |
You can either edit the files themselves, or
(better) modify the program so it reads only the first n lines.
If there is an error, you can reduce n to the smallest value that manifests the
error, and then increase it gradually as you find and correct errors.
-----
**Check summaries and types Instead of printing and... |
For
debugging this kind of error, it is often enough to print the type of a value.
**Write self-checks Sometimes you can write code to check for errors automati-**
cally. |
For example, if you are computing the average of a list of numbers, you
could check that the result is not greater than the largest element in the list
or less than the smallest. |
This is called a “sanity check” because it detects
results that are “completely illogical”.
Another kind of check compares the results of two different
computations to see if they are consistent. |
This is called a
"consistency check".
**Pretty print the output Formatting debugging output can make it easier to**
spot an error.
Again, time you spend building scaffolding can reduce the time you spend debugging.
##### 9.6 Glossary
**dictionary A mapping from a set of keys to their corresponding values.**
**hash... |
The**
inner loop runs to completion each time the outer loop runs once.
**value An object that appears in a dictionary as the second part of a key-value**
pair. |
This is more specific than our previous use of the word “value”.
-----
##### 9.7 Exercises
**Exercise 2: Write a program that categorizes each mail message by which day of**
the week the commit was done. |
To do this look for lines that start with “From”,
then look for the third word and keep a running count of each of the days of the
week. |
At the end of the program print out the contents of your dictionary (order
does not matter).
Sample Line:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Sample Execution:
python dow.py
Enter a file name: mbox-short.txt
{'Fri': 20, 'Thu': 6, 'Sat': 1}
**Exercise 3: Write a program to read through a mail lo... |
At the end of the program, print out the contents of your dictionary.
python schoolcount.py
Enter a file name: mbox-short.txt
{'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7,
'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8}
-----
## Chapter 10
# Tuples
##### 10.1 Tuples are immutable
A tuple[1] is ... |
The values stored in a tuple can
be any type, and they are indexed by integers. The important difference is that
tuples are immutable. |
Tuples are also comparable and hashable so we can sort lists
of them and use tuples as key values in Python dictionaries.
Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is common to enclose tuples in parentheses to help
us quickly identify... |
With no argument,
it creates an empty tuple:
1Fun fact: The word “tuple” comes from the names given to sequences of numbers of varying
lengths: single, double, triple, quadruple, quituple, sextuple, septuple, etc.
-----
>>> t = tuple()
>>> print(t)
()
If the argument is a sequence (string, list, or tuple), the res... |
The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print(t[0])
_'a'_
And the slice operator selects a range of elements.
>>> print(t[1:3])
('b', 'c')
But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A'
TypeError: object doesn't support item assign... |
Python starts by
comparing the first element from each sequence. If they are equal, it goes on to the
next element, and so on, until it finds elements that differ. |
Subsequent elements
are not considered (even if they are really big).
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
-----
The sort function works the same way. |
It sorts primarily by first element, but in
the case of a tie, it sorts by second element, and so on.
This feature lends itself to a pattern called DSU for
**Decorate a sequence by building a list of tuples with one or more sort keys**
preceding the elements from the sequence,
**Sort the list of tuples using the Pyt... |
The keyword argument reverse=True tells sort to go in
decreasing order.
The second loop traverses the list of tuples and builds a list of words in descending
order of length. |
The four-character words are sorted in reverse alphabetical order,
so “what” appears before “soft” in the following list.
The output of the program is as follows:
['yonder', 'window', 'breaks', 'light', 'what',
'soft', 'but', 'in']
Of course the line loses much of its poetic impact when turned into a Python list
and... |
This allows you to assign more
than one variable at a time when the left side is a sequence.
In this example we have a two-element list (which is a sequence) and assign the first
and second elements of the sequence to the variables x and y in a single statement.
>>> m = [ 'have', 'fun' ]
>>> x, y = m
>>> x
_'have'_
>... |
For example, if you try this with a dictionary,
it will not work as might expect.
-----
Both sides of this statement are tuples, but the left side is a tuple of variables;
the right side is a tuple of expressions. |
Each value on the right side is assigned
to its respective variable on the left side. |
All the expressions on the right side are
evaluated before any of the assignments.
The number of variables on the left and the number of values on the right must be
the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
More generally, the right side can be any kind of sequence (string, list, or tuple).
... |
Converting a dictionary to a list of tuples is a way for us to
output the contents of a dictionary sorted by key:
>>> d = {'a':10, 'b':1, 'c':22}
>>> t = list(d.items())
>>> t
[('b', 1), ('a', 10), ('c', 22)]
>>> t.sort()
>>> t
[('a', 10), ('b', 1), ('c', 22)]
The new list is sorted in ascending alphabetical order ... |
The
items method would give us a list of (key, value) tuples, but this time we want
to sort by value, not key. |
Once we have constructed the list with the value-key
tuples, it is a simple matter to sort the list in reverse order and print out the new,
sorted list.
>>> d = {'a':10, 'b':1, 'c':22}
>>> l = list()
>>> for key, val in d.items() :
... |
l.append( (val, key) )
...
>>> l
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> l.sort(reverse=True)
>>> l
[(22, 'c'), (10, 'a'), (1, 'b')]
>>>
By carefully constructing the list of tuples to have the value as the first element
of each tuple, we can sort the list of tuples and get our dictionary contents sorted
by value.
--... |
But
instead of simply printing out counts and ending the program, we construct a list
of (val, key) tuples and then sort the list in reverse order.
Since the value is first, it will be used for the comparisons. |
If there is more than
one tuple with the same value, it will look at the second element (the key), so
tuples where the value is the same will be further sorted by the alphabetical order
of the key.
At the end we write a nice for loop which does a multiple assignment iteration
and prints out the ten most common words b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.