Top Banner
An Introduction To Software Development Using Python Spring Semester, 2014 Class #12: Tables, List Algorithms
21
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: An Introduction To Python - Tables, List Algorithms

An Introduction To Software

Development Using Python

Spring Semester, 2014

Class #12:

Tables,

List Algorithms

Page 2: An Introduction To Python - Tables, List Algorithms

Let’s Talk About: Tables

• It often happens that you want to storecollections 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

Page 3: An Introduction To Python - Tables, List Algorithms

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

Page 4: An Introduction To Python - Tables, List Algorithms

Accessing Elements Of A Table

• To access a particular element in the table, you need to specify two index values inseparate brackets to select the row and column, respectively.

medalCount = counts[3][1] = 0

Page 5: An Introduction To Python - Tables, List Algorithms

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

Page 6: An Introduction To Python - Tables, List Algorithms

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

Page 7: An Introduction To Python - Tables, List Algorithms

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

Page 8: An Introduction To Python - Tables, List Algorithms

Computing Column Totals

• Computing column totals is similar.

• Form the sum of counts[i][j] , where i rangesfrom 0 to COUNTRIES - 1.

d

Page 9: An Introduction To Python - Tables, List Algorithms

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

Page 10: An Introduction To Python - Tables, List Algorithms

List Algorithms: Fill A List

• We want to both create and fill a list with values at the same time.

n = 100values = []for i in range(n) :

values.append(0)

Page 11: An Introduction To Python - Tables, List Algorithms

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

Page 12: An Introduction To Python - Tables, List Algorithms

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

Page 13: An Introduction To Python - Tables, List Algorithms

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 = 100if searchedValue in values

pos = values.index(searchedValue)print("Found at position:", pos)

else print("Not found")

h

Page 14: An Introduction To Python - Tables, List Algorithms

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 = 100pos = 0found = Falsewhile 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")

Page 15: An Introduction To Python - Tables, List Algorithms

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 = 100result = []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 = 100counter = 0for element in values :if (element > limit) :

counter = counter + 1

Image Credit: www.clipartof.com

Page 16: An Introduction To Python - Tables, List Algorithms

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.

Page 17: An Introduction To Python - Tables, List Algorithms

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 = 0while i < len(words) :

word = words[i]if len(word) < 4 :

words.pop(i)else :

i = i + 1

Page 18: An Introduction To Python - Tables, List Algorithms

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

Page 19: An Introduction To Python - Tables, List Algorithms

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 thelist:

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

Page 20: An Introduction To Python - Tables, List Algorithms

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/

Page 21: An Introduction To Python - Tables, List Algorithms

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/