Python_courses_in_English-4
Python_courses_in_English-4
ALGORITHMIC FUNDAMENTALS
CHAPTER 1
Algorithmic Fundamentals
1.1 Introduction
In this opening chapter, we will introduce the fundamental principles of algorithmics. We will
explore how, by beginning with a real-world problem, we can formulate a solution in the form
of an algorithm.
Definition 1.1
Computer science relies on two fundamental and complementary aspects: hardware, which
corresponds to the machine or computer, and software/programs, which describe the operations
to be carried out on the machine.
Definition 1.2
Program: is a specific set of structured and ordered operations that describe an information
processing task to be executed by a computer.
To write a program, one uses a programming language, and the technique of creating programs
is called programming. It involves the creation of computer programs and software, which will
subsequently be executed on the computer.
Definition 1.3
Definition 1.4
• Compilation: Compilation involves translating the entire source code at once. The compiler
reads the entire program and produces a new set of code known as object code, which
can now be executed by the computer. Languages like C, C++,Pascal are examples of
compiled languages.
• Interpretation: Interpretation involves translating the program line by line into a few
machine language instructions, which are then executed directly. Lisp, Prolog are
examples of interpreted languages.
Definition 1.5
Algorithm: It is an ordered and finite sequence of instructions that outlines the steps to
follow in solving a problem.
According to this definition, it’s clear that an algorithm does not solve the problem itself; rather,
it provides a series of steps. If these steps are followed correctly, they will ultimately lead to a
solution for the problem.
Definition 1.6
1. Find a Safe Spot : First, pull over to a safe location away from traffic. Ensure your hazard
lights are on;
2. Gather Tools : Locate your spare tire, jack, and lug wrench;
3. Loosen Lug Nuts: Using the lug wrench, slightly loosen(but do not remove) the lug nuts
on the flat tire;
4. Position the Jack : Place the jack under the vehicle and lift it until the flat tire is off the
ground;
5. Fully Remove Lug Nuts : Now, you can fully remove the loosened lug nuts and take off
the flat tire;
6. Mount the Spare Tire : Place the spare tire onto the wheel bolts and hand-tighten the lug
nuts as much as possible;
7. Lower the Car : Carefully lower the car using the jack until it’s on the ground again;
8. Tighten Lug Nuts : Use the lug wrench to securely tighten the lug nuts on the spare tire;
Certainly, the preceding steps are logically ordered from 1 to 8, meaning that you cannot, for
example, install the jack after fully loosening the nuts! Furthermore, the actions are clear,
understandable, and well-defined.
Locating the necessary information and determining the required actions for solving a given
problem is the central theme of the upcoming section.
Note 1.1
In this course, we will delve into the instructions available in the programming language
Python, and we will opt to express solutions in this programming language without the
need for an intermediary algorithmic language. Additionally, despite the distinctions, we
will use the terms (algorithm/program/script) and (algorithmics/programming)
interchangeably.
The analysis step allows us to answer the following three questions to better understand the
problem:
Example 1.2. If we consider to apply this method on the previous example 1.1, we obtain the
following responses:
1. What are the necessary data/tools in this case (inputs)? => the spare tire, jack, lug
wrench;
2. What are the steps to follow to achieve the results and how to use the data/tools
(processing)?=> steps: 1, 3, 4, 5, 6, 7 and 8;
3. What are the expected results (outputs)? => result here is intuitive: we end up with a
car equipped with good tires!
The algorithm (program) writing step involves transforming the solution described in the analysis
step into a more structured form.
Therefore, based on the previous example, the algorithm should look something like this:
All data manipulated by an algorithm are considered as objects, and the operations and actions
that interact with these objects are referred to as instructions or statements. This what we
will explore in the following sections.
1.3.1 Objects
Definition 1.7
a.blaIdentifier
Definition 1.8
Syntax 1. bla
Figure 1.4: The list of keywords in the Python 3.7 programming language.
The keywords in 1.4 have specific meanings and functionalities within Python, and they cannot
be used as identifiers for variables, functions, or other user-defined objects.
b.blaConstants
Definition 1.9
A constant is an object that associates a name with a value. This value should not be
modified, and it cannot be an expression.
Note 1.2
In Python, constants are typically declared and assigned values in a module (a new file)
that is imported into the main program file. Inside the module, constants are written in
UPPERCASE LETTERS with underscores separating words. This naming convention
helps identify constants and distinguishes them from variables in the code.
Syntax 2. blabla
IDENTIFIER = value_constant
Note 1.3
c.blaVariables
Definition 1.10
A variable is an object that associates an identifier with a value, which can potentially
be modified or changed later in the program.
In Python, the variable name allows access to the content of the memory location, while its value
specifies the type of data that can be stored in that memory location (integer, float, character,
etc.).
Definition 1.11
A type describes a set of values that an object of that type can take, along with the set of
operators that can be applied to those values.
In Python, and in this chapter, we are focusing on the four basic types presented in the figure
1.5.
There are other data types in Python known as composite data types, including list, dict, and
tuple, which we will cover in the upcoming chapters. These composite data types allow you to
work with more complex and structured data in Python.
Note 1.4
A variable in Python does not have its own type; it takes on the type of the object it
references. This characteristic is known as dynamic typing or duck typing in Python.
It means that you do not need to explicitly declare the type of a variable; it is determined
by the type of object it currently holds. This dynamic typing allows for flexibility and ease
of use in Python.
Note 1.5
In Python, the bool type is, in fact, a form of the int type. The boolean value True
corresponds to the integer value 1, and the boolean value False corresponds to the integer
value 0.
1.3.2 Expressions
Definition 1.12
Expressions are composed of objects (constants, variables, values) and/or functions called
operands, linked together by operators. An expression yields a value as a result after its
evaluation.
In this chapter, we present the basic operators that apply to the fundamental data types
mentioned above. These operators are represented in the table below: 1.1.
Note 1.6
Python has other types beyond the basic types presented in this chapter, and accordingly,
they have their own set of operators. We will explore these types in the upcoming chapters.
Therefore, expressions, depending on the operators used, can be either arithmetic expressions or
logical expressions.
Note 1.7
Parentheses and functions (to be discussed later) are considered primary operators.
Logical expressions are evaluated using truth tables, as shown in Figure 1.7.
Figure 1.7: The truth tables for the operators and, or, and not.
a. Well-formed expression
For a correct evaluation of the expression, it must be well-written and well-formed. If the
expression contains multiple operands and operators, it is better to organise them using
parentheses according to the intended meaning of the expression. It’s also important to respect
the operator-operand association according to their application, as shown in the table. 1.1.
A well-formed expression has a type that depends on the evaluation rules of the expression.
while the intention might have been to calculate 5 + 3 first and then multiply the result
by 2. It is best to use parentheses to clarify the order of evaluation.
Note 1.8
As we mentioned in Remark 1.5, True and False represent the values 1 and 0, respectively.
Therefore, True + False yields 1, and True > False yields True. Ex: T rue ∗ 5 = 5
b. Evaluation rules
In algorithmics, various operators are ranked by order of precedence. In an expression, operators
with higher precedence are evaluated before those with lower precedence. When two operators
have equal precedence, evaluation proceeds from left to right.
In algorithmics (Python), operators are prioritised according to the following list, starting with
the highest priority, and operators on the same line have equal priority.:
1. Parentheses ( );
2. power **;
3. the least unary, the most unary ;
4. *, /, //, % ;
5. +, -;
6. in, not in, >, >=, <,<=, ==, !=;
7. not;
8. and;
9. or.
Solution: see Figure 1.8 for the expression E1, and Figure 1.9 for the expression E2. The
evaluation of expression E3 gives -4.0.
Definition 1.13
The assignment statement " = " corresponds to the operation of assigning a value to a
variable.
Syntax 5. blabla
variable = other_variable
variable = value
variable = constant
variable = expression
Principles: blabla
Note 1.9
In Python, assignment can be written in a contracted form. See the table 1.2.
Definition 1.14
A data output statement corresponds to the operation of displaying the values of variables
after processing.
The output will be shown on the screen or on an output device. This instruction also enables
the display of messages (strings).
Syntax 6. blabla
• print(variable)
• print(variable1, variable2,. . . , variable_n)
• print(’ message’) ; print("message")
• print (value)
• print(constant)
• print(expression)
Definition 1.15
A data input statement corresponds to the operation of entering values and assigning them
to variables.
The input is collected through the keyboard or another data input device. Subsequently, the
entered value is stored in a designated memory location.
We can use the input() function with empty parentheses or provide it with an explanatory
message as an argument for the user.
Syntax 7. blabla
Note 1.10
If we desire a numeric value from the user, we must convert the entered data into a numerical type
of our choice using predefined and integrated functions and methods. This will be elaborated
upon in the following section.
To input numeric values, we use the input() function to get a string input from the user. However,
since we need this input to be in a numeric format, such as an integer or a floating number, we
must convert it using the int() or f loat() functions, respectively. This conversion ensures that
the input is treated as a numeric value rather than a string.
Syntax 8. blabla
Note 1.11
Python provides the type() function, which returns the type of an object.
Figure 1.10 illustrates the execution in the console (shell) of both instructions with and without
type conversion, and demonstrates the resulting data types for each instruction.
Although Python has other predefined functions that belong to Python’s standard library, such
as:
1. len() which returns the length of a string (the size of an object of type str);
2. min() and max() which respectively return the smallest and largest element from a set of
data or variables;
3. abs() which returns the absolute value of its argument;
Note 1.12
The Python standard library contains numerous modules that offer many other functions.
To use these functions, you must first import them using the command: import.
Syntax 9. blabla
Among the available modules, we are interested in the math module, which contains mathematical
functions such as square root: sqrt(), cosine: cos(), sine: sin(), etc.
1.4 Exercises
In this section, we will delve into comprehensive solutions for a few straightforward problems.
Exercise 1.1. Write an algorithm that calculates the distance between two points A and B on
a Cartesian plane.
To calculate the distance between two points A and B on a Cartesian plane, we can use the
Pythagorean theorem. Here’s an analysis of the problem:
Problem analysis:
Note 1.13
In a Python editor, you can choose your mode of writing the program, either in the script
window or in the console (shell).
The script window in a Python editor is where programmers write their code, which can be
saved and modified.
The console (shell) is where the program runs, and users enter inputs requested by the program.
For the Python code in the script window and its execution in the console, please refer to the
Figure 1.11.
Exercise 1.2. Create an algorithm to compute the areas and perimeters of a rectangle and a
circle. Extend this solution to determine the surface area and volume of a cylinder with the
circle as its base.
Note 1.14
Problem analysis :
We need to break down the problem into sub-problems and solve each of them separately, then
combine them into the final solution.
• Inputs : enter the length and width of the rectangle (l, w), and the radius of the circle (r);
• Processing :
+ Calculate the area of the rectangle: ra = l ∗ w
+ Calculate the perimeter of the rectangle: rp = 2 ∗ (l + w)
+ Calculate the area of the circle: ca = r ∗ ∗2 ∗ P i
+ Calculate the circumference (perimeter) of the circle: cp = 2 ∗ r ∗ P i
• Inputs : For the volume, we require the base surface area (ca) and the height (H). For
the surface area, we need both the base surface area (ca) and the side surface area (cs),
which is a rectangular strip with a width of H and a length equal to the perimeter of the
circle (cp).
• Processing:
+ Lateral surface area: lsa = 2 ∗ ca + H ∗ pc
+ Volume: cv = ca ∗ H
Python implementation of the solution : see the code in Listing 1.2 and execution console
in Figure 1.13.
Note 1.15
In Figure 1.13 we notice that the results consist of real numbers with multiple digits after
the decimal point. To round these results and display them with precision to two decimal
places for example, we can employ the round() method.
2. round(21.1234567) → 21 bla in this case the method rounds to the nearest integer (21)
Exercise 1.3. Consider the following problems along with their analyses. You are tasked with
writing their corresponding algorithms.
1. Analysis of the problem which reads the concentration of a chemical solution and provides
its pH.
Problem analysis :
• Inputs : concentration c;
• Processing : ph = −log10 (c) ;
• Outputs : display the result: ph ;
2. Analysis of the problem that enables the conversion of a quantity into moles:
Problem analysis :
3. Analysis of the problem that converts a temperature in degrees Celsius to degrees Fahrenheit
. Problem analysis :
4. Analysis of the problem that determines the components X and Y of a vector V based on
its magnitude and the angle (expressed in degrees) relative to the horizontal axis.
Problem analysis :
5. Analysis of the problem which reads the components x and y of a vector V and calculates
its magnitude.
Problem analysis:
6. Analysis of the problem which reads the coordinates of points A and B, and calculates the
coordinates of the midpoint of the segment connecting them.
Problem analysis:
7. The analysis involves reading a time duration provided in hours, minutes, and seconds, and
then converting it into seconds.
Problem analysis :
8. The analysis involves reading the coordinates of two points, A(Ax, Ay) and B(Bx, By), and
then determining the equation of the line that passes through both points.
Problem analysis :
9. Analysis of the problem that reads a four-digit number and decomposes it into thousands,
hundreds, tens, and units.
Problem analysis :