This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:
http://youtu.be/6R8pZ5c82Uw
http://youtu.be/a2YtKMBfVgg
An Introduction To Python - Tables, List Algorithms
1. An Introduction To Software
Development Using Python
Spring Semester, 2014
Class #12:
Tables,
List Algorithms
2. Let’s Talk About: Tables
• It often happens that you want to store
collections of values that have a two-
dimensional tabular layout.
• Such data sets commonly occur in
financial and scientific applications.
• An arrangement consisting of rows and
columns of values is called a table, or a
matrix.
Image Credit: www.rafainspirationhomedecor.com
3. How To Create Tables
• Python does not have a data type for creating
tables.
• A two-dimensional tabular structure can be
created using Python lists.
• A table is simply a list in which each element is
itself another list
4. Accessing Elements Of A Table
• To access a particular element in the table,
you need to specify two index values in
separate brackets to select the row and
column, respectively.
medalCount = counts[3][1] = 0
5. Access All Elements In A Table
• To access all elements in a table, you use two
nested loops.
for i in range(COUNTRIES) :
# Process the i th row.
for j in range(MEDALS) :
# Process the j th column in the i th row.
print("%8d" % counts[i][j], end="")
print() # Start a new line at the end of the row.
a
6. Finding Your Neighbors In A Table
• Some programs that work with tables
need to locate the elements that are
adjacent to an element.
• You need to be careful about computing
neighbors at the boundary of the list.
• You need to check whether the element
is located at the top or bottom of the
table
b
7. Computing Row Totals
• A common task is to compute row or column totals.
• In our example, the row totals give us the total number of medals won by
a particular country.
• Finding the correct index values is a bit tricky, and it is a good idea to make
a quick sketch.
• To compute the total of row i:
c
8. Computing Column Totals
• Computing column totals is similar.
• Form the sum of counts[i][j] , where i ranges
from 0 to COUNTRIES - 1.
d
9. List Algorithms:
Maximum and Minimum
• In order to find the maximum value that is stored in a list:
largest = values[0]
for i in range(1, len(values)) :
if values[i] > largest :
largest = values[i]
Note that the loop starts at 1 because we initialize largest with values[0] .
• To compute the smallest element, reverse the comparison.
e
10. List Algorithms: Fill A List
• We want to both create and fill a list with
values at the same time.
n = 100
values = []
for i in range(n) :
values.append(0)
11. List Algorithms:
Combining List Elements
• If you want to compute the sum of a list of numbers, you can simply call
the sum function.
• But suppose you have a list of strings and want to concatenate them. Then
the sum method doesn’t work.
• Here is how to compute a sum of numbers in the list “values”:
result = ""
for element in names :
result = result + element
f
12. List Algorithms:
Element Separators
• When you display the elements of a list, you usually want to separate
them, often with commas or vertical lines, like this:
Harry, Emily, Bob
• Note that there is one fewer separator than there are numbers.
• Add the separator before each element in the sequence except the initial
one (with index 0), like this:
for i in range(len(names)) :
if i > 0 :
result = result + ", "
result = result + names[i]
g
13. List Algorithms:
Linear Search
• You often need to search for the position of a specific element in a list so that you
can replace or remove it.
• If you simply want to find the position of a value, you can use the index method:
searchedValue = 100
if searchedValue in values
pos = values.index(searchedValue)
print("Found at position:", pos)
else
print("Not found")
h
14. List Algorithms:
Linear Search
• However, if you want to find the
position of a value that has a
given property, you have to know
how the index method works.
• Consider the task of finding the
first value that is > 100. You need
to visit all elements until you
have found a match or you have
come to the end of the list.
• This algorithm is called
linear search or sequential search
because you inspect the elements
in sequence.
limit = 100
pos = 0
found = False
while pos < len(values) and not found :
if values[pos] > limit
found = True
else
pos = pos + 1
if found
print("Found at
position:", pos)
else
print("Not found")
15. List Algorithms:
Collecting and Counting Matches
• In the preceding section, you saw
how to find the position of the first
element that fulfills a particular
condition.
• Suppose we want to know all
matches. You can simply append
them to an initially empty list.
• Here, we collect all values that are >
100:
limit = 100
result = []
for element in values :
if (element > limit) :
result.append(element)
• Sometimes you just want to know
how many matches there are without
counting them.
• Then you increment a counter
instead of collecting the matches:
limit = 100
counter = 0
for element in values :
if (element > limit) :
counter = counter + 1
Image Credit: www.clipartof.com
16. List Algorithms:
Removing Matches
• A common processing task is to remove all elements that match a
particular condition.
• Suppose, for example, that we want to remove all strings of length < 4
from a list.
• Of course, you traverse the list and look for matching elements:
for i in range(len(words)) :
word = words[i]
if len(word) < 4 :
Remove the element at index i.
• But there is a subtle problem. After you remove the element, the for loop
increments i , skipping past the next element.
17. List Algorithms:
Removing Matches
• Consider this concrete example,
where words contains the strings
"Welcome", "to", "the", "island!".
• When i is 1, we remove the word "to"
at index 1.
• Then i is incremented to 2, and the
word "the", which is now at position
1, is never examined.
• We should not increment the index
when removing a word.
• Because we don’t always increment
the index, a for loop is not
appropriate for this algorithm.
Instead, use a while loop:
i = 0
while i < len(words) :
word = words[i]
if len(word) < 4 :
words.pop(i)
else :
i = i + 1
18. List Algorithms:
Swapping Elements
• You often need to swap elements of a list.
• For example, you can sort a list by
repeatedly swapping elements that are not
in order.
• Consider the task of swapping the elements
at positions i and j of a list values.
• We’d like to set values[i] to values[j] . That
overwrites the value that is currently stored
in values[i] , so we want to save that first:
temp = values[i]
values[i] = values[j]
# Now we can set values[j] to
the saved value.
values[j] = temp
19. List Algorithms:
Reading Input
• It is very common to read input from a user and store it in a
list for later processing.
• Start with an empty list and, as each value is read, append the
value to the end of the
list:
values = []
print("Please enter values, Q to quit:")
userInput = input("")
while userInput.upper() != "Q" :
values.append(float(userInput))
userInput = input("")
Image Credit: all-free-download.com
20. What We Covered Today
1. Tables
1. Creating
2. Accessing
3. Neighbors
4. Summing
2. List Algorithms
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
21. What We’ll Be Covering Next Time
1. Processing Strings
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/
Notas do Editor
New name for the class
I know what this means
Technical professionals are who get hired
This means much more than just having a narrow vertical knowledge of some subject area.
It means that you know how to produce an outcome that I value.
I’m willing to pay you to do that.