SlideShare uma empresa Scribd logo
1 de 21
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/

Mais conteúdo relacionado

Mais procurados

Mais procurados (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)
 

Destaque

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 - Python Midterm Review
An Introduction To Python - Python Midterm ReviewAn Introduction To Python - Python Midterm Review
An Introduction To Python - Python Midterm ReviewBlue Elephant Consulting
 
An Introduction To Python - Variables, Math
An Introduction To Python - Variables, MathAn Introduction To Python - Variables, Math
An Introduction To Python - Variables, MathBlue 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 MaintenanceBlue Elephant Consulting
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationBlue 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 AlternativesBlue 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 2Blue 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 DataBlue 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 DesignBlue Elephant Consulting
 

Destaque (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
 

Semelhante a 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 pythonchanna basava
 
MODULE-2.pptx
MODULE-2.pptxMODULE-2.pptx
MODULE-2.pptxASRPANDEY
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptxchin463670
 
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 structuresmidtushar
 
Acm aleppo cpc training seventh session
Acm aleppo cpc training seventh sessionAcm aleppo cpc training seventh session
Acm aleppo cpc training seventh sessionAhmad Bashar Eter
 
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 Pythonyashar Aliabasi
 
powerpoint 2-13.pptx
powerpoint 2-13.pptxpowerpoint 2-13.pptx
powerpoint 2-13.pptxJuanPicasso7
 
Arrays and linked lists
Arrays and linked listsArrays and linked lists
Arrays and linked listsAfriyieCharles
 
DATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTDATA STRUCTURES USING C -ENGGDIGEST
DATA STRUCTURES USING C -ENGGDIGESTSwapnil Mishra
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptxOut Cast
 
Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Abstract Algebra and Category Theory
Abstract Algebra and Category Theory Naveenkumar Muguda
 
11_hashtable-1.ppt. Data structure algorithm
11_hashtable-1.ppt. Data structure algorithm11_hashtable-1.ppt. Data structure algorithm
11_hashtable-1.ppt. Data structure algorithmfarhankhan89766
 

Semelhante a 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
 
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
 
11_hashtable-1.ppt. Data structure algorithm
11_hashtable-1.ppt. Data structure algorithm11_hashtable-1.ppt. Data structure algorithm
11_hashtable-1.ppt. Data structure algorithm
 

Último

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 

Último (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

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

  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.