SlideShare a Scribd company logo
An Introduction To Software
Development Using Python
Spring Semester, 2014
Class #12:
Tables,
List Algorithms
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
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
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
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
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
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
Computing Column Totals
• Computing column totals is similar.
• Form the sum of counts[i][j] , where i ranges
from 0 to COUNTRIES - 1.
d
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
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)
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
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
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
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")
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
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.
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
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
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
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/
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/

More Related Content

What's hot

Binary search
Binary searchBinary search
Binary search
sana younas
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
SoftNutx
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List Comprehensions
Yos Riady
 
Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
Trupti Agrawal
 
Radix sort
Radix sortRadix sort
Radix sort
zahraa F.Muhsen
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithms
Abdullah Al-hazmy
 
Data structure
Data structureData structure
Data structure
Nihal Singh
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
deepalishinkar1
 
List interface
List interfaceList interface
Unit 8 searching and hashing
Unit   8 searching and hashingUnit   8 searching and hashing
Unit 8 searching and hashing
Dabbal Singh Mahara
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
infanciaj
 
Radix and shell sort
Radix and shell sortRadix and shell sort
Radix and shell sort
Aaron Joaquin
 
Hashing
HashingHashing
Binary search
Binary search Binary search
Binary search Raghu nath
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
deepalishinkar1
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
Elavarasi K
 

What's hot (20)

Binary search
Binary searchBinary search
Binary search
 
Java10 Collections and Information
Java10 Collections and InformationJava10 Collections and Information
Java10 Collections and Information
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List Comprehensions
 
Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
 
Chap10
Chap10Chap10
Chap10
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Radix sort
Radix sortRadix sort
Radix sort
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithms
 
Data structure
Data structureData structure
Data structure
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
List interface
List interfaceList interface
List interface
 
Ds 8
Ds 8Ds 8
Ds 8
 
Unit 8 searching and hashing
Unit   8 searching and hashingUnit   8 searching and hashing
Unit 8 searching and hashing
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Radix and shell sort
Radix and shell sortRadix and shell sort
Radix and shell sort
 
Hashing
HashingHashing
Hashing
 
Binary search
Binary search Binary search
Binary search
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 

Viewers also liked

An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()
Blue Elephant Consulting
 
An Introduction To Python - WHILE Loop
An Introduction To  Python - WHILE LoopAn Introduction To  Python - WHILE Loop
An Introduction To Python - WHILE Loop
Blue Elephant Consulting
 
An Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm ReviewAn Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm Review
Blue Elephant Consulting
 
An Introduction To Python - Variables, Math
An Introduction To Python - Variables, MathAn Introduction To Python - Variables, Math
An Introduction To Python - Variables, Math
Blue Elephant Consulting
 
An Introduction To Python - Graphics
An Introduction To Python - GraphicsAn Introduction To Python - Graphics
An Introduction To Python - Graphics
Blue Elephant Consulting
 
An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1
Blue Elephant Consulting
 
An Introduction To Python - Dictionaries
An Introduction To Python - DictionariesAn Introduction To Python - Dictionaries
An Introduction To Python - Dictionaries
Blue Elephant Consulting
 
An Introduction To Software Development - Software Support and Maintenance
An Introduction To Software Development - Software Support and MaintenanceAn Introduction To Software Development - Software Support and Maintenance
An Introduction To Software Development - Software Support and Maintenance
Blue Elephant Consulting
 
An Introduction To Python - FOR Loop
An Introduction To Python - FOR LoopAn Introduction To Python - FOR Loop
An Introduction To Python - FOR Loop
Blue Elephant Consulting
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - Implementation
Blue Elephant Consulting
 
An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1
Blue Elephant Consulting
 
An Introduction To Python - Lists, Part 2
An Introduction To Python - Lists, Part 2An Introduction To Python - Lists, Part 2
An Introduction To Python - Lists, Part 2
Blue Elephant Consulting
 
An Introduction To Python - Nested Branches, Multiple Alternatives
An Introduction To Python - Nested Branches, Multiple AlternativesAn Introduction To Python - Nested Branches, Multiple Alternatives
An Introduction To Python - Nested Branches, Multiple Alternatives
Blue Elephant Consulting
 
An Introduction To Python - Functions, Part 2
An Introduction To Python - Functions, Part 2An Introduction To Python - Functions, Part 2
An Introduction To Python - Functions, Part 2
Blue Elephant Consulting
 
An Introduction To Python - Working With Data
An Introduction To Python - Working With DataAn Introduction To Python - Working With Data
An Introduction To Python - Working With Data
Blue Elephant Consulting
 
An Introduction To Software Development - Architecture & Detailed Design
An Introduction To Software Development - Architecture & Detailed DesignAn Introduction To Software Development - Architecture & Detailed Design
An Introduction To Software Development - Architecture & Detailed Design
Blue Elephant Consulting
 

Viewers also liked (16)

An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()
 
An Introduction To Python - WHILE Loop
An Introduction To  Python - WHILE LoopAn Introduction To  Python - WHILE Loop
An Introduction To Python - WHILE Loop
 
An Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm ReviewAn Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm Review
 
An Introduction To Python - Variables, Math
An Introduction To Python - Variables, MathAn Introduction To Python - Variables, Math
An Introduction To Python - Variables, Math
 
An Introduction To Python - Graphics
An Introduction To Python - GraphicsAn Introduction To Python - Graphics
An Introduction To Python - Graphics
 
An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1
 
An Introduction To Python - Dictionaries
An Introduction To Python - DictionariesAn Introduction To Python - Dictionaries
An Introduction To Python - Dictionaries
 
An Introduction To Software Development - Software Support and Maintenance
An Introduction To Software Development - Software Support and MaintenanceAn Introduction To Software Development - Software Support and Maintenance
An Introduction To Software Development - Software Support and Maintenance
 
An Introduction To Python - FOR Loop
An Introduction To Python - FOR LoopAn Introduction To Python - FOR Loop
An Introduction To Python - FOR Loop
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - Implementation
 
An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1
 
An Introduction To Python - Lists, Part 2
An Introduction To Python - Lists, Part 2An Introduction To Python - Lists, Part 2
An Introduction To Python - Lists, Part 2
 
An Introduction To Python - Nested Branches, Multiple Alternatives
An Introduction To Python - Nested Branches, Multiple AlternativesAn Introduction To Python - Nested Branches, Multiple Alternatives
An Introduction To Python - Nested Branches, Multiple Alternatives
 
An Introduction To Python - Functions, Part 2
An Introduction To Python - Functions, Part 2An Introduction To Python - Functions, Part 2
An Introduction To Python - Functions, Part 2
 
An Introduction To Python - Working With Data
An Introduction To Python - Working With DataAn Introduction To Python - Working With Data
An Introduction To Python - Working With Data
 
An Introduction To Software Development - Architecture & Detailed Design
An Introduction To Software Development - Architecture & Detailed DesignAn Introduction To Software Development - Architecture & Detailed Design
An Introduction To Software Development - Architecture & Detailed Design
 

Similar to An Introduction To Python - Tables, List Algorithms

List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
channa basava
 
MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptx
ASRPANDEY
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
chin463670
 
PPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structuresPPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structures
midtushar
 
Acm aleppo cpc training seventh session
Acm aleppo cpc training seventh sessionAcm aleppo cpc training seventh session
Acm aleppo cpc training seventh session
Ahmad Bashar Eter
 
Unit viii searching and hashing
Unit   viii searching and hashing Unit   viii searching and hashing
Unit viii searching and hashing
Tribhuvan University
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
MamataAnilgod
 
powerpoint 2-13.pptx
powerpoint 2-13.pptxpowerpoint 2-13.pptx
powerpoint 2-13.pptx
JuanPicasso7
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
HarsimranKaur362773
 
Intro to Lists
Intro to ListsIntro to Lists
Intro to Lists
primeteacher32
 
Complexity
ComplexityComplexity
Complexity
Malainine Zaid
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
Prof. Dr. K. Adisesha
 
Arrays and linked lists
Arrays and linked listsArrays and linked lists
Arrays and linked lists
AfriyieCharles
 
day 13.pptx
day 13.pptxday 13.pptx
day 13.pptx
codewavecommunity44
 
hashing in data strutures advanced in languae java
hashing in data strutures advanced in languae javahashing in data strutures advanced in languae java
hashing in data strutures advanced in languae java
ishasharma835109
 
DATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTDATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGEST
Swapnil Mishra
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
Out Cast
 
Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Abstract Algebra and Category Theory
Abstract Algebra and Category Theory
Naveenkumar Muguda
 

Similar to An Introduction To Python - Tables, List Algorithms (20)

List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptx
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 
PPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structuresPPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structures
 
Acm aleppo cpc training seventh session
Acm aleppo cpc training seventh sessionAcm aleppo cpc training seventh session
Acm aleppo cpc training seventh session
 
Unit viii searching and hashing
Unit   viii searching and hashing Unit   viii searching and hashing
Unit viii searching and hashing
 
Sorting
SortingSorting
Sorting
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
 
ARRAYS.pptx
ARRAYS.pptxARRAYS.pptx
ARRAYS.pptx
 
powerpoint 2-13.pptx
powerpoint 2-13.pptxpowerpoint 2-13.pptx
powerpoint 2-13.pptx
 
Arrays in C.pptx
Arrays in C.pptxArrays in C.pptx
Arrays in C.pptx
 
Intro to Lists
Intro to ListsIntro to Lists
Intro to Lists
 
Complexity
ComplexityComplexity
Complexity
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Arrays and linked lists
Arrays and linked listsArrays and linked lists
Arrays and linked lists
 
day 13.pptx
day 13.pptxday 13.pptx
day 13.pptx
 
hashing in data strutures advanced in languae java
hashing in data strutures advanced in languae javahashing in data strutures advanced in languae java
hashing in data strutures advanced in languae java
 
DATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTDATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGEST
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Abstract Algebra and Category Theory
Abstract Algebra and Category Theory
 

Recently uploaded

Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 

Recently uploaded (20)

Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 

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/

Editor's Notes

  1. 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.