Class 01
Introduction + Python essentials
me
Design of algorithms using Python
ANA ALMEIDA MATOS - MINOR INFORMATICS + LEME 2024/25 1
"The art and science of asking questions is the
source of all knowledge" Thomas Berger
• Do not hesitate to ask!
• If something is not clear, stop me and ask.
• Now let me ask something…
• What are your goals in studying Python programming
and algorithms?
Introduction
Class 01
• Introduction to Algorithms and
Data Structures
• Organization of the course
• Python essentials
3
What Is Computer Science?
``Computer science is the study of solutions to problems
as well as the study of problems with no solutions´´
DESIGN OF ALGORITHMS USING PYTHON 2024/25 4
What Is an Algorithm?
``An algorithm is a step by step list of instructions that if
followed exactly will solve the problem under consideration´´
DESIGN OF ALGORITHMS USING PYTHON 2024/25 5
What Is Programming?
``Programming is the process of taking an algorithm
and encoding it into a notation, a programming
language, so that it can be executed by a computer.''
DESIGN OF ALGORITHMS USING PYTHON 2024/25 6
Why Study Algorithms?
• To gain experience in algorithms that facilitates designing
new algorithms for solving similar problems.
• To learn analysis techniques that allow us to compare and
contrast abstract solutions.
• To be able to distinguish between those problems that have
solutions, those that do not, and those where solutions exist
but require too much time or resources.
• To know and understand solution evaluation techniques for
deciding whether a given solution is a good one.
DESIGN OF ALGORITHMS USING PYTHON 2024/25 7
Why Study Data Structures and
Abstract Data Types?
• Data structures define the format in which data is
organized, managed and stored, and the functions and
operations for manipulating it.
• Abstractions help manage the complexity of
problems and make the problem-solving process
more efficient.
• Abstract Data Types describe the data that our
algorithms manipulate in an implementation-independent
view, and to remain focused on the problem-solving process.
DESIGN OF ALGORITHMS USING PYTHON 2024/25 8
Why Python?
• C is faster, but less high level,
• Java has a more demanding
requires knowledge of
learning curve, more verbose
systems
high-level
easy to learn
multiple
paradigms
widely used
DESIGN OF ALGORITHMS USING PYTHON 2022/23
DESIGN OF ALGORITHMS USING PYTHON 2024/25 9
Why Python? top position
since 2022
DESIGN OF ALGORITHMS USING PYTHON 2024/25 10
Introduction
Class 01
• Introduction to Algorithms and
Data Structures
• Organization of the course
• Python essentials
11
Goals
• to consolidate knowledge of algorithmic and data
structures
• in an accessible programming language that allows the
focus on the algorithmic components of computational
solutions
• to provide students with knowledge to build medium-
sized programs that allow them to manipulate data
efficiently.
DESIGN OF ALGORITHMS USING PYTHON 2024/25 12
Classes
• Theoretical classes: 7 weeks x 2 classes x 2 hours
• Practical classes: 7 weeks x 2 classes x 1.5 hours
• Calendar:
• Teaching: 9 September - 25 October
• Exams: 5 November and 7 February
DESIGN OF ALGORITHMS USING PYTHON 2024/25 13
Schedule
LEME Minor I
?
?
EA3
QA1.1
DESIGN OF ALGORITHMS USING PYTHON 2024/25 14
Minor I // LEME
• Theoretical classes are taught together
• some topics (as indicated in classes) will not be
evaluated in LEME
• Practical classes are differentiated (schedules and
selected exercises)
• Project, practical test, and exams specifications are
adapted
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Communication
• Primarily via Zulip, for a quicker response, and so that all students can
benefit from the information - remember to configure notifications
• Official announcements and resources via:
• the course’s website (Fenix),
• email, using your official email address
• Course’s website @ Fenix:
LEME
https://fenix.tecnico.ulisboa.pt/disciplinas/DAUP11-2/2024-2025/1-semestre
Minor I
https://fenix.tecnico.ulisboa.pt/disciplinas/DAUP11/2024-2025/1-semestre
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Resources
• interactive courses @ https://runestone.academy
• "AlgPy-2425"
• "AlgPy-Intro-2425"
• slides, exercises
• class recordings, videos
• books, tutorials, papers
Sections Study Materials @ Fénix
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Evaluation
• Project (50%)
• in groups of 2
• includes practical test (during week 8 “semana de preparação”)
• Exam (50%)
• covers theoretical and practical classes
• can be repeated (“Época de Recurso”)
• “Época especial” exam can replace Project grade
See “Evaluations” and “Evaluation Methods” @ Fenix
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Office hours
• Support to your study is offered via Zoom
• Wednesdays 9:00 to 13:00 and 14:30 to 15:30
See Office hours @ Section “Course Logistics”, Fénix
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Program (may be adjusted)
• Week 01 - Introduction
• Class 01 - Introduction to the course + Python essentials
• Introduction to Algorithms and Data Structures
• Organization of the course
• Python essentials
• Class 02 - Python essentials (continued)
• Control Structures
• Exceptions
• Functions Section “Summaries” @ Fénix
DESIGN OF ALGORITHMS USING PYTHON 2024/25 20
• Week 02 - Python essentials (conclusion) and Analysis
• Class 03 - Object-Oriented Programming in Python
• Class 04 - Complexity Analysis
• Week 03 - Analysis
• Class 05 - Algorithm Complexity
• Class 06 - Analysis of Python structures and applications
• Week 04 - Basic Data Structures
• Class 07 - Stacks, Queues, Dequeues and Lists
DESIGN OF ALGORITHMS USING PYTHON 2024/25 21
• Week 05 - Recursion, Sorting and Searching
• Class 09 - Recursion
• Class 10 - Sorting and Searching
• Week 06 - Trees and Tree Algorithms
• Class 11 - Tree basics, Binary Trees
• Class 12 - Graph basics
• Week 07 - Graphs and Graph Algorithms
• Class 13 - Breadth First Search, Shortest Path, Spanning Tree
• Class 14 - Depth First Search, Topological sorting, Strongly
Connected Components
DESIGN OF ALGORITHMS USING PYTHON 2024/25 22
Python essentials
• Next two weeks - introduce/review the essential aspects of
the Python programming language that are needed for this
course
• You will develop your practice of Python programming in
practical classes and project, while focusing on algorithms
• You are encouraged to adjust your pace and depth of study of
Python depending on your level of proficiency
• Complementary resource: How to Think Like a Computer
Scientist: Interactive Edition @ runestone.academy
DESIGN OF ALGORITHMS USING PYTHON 2024/25 23
Getting started with Python
• Official Python documentation: https://www.python.org/
doc/
• Python (version ≥3.6) interpreter:
• Locally: using terminal in Unix-like systems
• Lab terminals or remotely by ssh (activate afs and
shell services in self-service of DSI).
• Online repl: https://replit.com/languages/python3
DESIGN OF ALGORITHMS USING PYTHON 2024/25 24
Hello, World!
• Interactive shell
>>> print("Hello, World!")
>>>
• Script
DESIGN OF ALGORITHMS USING PYTHON 2024/25 25
Developing in Python
• Integrated development environments (IDE):
• WING - https://wingware.com
• PyCharm - https://www.jetbrains.com/pycharm/
• Visual Studio Code - https://code.visualstudio.com/
• Installing modules:
pip install …
• Visualizing execution
https://pythontutor.com/visualize.html
•…
DESIGN OF ALGORITHMS USING PYTHON 2024/25 26
27
Objectives - weeks 1 & 2
• To review the ideas of computer science,
programming, and problem-solving.
• To understand abstraction and the role it plays in the
problem-solving process.
• To understand and implement the notion of an abstract
data type.
• To review the Python programming language.
DESIGN OF ALGORITHMS USING PYTHON 2024/25 28
Introduction
Class 01
• Introduction to Algorithms and
Data Structures
• Organization of the course
• Python essentials
• Programming language
elements
• Built-in Data Types
• Input-Output
29
Programming language elements
• Elements for defining a programming language:
• Syntax - describes the possible combinations of symbols
that form a syntactically correct program
• Types- define how values and expressions are classified into
types, and what is their meaning - how data is manipulated
and interacts, according to their types.
• Semantics (Dynamic) - describes the meaning of programs
- how to execute them, what is their value or effect.
DESIGN OF ALGORITHMS USING PYTHON 2024/25 30
Syntactic components
- Expressions and Statements representation
of data
• Expressions evaluate to a value. They can be:
• atomic
• literal (number, logical value, string, …) processing
• name (identifier) reference of data
•… to data
• compound (combination of expressions)
• collection of expressions (tuple, list, dictionary…)
• operation on expressions
• function call (function name and argument expressions)
• method attribute reference (object, method name and
argument expressions)
• field attribute reference (object and field name)
•… 31
SYNTACTIC COMPONENTS - EXPRESSIONS
Literal
• Literals are values that are expressed “as themselves". They can be:
• Number
integer (2016, -2, 63767545888771622210228887333),
floating point in decimal notation (2.0, -2.0, +2.0,
0.00000000000000000000000000001), floating point in
scientific notation (10e-12)
• Logical value
True, False, …
• String
'Hello world', "Hello", "H", …
SYNTACTIC COMPONENTS - EXPRESSIONS 32
Name
• Names are sequences of letters, underscores or digits
which don’t start with a digit
• xpto, Xpto2, Taxa_de_Juro, _largura, …
• (except keywords)
• Names identify computational objects and refer to values
in memory
SYNTACTIC COMPONENTS - EXPRESSIONS 33
Operation with expressions
• Arithmetic operations (+, -, *, /, **,… )
-5, -(5), 2012-1958, 3*24+12, 3*(24+12),
3.0*(24+12), 23/7*5 + 12.5, 7//2, …
• Relational operations (==, !=, >, <, >=, <=) and
logical operations and, or, not)
not False, 7>12, …
• String operation (+, … )
"Hello"+"world", …
•…
SYNTACTIC COMPONENTS - EXPRESSIONS 34
Function call
• Similar to applying a math function on some arguments,
like f(3), but has a computational meaning:
• besides returning the value of f(3), the call can
produce side effects.
• functions can receive and return any type of values
• print(), type()
SYNTACTIC COMPONENTS - EXPRESSIONS
Attribute reference
• Python's object-oriented programming paradigm:
• Data is structured into Classes
• data items are objects
• an object is an instance of a class
• Classe's attributes describe its object's state (fields)
and behavior (methods)
l.append(3) method
object and argument
SYNTACTIC COMPONENTS - EXPRESSIONS
Syntactic components
- Expressions and Statements
• Statements are instructions that when executed can
produce a side effect. They can depend on the
evaluation of expressions:
• expression (for example a function call, like print())
• assignment (=) for moving data
• control-flow changing statements (next class)
• class definitions (next week)
SYNTACTIC COMPONENTS - STATEMENTS 37
Assignment
• An assignment statement sets and/or re-sets the value
stored in the storage location(s) denoted by a variable name or
field attribute; in other words, it copies a value into the variable.
• It is a fundamental construct in most imperative programming
languages.
REFERENCE = EXPRESSION
• Execution:
• expression is evaluated value assigned to
• then the returned value is associated to the reference (name
or field attribute)
SYNTACTIC COMPONENTS - STATEMENTS 38
Assignment
• Not to be confused with equality (==)
message = "What's up, Doc?"
n = 17
pi = 3.14159
• Assignment statements create new references when
they don't already exist in the name space.
SYNTACTIC COMPONENTS - STATEMENTS 39
Data types, classes, objects
• Python supports the object-oriented programming
paradigm => data is the focal point of the problem-solving
process.
• A class is a description of what the data look like (the state)
and what the data can do (the behavior). Classes work
similarly to abstract data types because a user of a class
only sees the state and behavior of a data item.
• Data items are called objects in the object-oriented
paradigm. An object is an instance of a class.
DESIGN OF ALGORITHMS USING PYTHON 2024/25 40
Data types
• Data types provide an interpretation for data. They are
sets of values and operations on them
• Primitive data types:
• Atomic (integer, floating point, boolean…)
• Collection (string, tuple, list, dictionary, set)
• User defined data types:
• Defining Classes (next week)
PRIMITIVE DATA TYPES 41
Primitive Atomic Data Types
• Integer (int)
• Floating point (float)
• Boolean (bool)
• None (NoneType)
•…
PRIMITIVE DATA TYPES 42
Primitive Collection Data Types
• Examples: sequence heterogeneous
• string "elements"
• tuple ("e","l","e","m","e","n","t","s")
• list ["e","l","e","m","e","n","t","s"]
• set {"e","l","m","n","t","s"}
• dictionary {"e":3,"l":1,"m":1,"n":1,"t":1,"s":1}
mutable
PRIMITIVE DATA TYPES 43
Sequences
• Sequences are data types composed of elements that take a
particular order from left to right (strings, tuples, lists)
• Operations that apply to any sequence:
PRIMITIVE DATA TYPES 44
Tuples ("e","l","e","m","e","n","t","s")
• Tuples are finite immutable sequences of 0 or more values
• Type: tuple
PRIMITIVE DATA TYPES 45
Tuples
#try!
• Immutability
t1=(1,2,3)
t2=t1
t2=t2+(5,6,7)
t2[:-1]
t2=t2[:-1]
• Disambiguating one-element tuples
(2,)
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Strings "elements"
• Strings are finite immutable sequences of 0 or more characters
• Type: str
• Characters are represented
internally as numeric code
(UTF-8, which includes ASCII)
• ord(char)
returns code of a character
• chr(code)
returns string for a code #try!
>>> ord('c') >>> s='Hello, World!'
99 >>> s.split(',')
>>> chr(99) ['Hello', ' World!']
'c'
PRIMITIVE DATA TYPES 47
Strings
#try!
• Immutability s1=“123”
s2=s1
s2=s2+"567"
s2[:-1]
s2=s2[:-1]
• Python offers several ways to perform string formatting
which is useful in printing.
DESIGN OF ALGORITHMS USING PYTHON 2024/25
String formatting
• String method format - makes substitutions into a format
string that is embedded closed braces.
Each '{}' is replaced by the next value of an expression taken from
the parameter list for the format method.
#try!
person = input('Your name: ')
greeting = 'Hello {}!'.format(person)
print(greeting)
from math import pi
print('{:.2f}'.format(pi))
print('{:.6f}'.format(pi))
DESIGN OF ALGORITHMS USING PYTHON 2024/25
f-strings
• Allow to use proper variable names instead of placeholders.
• Formatting conversion symbols are the same as those used
with placeholders, but the alignment symbols are different.
person = input('Your name: ')
greeting = f"Hello {person}!"
print(greeting)
from math import pi
print(f"{pi:.2f}")
print(f"{pi:.6f}")
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Lists ["e","l","e","m","e","n","t","s"]
• Lists are finite mutable sequences of 0 or more values
• mutable - it is possible to change, eliminate and add
elements
• heterogenous - the elements of a list can have any type
and for any one list, the items can be of different types.
PRIMITIVE DATA TYPES 51
Lists
• Mutability
#try!
l1=[1,2,3]
l2=l1
l2.extend([4,5,6])
l2=l2+[7,8,9]
l2[:-1]
del(l2[-1])
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Lists
• Copying
Shallow and deep copying of lists
#try!
import copy
l1=[[1,2,3],[5]]
l2=l1.copy() #shallow copy
l3=copy.deepcopy(l1) #deep copy
l1[0][1]=“ola”
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Sets {"e","l","m","n","t","s"}
• Sets are finite mutable unordered collections of zero or more
immutable Python data objects
• Sets do not allow duplicates. The empty set is written set().
• Type: set
PRIMITIVE DATA TYPES 54
Dictionaries {"e":3,"l":1,"m":1,"n":1,"t":1,"s":1}
• Dictionaries are
collections of
associated pairs of
items that map keys to
values, written as
key:value.
>>> d["e"]
• Index by keys 3
• Keys must be immutable
• Type: dict
PRIMITIVE DATA TYPES 55
Dictionaries
• Copying
Shallow and deep copying of
dictionaries
#try!
import copy
d1={"one":[1,2,3],"another":[5]}
d2=d1.copy() #shallow copy
d3=copy.deepcopy(d1) #deep copy
DESIGN OF ALGORITHMS USING PYTHON 2024/25
Between Data Types
• Overloading: The same notation can be used for different
operations on different data types
1+2 vs. 1.0+2.0 vs "Hello"+"World"
• Coercion: Types can be implicitly converted to fit
operation
4+7.3
• Casting: Types can be converted
round(3.4), int("3"), float(2)
PRIMITIVE DATA TYPES 57
Input and Output
• Function for reading input: input() or
input(string)
• Returns the string inputted by the user
s=input('Write something\n\t ->')
• Function for printing output: print(string,…)
• Prints the arguments
print("You wrote ", s) or
print("You wrote {}".format(s))
PYTHON ESSENTIALS 58
Homework
• Make sure you have Python version ≥3.6
• Register @ Runestone Academy into courses AlgPy-2425 and AlgPy-Intro-2425
• Reading and exercises:
• AlgPy-2425 - Chapter 1, Sections 1.1-1.9
• AlgPy-Intro-2425 - Recommended exercises @ course's webpage Section
"Practical Classes", Fenix
• More Python?
• AlgPy-Intro-2425 - Chapters 1-3, Sections 9.1-9.7, 9.9, 10.1-10.16, 12.1-12.2,
12.4-12.6, Appendix "Using Python in an IDE"
• Videos: Introduction 1 - 11 @ https://gjenkinsedu.com/pyds/videos/
DESIGN OF ALGORITHMS USING PYTHON 2024/25 59