SlideShare a Scribd company logo
Algorithm Design
Lecture 8
Announcements For This Lecture
Assignment 1
• Due TOMORROW
§ Due before midnight
§ Submit something…
§ Last revision Sep. 23
• Grades posted Sunday
• Complete the Survey
§ Must answer individually
Getting Help
• Can work on it in lab
§ But still have a new lab
§ Make sure you do both
• Consulting Hours
§ But expect it to be busy
§ First-come, first-served
• One-on-Ones still going
§ Lots of spaces available
2
9/15/22 Algorithm Design
Announcements For This Lecture
Assignment 1
• Due TOMORROW
§ Due before midnight
§ Submit something…
§ Last revision Sep. 23
• Grades posted Sunday
• Complete the Survey
§ Must answer individually
Getting Help
• Can work on it in lab
§ But still have a new lab
§ Make sure you do both
• Consulting Hours
§ But expect it to be busy
§ First-come, first-served
• One-on-Ones still going
§ Lots of spaces available
3
9/15/22 Algorithm Design
Will post Assignment 2 Friday.
This is a handwritten assignment.
What Are Algorithms?
Algorithm
• Step-by-step instructions
§ Not specific to a language
§ Could be a cooking recipe
• Outline for a program
Implementation
• Program for an algorithm
§ In a specific language
§ What we often call coding
• The filled in outline
9/15/22 Algorithm Design 4
• Good programmers can separate the two
§ Work on the algorithm first
§ Implement in language second
• Why approach strings as search-cut-glue
Difficulties With Programming
Syntax Errors
• Python can’t understand you
• Examples:
§ Forgetting a colon
§ Not closing a parens
• Common with beginners
§ But can quickly train out
Conceptual Errors
• Does what you say, not mean
• Examples:
§ Forgot last char in slice
§ Used the wrong argument
• Happens to everyone
§ Large part of CS training
Proper algorithm design
reduces conceptual errors
9/15/22 Algorithm Design 5
Testing First Strategy
• Write the Tests First
Could be script or written by hand
• Take Small Steps
Do a little at a time; make use of placeholders
• Intersperse Programming and Testing
When you finish a step, test it immediately
• Separate Concerns
Do not move to a new step until current is done
9/15/22 Algorithm Design 6
Testing First Strategy
• Write the Tests First
Could be script or written by hand
• Take Small Steps
Do a little at a time; make use of placeholders
• Intersperse Programming and Testing
When you finish a step, test it immediately
• Separate Concerns
Do not move to a new step until current is done
Will see several strategies.
But all built on this core idea.
9/15/22 Algorithm Design 7
Using Placeholders in Design
• Strategy: fill in definition a little at a time
• We start with a function stub
§ Function that can be called but is unfinished
§ Allows us to test while still working (later)
• All stubs must have a function header
§ But the definition body might be “empty”
§ Certainly is when you get started
9/15/22 Algorithm Design 8
A Function Stub
def last_name_first(s):
"""Returns: copy of s in form 'last-name, 'first-name'
Precondition: s is in form 'first-name last-name'
with one blank between the two names"""
# Finish the body
“Empty”
9/15/22 Algorithm Design 9
But it Cannot Really Be Empty
def last_name_first(s):
# Finish the body
• A function definition is only valid with a body
§ (Single-line) comments do not count as body
§ But doc-strings do count (part of help function)
• So you should always write in the specification
Error
9/15/22 Algorithm Design 10
An Alternative: Pass
def last_name_first(s):
pass
• You can make the body non-empty with pass
§ It is a command to “do nothing”
§ Only purpose is to ensure there is a body
• You would remove it once you got started
Fine!
9/15/22 Algorithm Design 11
Ideally: Use Both
def last_name_first(s):
"""Returns: copy of s in form 'last-name, 'first-name'
Precondition: s is in form 'first-name last-name'
with one blank between the two names"""
pass
Now pass is a note that is unfinished.
Can leave it there until work is done.
9/15/22 Algorithm Design 12
Outlining Your Approach
• Recall the two types of errors you will have
§ Syntax Errors: Python can’t understand you
§ Conceptual Errors: Does what you say, not mean
• To remove conceptual errors, plan before code
§ Create outline of the steps to carry out
§ Write in this outline as comments
• This outline is called pseudocode
§ English statements of what to do
§ But corresponds to something simple in Python
9/15/22 Algorithm Design 13
Example: Reordering a String
def last_name_first(s):
"""Returns: copy of s in form 'last-name, 'first-name'
Precondition: s is in form 'first-name last-name'
with one blank between the two names"""
# Find the space between the two names
# Cut out the first name
# Cut out the last name
# Glue them together with a comma
9/15/22 Algorithm Design 14
Example: Reordering a String
def last_name_first(s):
"""Returns: copy of s in form 'last-name, 'first-name'
Precondition: s is in form 'first-name last-name'
with one blank between the two names"""
end_first = s.find(' ')
# Cut out the first name
# Cut out the last name
# Glue them together with a comma
9/15/22 Algorithm Design 15
Example: Reordering a String
def last_name_first(s):
"""Returns: copy of s in form 'last-name, 'first-name'
Precondition: s is in form 'first-name last-name'
with one blank between the two names"""
end_first = s.find(' ')
first_name = s[:end_first]
# Cut out the last name
# Glue them together with a comma
9/15/22 Algorithm Design 16
What is the Challenge?
• Pseudocode must correspond to Python
§ Preferably implementable in one line
§ Unhelpful: # Return the correct answer
• So what can we do?
§ Depends on the types involved
§ Different types have different operations
§ You should memorize important operations
§ Use these as building blocks
9/15/22 Algorithm Design 17
Case Study: Strings
• We can slice strings (s[a:b])
• We can glue together strings (+)
• We have a lot of string methods
§ We can search for characters
§ We can count the number of characters
§ We can pad strings
§ We can strip padding
• Sometimes, we can cast to a new type
9/15/22 Algorithm Design 18
Early Testing
• Recall: Combine programming & testing
§ After each step we should test
§ But it is unfinished; answer is incorrect!
• Goal: ensure intermediate results expected
§ Take an input from your testing plan
§ Call the function on that input
§ Look at the results at each step
§ Make sure they are what you expect
• Add a temporary return value
9/15/22 Algorithm Design 19
Stubbed Returns
def last_name_first(s):
"""Returns: copy of s in form 'last-name, 'first-name'
Precondition: s is in form 'first-name last-name'
with one blank between the two names"""
end_first = s.find(' ')
first = s[:end_first]
# Cut out the last name
# Glue them together with a comma
return first # Not the final answer
9/15/22 Algorithm Design 20
Working with Helpers
• Suppose you are unsure of a step
§ You maybe have an idea for pseudocode
§ But not sure if it easily converts to Python
• But you can specify what you want
§ Specification means a new function!
§ Create a specification stub for that function
§ Put a call to it in the original function
• Now can lazily implement that function
9/15/22 Algorithm Design 21
Example: last_name_first
def last_name_first(s):
"""Returns: copy of s in the form
'last-name, first-name'
Precondition: s is in the form
'first-name last-name' with
with one blank between names"""
# Cut out the first name
# Cut out the last name
# Glue together with comma
# Return the result
9/15/22 Algorithm Design 22
Example: last_name_first
def last_name_first(s):
"""Returns: copy of s in the form
'last-name, first-name'
Precondition: s is in the form
'first-name last-name' with
with one blank between names""”
first = first_name(s)
# Cut out the last name
# Glue together with comma
return first # Stub
def first_name(s):
"""Returns: first name in s
Precondition: s is in the form
'first-name last-name' with
one blank between names"""
pass
9/15/22 Algorithm Design 23
Example: last_name_first
def last_name_first(s):
"""Returns: copy of s in the form
'last-name, first-name'
Precondition: s is in the form
'first-name last-name' with
with one blank between names""”
first = first_name(s)
# Cut out the last name
# Glue together with comma
return first # Stub
def first_name(s):
"""Returns: first name in s
Precondition: s is in the form
'first-name last-name' with
one blank between names"""
end = s.find(' ')
return s[:end]
9/15/22 Algorithm Design 24
Concept of Top Down Design
• Function specification is given to you
§ This cannot change at all
§ Otherwise, you break the team
• But you break it up into little problems
§ Each naturally its own function
§ YOU design the specification for each
§ Implement and test each one
• Complete before the main function
9/15/22 Algorithm Design 25
Testing and Top Down Design
def test_first_name():
"""Test procedure for first_name(n)"""
result = name.first_name('Walker White')
introcs.assert_equals('Walker', result)
def test_last_name_first():
"""Test procedure for last_name_first(n)"""
result = name.last_name_first('Walker White')
introcs.assert_equals('White, Walker', result)
9/15/22 Algorithm Design 26
A Word of Warning
• Do not go overboard with this technique
§ Do not want a lot of one line functions
§ Can make code harder to read in extreme
• Do it if the code is too long
§ I personally have a one page rule
§ If more than that, turn part into a function
• Do it if you are repeating yourself a lot
§ If you see the same code over and over
§ Replace that code with a single function call
9/15/22 Algorithm Design 27
Exercise: Anglicizing an Integer
• anglicize(1) is “one”
• anglicize(15) is “fifteen”
• anglicize(123) is “one hundred twenty three”
• anglicize(10570) is “ten thousand five hundred
def anglicize(n):
"""Returns: the anglicization of int n.
Precondition: 0 < n < 1,000,000"""
pass # ???
9/15/22 Algorithm Design 28
Exercise: Anglicizing an Integer
def anglicize(n):
"""Returns: the anglicization of int n.
Precondition: 0 < n < 1,000,000"""
# if < 1000, provide an answer
# if > 1000, break into hundreds, thousands parts
# use the < 1000 answer for each part , and glue
# together with "thousands" in between
# return the result
9/15/22 Algorithm Design 29
Exercise: Anglicizing an Integer
def anglicize(n):
"""Returns: the anglicization of int n.
Precondition: 0 < n < 1,000,000"""
if n < 1000: # no thousands place
return anglicize1000(n)
elif n % 1000 == 0: # no hundreds, only thousands
return anglicize1000(n/1000) + ' thousand'
else: # mix the two
return (anglicize1000(n/1000) + ' thousand '+
anglicize1000(n))
9/15/22 Algorithm Design 30
Exercise: Anglicizing an Integer
def anglicize(n):
"""Returns: the anglicization of int n.
Precondition: 0 < n < 1,000,000"""
if n < 1000: # no thousands place
return anglicize1000(n)
elif n % 1000 == 0: # no hundreds, only thousands
return anglicize1000(n/1000) + ' thousand'
else: # mix the two
return (anglicize1000(n/1000) + ' thousand '+
anglicize1000(n))
9/15/22 Algorithm Design 31
Now implement this.
See anglicize.py

More Related Content

Similar to Python Lecture slides topic Algorithm design (20)

Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Chp-1 DAA (2).pptx design analysis and algoritham presentation
Chp-1 DAA (2).pptx design analysis and algoritham presentationChp-1 DAA (2).pptx design analysis and algoritham presentation
Chp-1 DAA (2).pptx design analysis and algoritham presentation
vaishnavbhavna17
 
UNIT-1.pptx python for engineering first year students
UNIT-1.pptx python for engineering first year studentsUNIT-1.pptx python for engineering first year students
UNIT-1.pptx python for engineering first year students
SabarigiriVason
 
l01-intro (3).ppt
l01-intro (3).pptl01-intro (3).ppt
l01-intro (3).ppt
ssuser15a62a
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
Sachin Goyani
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.ppt
SourabhPal46
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.ppt
Mard Geer
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.ppt
SamridhiGulati4
 
Introduction to Design Algorithm And Analysis.ppt
Introduction to Design Algorithm And Analysis.pptIntroduction to Design Algorithm And Analysis.ppt
Introduction to Design Algorithm And Analysis.ppt
BhargaviDalal4
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.ppt
racha49
 
UNIT-1-PPTS-DAA INTRO WITH DIVIDE AND CONQUER
UNIT-1-PPTS-DAA INTRO WITH DIVIDE AND CONQUERUNIT-1-PPTS-DAA INTRO WITH DIVIDE AND CONQUER
UNIT-1-PPTS-DAA INTRO WITH DIVIDE AND CONQUER
Salini P
 
UNIT 1- Design Analysis of algorithms and its working
UNIT 1- Design Analysis of algorithms and its workingUNIT 1- Design Analysis of algorithms and its working
UNIT 1- Design Analysis of algorithms and its working
Bobby Pra A
 
Design and analysis of algorithms Module-I.pptx
Design and analysis of algorithms Module-I.pptxDesign and analysis of algorithms Module-I.pptx
Design and analysis of algorithms Module-I.pptx
DhanushreeAN1
 
GLOBAL INSTITUTE OF MANAGEMENT AND TECHNOLOGY.pptx
GLOBAL INSTITUTE OF MANAGEMENT AND TECHNOLOGY.pptxGLOBAL INSTITUTE OF MANAGEMENT AND TECHNOLOGY.pptx
GLOBAL INSTITUTE OF MANAGEMENT AND TECHNOLOGY.pptx
hemantag1989
 
Unit 1.pptx
Unit 1.pptxUnit 1.pptx
Unit 1.pptx
DeepakYadav656387
 
Chapter-1-Introduction-to-Aglorithms.pdf
Chapter-1-Introduction-to-Aglorithms.pdfChapter-1-Introduction-to-Aglorithms.pdf
Chapter-1-Introduction-to-Aglorithms.pdf
Shanmuganathan C
 
What is algorithm
What is algorithmWhat is algorithm
What is algorithm
lilyMalar1
 
01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx
ssuser586772
 
s-INTRODUCTION TO PROBLEM SOLVING PPT.pptx
s-INTRODUCTION TO PROBLEM SOLVING PPT.pptxs-INTRODUCTION TO PROBLEM SOLVING PPT.pptx
s-INTRODUCTION TO PROBLEM SOLVING PPT.pptx
ShamithRai
 
Problem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialProblem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study material
To Sum It Up
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Chp-1 DAA (2).pptx design analysis and algoritham presentation
Chp-1 DAA (2).pptx design analysis and algoritham presentationChp-1 DAA (2).pptx design analysis and algoritham presentation
Chp-1 DAA (2).pptx design analysis and algoritham presentation
vaishnavbhavna17
 
UNIT-1.pptx python for engineering first year students
UNIT-1.pptx python for engineering first year studentsUNIT-1.pptx python for engineering first year students
UNIT-1.pptx python for engineering first year students
SabarigiriVason
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
Sachin Goyani
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.ppt
SourabhPal46
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.ppt
Mard Geer
 
Introduction to Design Algorithm And Analysis.ppt
Introduction to Design Algorithm And Analysis.pptIntroduction to Design Algorithm And Analysis.ppt
Introduction to Design Algorithm And Analysis.ppt
BhargaviDalal4
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.ppt
racha49
 
UNIT-1-PPTS-DAA INTRO WITH DIVIDE AND CONQUER
UNIT-1-PPTS-DAA INTRO WITH DIVIDE AND CONQUERUNIT-1-PPTS-DAA INTRO WITH DIVIDE AND CONQUER
UNIT-1-PPTS-DAA INTRO WITH DIVIDE AND CONQUER
Salini P
 
UNIT 1- Design Analysis of algorithms and its working
UNIT 1- Design Analysis of algorithms and its workingUNIT 1- Design Analysis of algorithms and its working
UNIT 1- Design Analysis of algorithms and its working
Bobby Pra A
 
Design and analysis of algorithms Module-I.pptx
Design and analysis of algorithms Module-I.pptxDesign and analysis of algorithms Module-I.pptx
Design and analysis of algorithms Module-I.pptx
DhanushreeAN1
 
GLOBAL INSTITUTE OF MANAGEMENT AND TECHNOLOGY.pptx
GLOBAL INSTITUTE OF MANAGEMENT AND TECHNOLOGY.pptxGLOBAL INSTITUTE OF MANAGEMENT AND TECHNOLOGY.pptx
GLOBAL INSTITUTE OF MANAGEMENT AND TECHNOLOGY.pptx
hemantag1989
 
Chapter-1-Introduction-to-Aglorithms.pdf
Chapter-1-Introduction-to-Aglorithms.pdfChapter-1-Introduction-to-Aglorithms.pdf
Chapter-1-Introduction-to-Aglorithms.pdf
Shanmuganathan C
 
What is algorithm
What is algorithmWhat is algorithm
What is algorithm
lilyMalar1
 
01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx01 Introduction to analysis of Algorithms.pptx
01 Introduction to analysis of Algorithms.pptx
ssuser586772
 
s-INTRODUCTION TO PROBLEM SOLVING PPT.pptx
s-INTRODUCTION TO PROBLEM SOLVING PPT.pptxs-INTRODUCTION TO PROBLEM SOLVING PPT.pptx
s-INTRODUCTION TO PROBLEM SOLVING PPT.pptx
ShamithRai
 
Problem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialProblem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study material
To Sum It Up
 

More from MuhammadIfitikhar (10)

Lecture-00: Azure IoT Pi Day Slides.pptx
Lecture-00: Azure IoT Pi Day Slides.pptxLecture-00: Azure IoT Pi Day Slides.pptx
Lecture-00: Azure IoT Pi Day Slides.pptx
MuhammadIfitikhar
 
Lecture-6: Azure and Iot hub lecture.pptx
Lecture-6: Azure and Iot hub lecture.pptxLecture-6: Azure and Iot hub lecture.pptx
Lecture-6: Azure and Iot hub lecture.pptx
MuhammadIfitikhar
 
Python course slides topic objects in python
Python course slides topic objects in pythonPython course slides topic objects in python
Python course slides topic objects in python
MuhammadIfitikhar
 
Python Slides conditioanls and control flow
Python Slides conditioanls and control flowPython Slides conditioanls and control flow
Python Slides conditioanls and control flow
MuhammadIfitikhar
 
Python course lecture slides specifications and testing
Python course lecture slides specifications and testingPython course lecture slides specifications and testing
Python course lecture slides specifications and testing
MuhammadIfitikhar
 
Python Lecture Slides topic strings handling
Python Lecture Slides topic strings handlingPython Lecture Slides topic strings handling
Python Lecture Slides topic strings handling
MuhammadIfitikhar
 
Python Course Lecture Defining Functions
Python Course Lecture Defining FunctionsPython Course Lecture Defining Functions
Python Course Lecture Defining Functions
MuhammadIfitikhar
 
Python Course Functions and Modules Slides
Python Course Functions and Modules SlidesPython Course Functions and Modules Slides
Python Course Functions and Modules Slides
MuhammadIfitikhar
 
Python Lecture Slides Variables and Assignments
Python Lecture Slides Variables and AssignmentsPython Lecture Slides Variables and Assignments
Python Lecture Slides Variables and Assignments
MuhammadIfitikhar
 
Course Overview Python Basics Course Slides
Course Overview Python Basics Course SlidesCourse Overview Python Basics Course Slides
Course Overview Python Basics Course Slides
MuhammadIfitikhar
 
Lecture-00: Azure IoT Pi Day Slides.pptx
Lecture-00: Azure IoT Pi Day Slides.pptxLecture-00: Azure IoT Pi Day Slides.pptx
Lecture-00: Azure IoT Pi Day Slides.pptx
MuhammadIfitikhar
 
Lecture-6: Azure and Iot hub lecture.pptx
Lecture-6: Azure and Iot hub lecture.pptxLecture-6: Azure and Iot hub lecture.pptx
Lecture-6: Azure and Iot hub lecture.pptx
MuhammadIfitikhar
 
Python course slides topic objects in python
Python course slides topic objects in pythonPython course slides topic objects in python
Python course slides topic objects in python
MuhammadIfitikhar
 
Python Slides conditioanls and control flow
Python Slides conditioanls and control flowPython Slides conditioanls and control flow
Python Slides conditioanls and control flow
MuhammadIfitikhar
 
Python course lecture slides specifications and testing
Python course lecture slides specifications and testingPython course lecture slides specifications and testing
Python course lecture slides specifications and testing
MuhammadIfitikhar
 
Python Lecture Slides topic strings handling
Python Lecture Slides topic strings handlingPython Lecture Slides topic strings handling
Python Lecture Slides topic strings handling
MuhammadIfitikhar
 
Python Course Lecture Defining Functions
Python Course Lecture Defining FunctionsPython Course Lecture Defining Functions
Python Course Lecture Defining Functions
MuhammadIfitikhar
 
Python Course Functions and Modules Slides
Python Course Functions and Modules SlidesPython Course Functions and Modules Slides
Python Course Functions and Modules Slides
MuhammadIfitikhar
 
Python Lecture Slides Variables and Assignments
Python Lecture Slides Variables and AssignmentsPython Lecture Slides Variables and Assignments
Python Lecture Slides Variables and Assignments
MuhammadIfitikhar
 
Course Overview Python Basics Course Slides
Course Overview Python Basics Course SlidesCourse Overview Python Basics Course Slides
Course Overview Python Basics Course Slides
MuhammadIfitikhar
 
Ad

Recently uploaded (20)

Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3Software Engineering Process, Notation & Tools Introduction - Part 3
Software Engineering Process, Notation & Tools Introduction - Part 3
Gaurav Sharma
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricIntegration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentric
Natan Silnitsky
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Ad

Python Lecture slides topic Algorithm design

  • 2. Announcements For This Lecture Assignment 1 • Due TOMORROW § Due before midnight § Submit something… § Last revision Sep. 23 • Grades posted Sunday • Complete the Survey § Must answer individually Getting Help • Can work on it in lab § But still have a new lab § Make sure you do both • Consulting Hours § But expect it to be busy § First-come, first-served • One-on-Ones still going § Lots of spaces available 2 9/15/22 Algorithm Design
  • 3. Announcements For This Lecture Assignment 1 • Due TOMORROW § Due before midnight § Submit something… § Last revision Sep. 23 • Grades posted Sunday • Complete the Survey § Must answer individually Getting Help • Can work on it in lab § But still have a new lab § Make sure you do both • Consulting Hours § But expect it to be busy § First-come, first-served • One-on-Ones still going § Lots of spaces available 3 9/15/22 Algorithm Design Will post Assignment 2 Friday. This is a handwritten assignment.
  • 4. What Are Algorithms? Algorithm • Step-by-step instructions § Not specific to a language § Could be a cooking recipe • Outline for a program Implementation • Program for an algorithm § In a specific language § What we often call coding • The filled in outline 9/15/22 Algorithm Design 4 • Good programmers can separate the two § Work on the algorithm first § Implement in language second • Why approach strings as search-cut-glue
  • 5. Difficulties With Programming Syntax Errors • Python can’t understand you • Examples: § Forgetting a colon § Not closing a parens • Common with beginners § But can quickly train out Conceptual Errors • Does what you say, not mean • Examples: § Forgot last char in slice § Used the wrong argument • Happens to everyone § Large part of CS training Proper algorithm design reduces conceptual errors 9/15/22 Algorithm Design 5
  • 6. Testing First Strategy • Write the Tests First Could be script or written by hand • Take Small Steps Do a little at a time; make use of placeholders • Intersperse Programming and Testing When you finish a step, test it immediately • Separate Concerns Do not move to a new step until current is done 9/15/22 Algorithm Design 6
  • 7. Testing First Strategy • Write the Tests First Could be script or written by hand • Take Small Steps Do a little at a time; make use of placeholders • Intersperse Programming and Testing When you finish a step, test it immediately • Separate Concerns Do not move to a new step until current is done Will see several strategies. But all built on this core idea. 9/15/22 Algorithm Design 7
  • 8. Using Placeholders in Design • Strategy: fill in definition a little at a time • We start with a function stub § Function that can be called but is unfinished § Allows us to test while still working (later) • All stubs must have a function header § But the definition body might be “empty” § Certainly is when you get started 9/15/22 Algorithm Design 8
  • 9. A Function Stub def last_name_first(s): """Returns: copy of s in form 'last-name, 'first-name' Precondition: s is in form 'first-name last-name' with one blank between the two names""" # Finish the body “Empty” 9/15/22 Algorithm Design 9
  • 10. But it Cannot Really Be Empty def last_name_first(s): # Finish the body • A function definition is only valid with a body § (Single-line) comments do not count as body § But doc-strings do count (part of help function) • So you should always write in the specification Error 9/15/22 Algorithm Design 10
  • 11. An Alternative: Pass def last_name_first(s): pass • You can make the body non-empty with pass § It is a command to “do nothing” § Only purpose is to ensure there is a body • You would remove it once you got started Fine! 9/15/22 Algorithm Design 11
  • 12. Ideally: Use Both def last_name_first(s): """Returns: copy of s in form 'last-name, 'first-name' Precondition: s is in form 'first-name last-name' with one blank between the two names""" pass Now pass is a note that is unfinished. Can leave it there until work is done. 9/15/22 Algorithm Design 12
  • 13. Outlining Your Approach • Recall the two types of errors you will have § Syntax Errors: Python can’t understand you § Conceptual Errors: Does what you say, not mean • To remove conceptual errors, plan before code § Create outline of the steps to carry out § Write in this outline as comments • This outline is called pseudocode § English statements of what to do § But corresponds to something simple in Python 9/15/22 Algorithm Design 13
  • 14. Example: Reordering a String def last_name_first(s): """Returns: copy of s in form 'last-name, 'first-name' Precondition: s is in form 'first-name last-name' with one blank between the two names""" # Find the space between the two names # Cut out the first name # Cut out the last name # Glue them together with a comma 9/15/22 Algorithm Design 14
  • 15. Example: Reordering a String def last_name_first(s): """Returns: copy of s in form 'last-name, 'first-name' Precondition: s is in form 'first-name last-name' with one blank between the two names""" end_first = s.find(' ') # Cut out the first name # Cut out the last name # Glue them together with a comma 9/15/22 Algorithm Design 15
  • 16. Example: Reordering a String def last_name_first(s): """Returns: copy of s in form 'last-name, 'first-name' Precondition: s is in form 'first-name last-name' with one blank between the two names""" end_first = s.find(' ') first_name = s[:end_first] # Cut out the last name # Glue them together with a comma 9/15/22 Algorithm Design 16
  • 17. What is the Challenge? • Pseudocode must correspond to Python § Preferably implementable in one line § Unhelpful: # Return the correct answer • So what can we do? § Depends on the types involved § Different types have different operations § You should memorize important operations § Use these as building blocks 9/15/22 Algorithm Design 17
  • 18. Case Study: Strings • We can slice strings (s[a:b]) • We can glue together strings (+) • We have a lot of string methods § We can search for characters § We can count the number of characters § We can pad strings § We can strip padding • Sometimes, we can cast to a new type 9/15/22 Algorithm Design 18
  • 19. Early Testing • Recall: Combine programming & testing § After each step we should test § But it is unfinished; answer is incorrect! • Goal: ensure intermediate results expected § Take an input from your testing plan § Call the function on that input § Look at the results at each step § Make sure they are what you expect • Add a temporary return value 9/15/22 Algorithm Design 19
  • 20. Stubbed Returns def last_name_first(s): """Returns: copy of s in form 'last-name, 'first-name' Precondition: s is in form 'first-name last-name' with one blank between the two names""" end_first = s.find(' ') first = s[:end_first] # Cut out the last name # Glue them together with a comma return first # Not the final answer 9/15/22 Algorithm Design 20
  • 21. Working with Helpers • Suppose you are unsure of a step § You maybe have an idea for pseudocode § But not sure if it easily converts to Python • But you can specify what you want § Specification means a new function! § Create a specification stub for that function § Put a call to it in the original function • Now can lazily implement that function 9/15/22 Algorithm Design 21
  • 22. Example: last_name_first def last_name_first(s): """Returns: copy of s in the form 'last-name, first-name' Precondition: s is in the form 'first-name last-name' with with one blank between names""" # Cut out the first name # Cut out the last name # Glue together with comma # Return the result 9/15/22 Algorithm Design 22
  • 23. Example: last_name_first def last_name_first(s): """Returns: copy of s in the form 'last-name, first-name' Precondition: s is in the form 'first-name last-name' with with one blank between names""” first = first_name(s) # Cut out the last name # Glue together with comma return first # Stub def first_name(s): """Returns: first name in s Precondition: s is in the form 'first-name last-name' with one blank between names""" pass 9/15/22 Algorithm Design 23
  • 24. Example: last_name_first def last_name_first(s): """Returns: copy of s in the form 'last-name, first-name' Precondition: s is in the form 'first-name last-name' with with one blank between names""” first = first_name(s) # Cut out the last name # Glue together with comma return first # Stub def first_name(s): """Returns: first name in s Precondition: s is in the form 'first-name last-name' with one blank between names""" end = s.find(' ') return s[:end] 9/15/22 Algorithm Design 24
  • 25. Concept of Top Down Design • Function specification is given to you § This cannot change at all § Otherwise, you break the team • But you break it up into little problems § Each naturally its own function § YOU design the specification for each § Implement and test each one • Complete before the main function 9/15/22 Algorithm Design 25
  • 26. Testing and Top Down Design def test_first_name(): """Test procedure for first_name(n)""" result = name.first_name('Walker White') introcs.assert_equals('Walker', result) def test_last_name_first(): """Test procedure for last_name_first(n)""" result = name.last_name_first('Walker White') introcs.assert_equals('White, Walker', result) 9/15/22 Algorithm Design 26
  • 27. A Word of Warning • Do not go overboard with this technique § Do not want a lot of one line functions § Can make code harder to read in extreme • Do it if the code is too long § I personally have a one page rule § If more than that, turn part into a function • Do it if you are repeating yourself a lot § If you see the same code over and over § Replace that code with a single function call 9/15/22 Algorithm Design 27
  • 28. Exercise: Anglicizing an Integer • anglicize(1) is “one” • anglicize(15) is “fifteen” • anglicize(123) is “one hundred twenty three” • anglicize(10570) is “ten thousand five hundred def anglicize(n): """Returns: the anglicization of int n. Precondition: 0 < n < 1,000,000""" pass # ??? 9/15/22 Algorithm Design 28
  • 29. Exercise: Anglicizing an Integer def anglicize(n): """Returns: the anglicization of int n. Precondition: 0 < n < 1,000,000""" # if < 1000, provide an answer # if > 1000, break into hundreds, thousands parts # use the < 1000 answer for each part , and glue # together with "thousands" in between # return the result 9/15/22 Algorithm Design 29
  • 30. Exercise: Anglicizing an Integer def anglicize(n): """Returns: the anglicization of int n. Precondition: 0 < n < 1,000,000""" if n < 1000: # no thousands place return anglicize1000(n) elif n % 1000 == 0: # no hundreds, only thousands return anglicize1000(n/1000) + ' thousand' else: # mix the two return (anglicize1000(n/1000) + ' thousand '+ anglicize1000(n)) 9/15/22 Algorithm Design 30
  • 31. Exercise: Anglicizing an Integer def anglicize(n): """Returns: the anglicization of int n. Precondition: 0 < n < 1,000,000""" if n < 1000: # no thousands place return anglicize1000(n) elif n % 1000 == 0: # no hundreds, only thousands return anglicize1000(n/1000) + ' thousand' else: # mix the two return (anglicize1000(n/1000) + ' thousand '+ anglicize1000(n)) 9/15/22 Algorithm Design 31 Now implement this. See anglicize.py