The document discusses algorithms and their building blocks. It defines an algorithm as a collection of well-defined, unambiguous and effectively computable instructions that return a proper output. The three building blocks of algorithms are identified as sequence, selection, and iteration. Sequence refers to a series of actions performed in order. Selection allows a program to choose between different actions or conditions. Iteration allows a block of code to be repeated while a condition is true. Pseudocode and flowcharts are introduced as common ways to express algorithms and illustrate the control flow and logic of a program.
This book's author is Zafar Ali Khan .
It consists of all the topics of As Level Computer Science topics that are required to be covered.
All credits goes to Zafar Ali Khan .
Here are the steps to solve the problems using IPO table, pseudo code and flowchart:
1. Define the problem and understand requirements
2. Make IPO table:
- Input, Process, Output
3. Write pseudo code using proper indentation and comments
4. Draw flowchart using standard symbols
5. Test and debug the program
This systematic approach helps analyze the problem, design the algorithm and implement it properly. The key is breaking down the problem into smaller understandable steps.
Design and Analysis of Algorithm ppt for unit onessuserb7c8b8
The document outlines an algorithms course, including course details, objectives, and an introduction. The course code is 10211CS202 and name is Design and Analysis of Algorithms. It has 4 credits and meets for 6 hours per week. The course aims to teach fundamental techniques for effective problem solving, analyzing algorithm performance, and designing efficient algorithms. It covers topics like sorting, searching, and graph algorithms.
This document outlines the syllabus for the course GE3151 Problem Solving and Python Programming. It includes 5 units that cover topics like computational thinking, Python data types, control flow, functions, lists, tuples, dictionaries, files and modules. The objectives of the course are to understand algorithmic problem solving, learn to solve problems using Python conditionals and loops, define functions and use data structures like lists and tuples. It also aims to teach input/output with files in Python. The document provides the number of periods (45) and textbooks recommended for the course.
This document discusses algorithms and data structures. It covers the requirements of algorithms including inputs, outputs, unambiguousness, generality, correctness, being finite, and efficiency. It also discusses representing algorithms through pseudo-code and flowcharts. Some key aspects of pseudo-code are described such as its purpose to define algorithms simply and its use of limited vocabulary and English-like notation. Common control structures like sequence, selection, and repetition are explained. Examples of bubble sort, selection sort, and insertion sort algorithms are also mentioned.
This document provides an overview of the Data Structures I course. It outlines the course objectives of becoming familiar with problem solving, algorithms, data structures, and tracing algorithms. The course will cover fundamentals of data structures and algorithms, static and dynamic data structures, searching and sorting algorithms, recursion, abstract data types, stacks, queues and trees. Exams, labs, participation and quizzes will be used for grading. Pseudo-code is introduced as a way to express algorithms independent of a programming language. Examples of algorithms for determining even/odd numbers and computing weekly wages are provided.
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
This document discusses algorithms and their design. It defines an algorithm as a sequence of unambiguous instructions to solve a problem within a finite time. The key steps in designing algorithms are: understanding the problem, choosing appropriate data structures and computational means, designing and proving the algorithm, analyzing its efficiency, and coding it. Important problem types include sorting, searching, graphs, and numerical problems. Fundamental data structures include arrays, linked lists, stacks, queues, trees, graphs, sets, bags and dictionaries.
Here are the algorithms in pseudocode:
1. Find largest number of unknown set:
- Read first number and assign to largest
- Read next number
- If number is greater than largest, assign it to largest
- Repeat step 2 until no more numbers
- Output largest
2. Find average of numbers:
- Read number of elements n
- Initialize sum = 0
- Initialize i = 0
- Repeat while i < n
- Read element at array[i]
- Add element to sum
- Increment i
- Calculate average = sum / n
- Output average
Here are the algorithms in pseudocode:
1. Find largest number of unknown set:
- Read first number and assign to largest
- Read next number
- If number is greater than largest, assign it to largest
- Repeat step 2 until no more numbers
- Output largest
2. Find average of numbers:
- Read number of elements n
- Initialize sum = 0
- Initialize i = 0
- Repeat while i < n
- Read element at array[i]
- Add element to sum
- Increment i
- Calculate average = sum / n
- Output average
This document outlines the syllabus for the subject "Design and Analysis of Algorithms" for the 3rd year 1st semester students of the Computer Science and Engineering department with specialization in Cyber Security at CMR Engineering College.
The syllabus is divided into 5 units which cover topics like algorithm analysis, asymptotic notations, algorithm design techniques like divide and conquer, dynamic programming, greedy algorithms etc. It also discusses NP-hard and NP-complete problems. The document provides the textbook and references for the subject. It further includes introductions to different units explaining key concepts like algorithms, properties of algorithms, ways to represent algorithms, need for algorithm analysis etc.
Introduction to Design Algorithm And Analysis.pptBhargaviDalal4
This document contains the syllabus for the subject "Design and Analysis of Algorithms" for the 3rd year 1st semester students of CMR Engineering College. It includes 5 units - Introduction, Disjoint Sets and Backtracking, Dynamic Programming and Greedy Methods, Branch and Bound, and NP-Hard and NP-Complete problems. The introduction covers topics like algorithm complexity analysis and divide and conquer algorithms. The syllabus outlines core algorithms topics and applications like binary search, quicksort, dynamic programming, shortest paths, knapsack etc. that will be covered in the course.
The document provides an introduction and overview of the Design and Analysis of Algorithms course. It covers key topics like asymptotic notations and their properties, analyzing recursive and non-recursive algorithms, divide-and-conquer algorithms like quicksort and mergesort, and sorting algorithms like heap sort. Examples of insertion sort and analysis of its worst-case running time of O(n2) are provided. Asymptotic notation like Big-O, Ω, and Θ are introduced to analyze algorithms' time complexities as the problem size n approaches infinity.
This document discusses algorithms and provides an example algorithm for adding three numbers and printing the sum. It defines an algorithm as a set of steps to solve a problem and lists characteristics of algorithms such as being clear, well-defined, finite, feasible, and language independent. The document also outlines a process for designing algorithms which includes defining the problem, developing a model, specifying the algorithm, designing it, checking correctness, analyzing it, implementing it, testing it, and documenting it. It then provides an example algorithm that takes three numbers as input, adds them together, stores the sum in a variable, and prints the result.
01 Introduction to analysis of Algorithms.pptxssuser586772
An algorithm is a set of steps of operations to solve a problem performing calculation, data processing, and automated reasoning tasks.
An algorithm is an efficient method that can be expressed within finite amount of Time and space.
The important aspects of algorithm design include creating an efficient algorithm to solve a problem in an efficient way using minimum time and space.
To solve a problem, different approaches can be followed. Some of them can be efficient with respect to time consumption, whereas other approaches may be memory efficient. To Evaluate An Algorithm we have to Satisfy the following Criteria:
INPUT: The Algorithm should be given zero or more input.
OUTPUT: At least one quantity is produced. For each input the algorithm produced value from specific task.
DEFINITENESS: Each instruction is clear and unambiguous.
FINITENESS: If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a finite number of steps.
EFFECTIVENESS: Every instruction must very basic so that it can be carried out, in principle, by a person using only pencil & paper.Algorithm : Systematic logical approach which is a well-defined, step-by-step procedure that allows a computer to solve a problem.
Pseudocode : It is a simpler version of a programming code in plain English which uses short phrases to write code for a program before it is implemented in a specific programming language.
Program : It is exact code written for problem following all the rules of the programming language.Algorithm can be described (Represent) in four ways.
Natural language like English:
When this way is chooses, care should be taken, we
should ensure that each & every statement is definite.
(no ambiguity)
2. Graphic representation called flowchart:
This method will work well when the algorithm is small& simple.
3. Pseudo-code Method:
In this method, we should typically describe algorithms as
program, which resembles language like Pascal & Algol
(Algorithmic Language).
4.Programming Language:
we have to use programming language to write algorithms like
C, C++,JAVA etc.Comments begin with // and continue until the end of line.
Blocks are indicated with matching braces { and }.
An identifier begins with a letter. The data types of variables are not explicitly declared.
node= record
{
data type 1 data 1;
data type n data n;
node *link;
}
4. There are two Boolean values TRUE and FALSE.
Logical Operators
AND, OR, NOT
Relational Operators
<, <=,>,>=, =, !=
1.How to create an algorithm: To create an algorithm we have following design technique
a) Divide & Conquer
b) Greedy method
c) Dynamic Programming
d) Branch & Bound
e) Backtracking
2.How to validate an algorithm:
Once an algorithm is created it is necessary to show that it computes the correct Pr
Problem solving using computers - Unit 1 - Study materialTo Sum It Up
Problem solving using computers involves transforming a problem description into a solution using problem-solving strategies, techniques, and tools. Programming is a problem-solving activity where instructions are written for a computer to solve something. The document then discusses the steps in problem solving like definition, analysis, approach, coding, testing etc. It provides examples of algorithms, flowcharts, pseudocode and discusses concepts like top-down design, time complexity, space complexity and ways to swap variables and count values.
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
This document discusses algorithms and their design. It defines an algorithm as a sequence of unambiguous instructions to solve a problem within a finite time. The key steps in designing algorithms are: understanding the problem, choosing appropriate data structures and computational means, designing and proving the algorithm, analyzing its efficiency, and coding it. Important problem types include sorting, searching, graphs, and numerical problems. Fundamental data structures include arrays, linked lists, stacks, queues, trees, graphs, sets, bags and dictionaries.
Here are the algorithms in pseudocode:
1. Find largest number of unknown set:
- Read first number and assign to largest
- Read next number
- If number is greater than largest, assign it to largest
- Repeat step 2 until no more numbers
- Output largest
2. Find average of numbers:
- Read number of elements n
- Initialize sum = 0
- Initialize i = 0
- Repeat while i < n
- Read element at array[i]
- Add element to sum
- Increment i
- Calculate average = sum / n
- Output average
Here are the algorithms in pseudocode:
1. Find largest number of unknown set:
- Read first number and assign to largest
- Read next number
- If number is greater than largest, assign it to largest
- Repeat step 2 until no more numbers
- Output largest
2. Find average of numbers:
- Read number of elements n
- Initialize sum = 0
- Initialize i = 0
- Repeat while i < n
- Read element at array[i]
- Add element to sum
- Increment i
- Calculate average = sum / n
- Output average
This document outlines the syllabus for the subject "Design and Analysis of Algorithms" for the 3rd year 1st semester students of the Computer Science and Engineering department with specialization in Cyber Security at CMR Engineering College.
The syllabus is divided into 5 units which cover topics like algorithm analysis, asymptotic notations, algorithm design techniques like divide and conquer, dynamic programming, greedy algorithms etc. It also discusses NP-hard and NP-complete problems. The document provides the textbook and references for the subject. It further includes introductions to different units explaining key concepts like algorithms, properties of algorithms, ways to represent algorithms, need for algorithm analysis etc.
Introduction to Design Algorithm And Analysis.pptBhargaviDalal4
This document contains the syllabus for the subject "Design and Analysis of Algorithms" for the 3rd year 1st semester students of CMR Engineering College. It includes 5 units - Introduction, Disjoint Sets and Backtracking, Dynamic Programming and Greedy Methods, Branch and Bound, and NP-Hard and NP-Complete problems. The introduction covers topics like algorithm complexity analysis and divide and conquer algorithms. The syllabus outlines core algorithms topics and applications like binary search, quicksort, dynamic programming, shortest paths, knapsack etc. that will be covered in the course.
The document provides an introduction and overview of the Design and Analysis of Algorithms course. It covers key topics like asymptotic notations and their properties, analyzing recursive and non-recursive algorithms, divide-and-conquer algorithms like quicksort and mergesort, and sorting algorithms like heap sort. Examples of insertion sort and analysis of its worst-case running time of O(n2) are provided. Asymptotic notation like Big-O, Ω, and Θ are introduced to analyze algorithms' time complexities as the problem size n approaches infinity.
This document discusses algorithms and provides an example algorithm for adding three numbers and printing the sum. It defines an algorithm as a set of steps to solve a problem and lists characteristics of algorithms such as being clear, well-defined, finite, feasible, and language independent. The document also outlines a process for designing algorithms which includes defining the problem, developing a model, specifying the algorithm, designing it, checking correctness, analyzing it, implementing it, testing it, and documenting it. It then provides an example algorithm that takes three numbers as input, adds them together, stores the sum in a variable, and prints the result.
01 Introduction to analysis of Algorithms.pptxssuser586772
An algorithm is a set of steps of operations to solve a problem performing calculation, data processing, and automated reasoning tasks.
An algorithm is an efficient method that can be expressed within finite amount of Time and space.
The important aspects of algorithm design include creating an efficient algorithm to solve a problem in an efficient way using minimum time and space.
To solve a problem, different approaches can be followed. Some of them can be efficient with respect to time consumption, whereas other approaches may be memory efficient. To Evaluate An Algorithm we have to Satisfy the following Criteria:
INPUT: The Algorithm should be given zero or more input.
OUTPUT: At least one quantity is produced. For each input the algorithm produced value from specific task.
DEFINITENESS: Each instruction is clear and unambiguous.
FINITENESS: If we trace out the instructions of an algorithm, then for all cases, the algorithm terminates after a finite number of steps.
EFFECTIVENESS: Every instruction must very basic so that it can be carried out, in principle, by a person using only pencil & paper.Algorithm : Systematic logical approach which is a well-defined, step-by-step procedure that allows a computer to solve a problem.
Pseudocode : It is a simpler version of a programming code in plain English which uses short phrases to write code for a program before it is implemented in a specific programming language.
Program : It is exact code written for problem following all the rules of the programming language.Algorithm can be described (Represent) in four ways.
Natural language like English:
When this way is chooses, care should be taken, we
should ensure that each & every statement is definite.
(no ambiguity)
2. Graphic representation called flowchart:
This method will work well when the algorithm is small& simple.
3. Pseudo-code Method:
In this method, we should typically describe algorithms as
program, which resembles language like Pascal & Algol
(Algorithmic Language).
4.Programming Language:
we have to use programming language to write algorithms like
C, C++,JAVA etc.Comments begin with // and continue until the end of line.
Blocks are indicated with matching braces { and }.
An identifier begins with a letter. The data types of variables are not explicitly declared.
node= record
{
data type 1 data 1;
data type n data n;
node *link;
}
4. There are two Boolean values TRUE and FALSE.
Logical Operators
AND, OR, NOT
Relational Operators
<, <=,>,>=, =, !=
1.How to create an algorithm: To create an algorithm we have following design technique
a) Divide & Conquer
b) Greedy method
c) Dynamic Programming
d) Branch & Bound
e) Backtracking
2.How to validate an algorithm:
Once an algorithm is created it is necessary to show that it computes the correct Pr
Problem solving using computers - Unit 1 - Study materialTo Sum It Up
Problem solving using computers involves transforming a problem description into a solution using problem-solving strategies, techniques, and tools. Programming is a problem-solving activity where instructions are written for a computer to solve something. The document then discusses the steps in problem solving like definition, analysis, approach, coding, testing etc. It provides examples of algorithms, flowcharts, pseudocode and discusses concepts like top-down design, time complexity, space complexity and ways to swap variables and count values.
In a tight labor market and tighter economy, PMOs and resource managers must ensure that every team member is focused on the highest-value work. This session explores how AI reshapes resource planning and empowers organizations to forecast capacity, prevent burnout, and balance workloads more effectively, even with shrinking teams.
Invited Talk at RAISE 2025: Requirements engineering for AI-powered SoftwarE Workshop co-located with ICSE, the IEEE/ACM International Conference on Software Engineering.
Abstract: Foundation Models (FMs) have shown remarkable capabilities in various natural language tasks. However, their ability to accurately capture stakeholder requirements remains a significant challenge for using FMs for software development. This paper introduces a novel approach that leverages an FM-powered multi-agent system called AlignMind to address this issue. By having a cognitive architecture that enhances FMs with Theory-of-Mind capabilities, our approach considers the mental states and perspectives of software makers. This allows our solution to iteratively clarify the beliefs, desires, and intentions of stakeholders, translating these into a set of refined requirements and a corresponding actionable natural language workflow in the often-overlooked requirements refinement phase of software engineering, which is crucial after initial elicitation. Through a multifaceted evaluation covering 150 diverse use cases, we demonstrate that our approach can accurately capture the intents and requirements of stakeholders, articulating them as both specifications and a step-by-step plan of action. Our findings suggest that the potential for significant improvements in the software development process justifies these investments. Our work lays the groundwork for future innovation in building intent-first development environments, where software makers can seamlessly collaborate with AIs to create software that truly meets their needs.
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...Insurance Tech Services
A modern Policy Administration System streamlines workflows and integrates with core systems to boost speed, accuracy, and customer satisfaction across the policy lifecycle. Visit https://www.damcogroup.com/insurance/policy-administration-systems for more details!
In today's world, artificial intelligence (AI) is transforming the way we learn.
This talk will explore how we can use AI tools to enhance our learning experiences, by looking at some (recent) research that has been done on the matter.
But as we embrace these new technologies, we must also ask ourselves:
Are we becoming less capable of thinking for ourselves?
Do these tools make us smarter, or do they risk dulling our critical thinking skills?
This talk will encourage us to think critically about the role of AI in our education. Together, we will discover how to use AI to support our learning journey while still developing our ability to think critically.
FME as an Orchestration Tool - Peak of Data & AI 2025Safe Software
Processing huge amounts of data through FME can have performance consequences, but as an orchestration tool, FME is brilliant! We'll take a look at the principles of data gravity, best practices, pros, cons, tips and tricks. And of course all spiced up with relevant examples!
Bonk coin airdrop_ Everything You Need to Know.pdfHerond Labs
The Bonk airdrop, one of the largest in Solana’s history, distributed 50% of its total supply to community members, significantly boosting its popularity and Solana’s network activity. Below is everything you need to know about the Bonk coin airdrop, including its history, eligibility, how to claim tokens, risks, and current status.
https://blog.herond.org/bonk-coin-airdrop/
Top 5 Task Management Software to Boost Productivity in 2025Orangescrum
In this blog, you’ll find a curated list of five powerful task management tools to watch in 2025. Each one is designed to help teams stay organized, improve collaboration, and consistently hit deadlines. We’ve included real-world use cases, key features, and data-driven insights to help you choose what fits your team best.
Revolutionize Your Insurance Workflow with Claims Management SoftwareInsurance Tech Services
Claims management software enhances efficiency, accuracy, and satisfaction by automating processes, reducing errors, and speeding up transparent claims handling—building trust and cutting costs. Explore More - https://www.damcogroup.com/insurance/claims-management-software
Generative Artificial Intelligence and its ApplicationsSandeepKS52
The exploration of generative AI begins with an overview of its fundamental concepts, highlighting how these technologies create new content and ideas by learning from existing data. Following this, the focus shifts to the processes involved in training and fine-tuning models, which are essential for enhancing their performance and ensuring they meet specific needs. Finally, the importance of responsible AI practices is emphasized, addressing ethical considerations and the impact of AI on society, which are crucial for developing systems that are not only effective but also beneficial and fair.
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfVarsha Nayak
In recent years, organizations have increasingly sought robust open source alternative to Jasper Reports as the landscape of open-source reporting tools rapidly evolves. While Jaspersoft has been a longstanding choice for generating complex business intelligence and analytics reports, factors such as licensing changes and growing demands for flexibility have prompted many businesses to explore other options. Among the most notable alternatives to Jaspersoft, Helical Insight stands out for its powerful open-source architecture, intuitive analytics, and dynamic dashboard capabilities. Designed to be both flexible and budget-friendly, Helical Insight empowers users with advanced features—such as in-memory reporting, extensive data source integration, and customizable visualizations—making it an ideal solution for organizations seeking a modern, scalable reporting platform. This article explores the future of open-source reporting and highlights why Helical Insight and other emerging tools are redefining the standards for business intelligence solutions.
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Natan Silnitsky
In a world where speed, resilience, and fault tolerance define success, Wix leverages Kafka to power asynchronous programming across 4,000 microservices. This talk explores four key patterns that boost developer velocity while solving common challenges with scalable, efficient, and reliable solutions:
1. Integration Events: Shift from synchronous calls to pre-fetching to reduce query latency and improve user experience.
2. Task Queue: Offload non-critical tasks like notifications to streamline request flows.
3. Task Scheduler: Enable precise, fault-tolerant delayed or recurring workflows with robust scheduling.
4. Iterator for Long-running Jobs: Process extensive workloads via chunked execution, optimizing scalability and resilience.
For each pattern, we’ll discuss benefits, challenges, and how we mitigate drawbacks to create practical solutions
This session offers actionable insights for developers and architects tackling distributed systems, helping refine microservices and adopting Kafka-driven async excellence.
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricNatan Silnitsky
At Wix, we revolutionized our platform by making integration events the backbone of our 4,000-microservice ecosystem. By abandoning traditional domain events for standardized Protobuf events through Kafka, we created a universal language powering our entire architecture.
We'll share how our "single-aggregate services" approach—where every CUD operation triggers semantic events—transformed scalability and extensibility, driving efficient event choreography, data lake ingestion, and search indexing.
We'll address our challenges: balancing consistency with modularity, managing event overhead, and solving consumer lag issues. Learn how event-based data prefetches dramatically improved performance while preserving the decoupling that makes our platform infinitely extensible.
Key Takeaways:
- How integration events enabled unprecedented scale and extensibility
- Practical strategies for event-based data prefetching that supercharge performance
- Solutions to common event-driven architecture challenges
- When to break conventional architectural rules for specific contexts
14 Years of Developing nCine - An Open Source 2D Game FrameworkAngelo Theodorou
A 14-year journey developing nCine, an open-source 2D game framework.
This talk covers its origins, the challenges of staying motivated over the long term, and the hurdles of open-sourcing a personal project while working in the game industry.
Along the way, it’s packed with juicy technical pills to whet the appetite of the most curious developers.
Have you upgraded your application from Qt 5 to Qt 6? If so, your QML modules might still be stuck in the old Qt 5 style—technically compatible, but far from optimal. Qt 6 introduces a modernized approach to QML modules that offers better integration with CMake, enhanced maintainability, and significant productivity gains.
In this webinar, we’ll walk you through the benefits of adopting Qt 6 style QML modules and show you how to make the transition. You'll learn how to leverage the new module system to reduce boilerplate, simplify builds, and modernize your application architecture. Whether you're planning a full migration or just exploring what's new, this session will help you get the most out of your move to Qt 6.
GDG Douglas - Google AI Agents: Your Next Intern?felipeceotto
Presentation done at the GDG Douglas event for June 2025.
A first look at Google's new Agent Development Kit.
Agent Development Kit is a new open-source framework from Google designed to simplify the full stack end-to-end development of agents and multi-agent systems.
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