0% found this document useful (0 votes)
2 views

Python_courses_in_English-4

Uploaded by

amina.rahil.123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python_courses_in_English-4

Uploaded by

amina.rahil.123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

CHAPTER 1.

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.

1.2 Fundamental Concepts


The term "informatics" is the word that characterises the automated and rational processing of
information. It is formed by the contraction of the expression "automatic information."

Definition 1.1

Informatics: also know by computer science, it is the science of automated information


processing.

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

Programming: it is the activity of writing the source code for a program.

UFAS 1st Class Common-Trunk in ST blalalablabl1 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.2. FUNDAMENTAL CONCEPTS

Definition 1.4

Programming Language: is a computer language that enables a human (programmer)


to write source code that will be analysed and executed by a computer.

Programming is considered the culmination of a series of steps.


The process illustrated in Figure 1.1 represents the production chain of a program. In this
process, algorithmics and algorithms constitute its most critical phase. This is because an
algorithm expresses the logical structure of a computer program, which will be translated into
the chosen programming language.
On the other hand, the process illustrates the various modes of executing a source program,
which are:

• 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.

• Semi-compilation: Semi-compilation is the combination of both techniques to leverage the


strengths of each. This is the case with languages like Python, Java for example.

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

Algorithmics: It is the set of methods used to define and/or study algorithms.

UFAS 1st Class Common-Trunk in ST blalalablabl2 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.2. FUNDAMENTAL CONCEPTS

Figure 1.1: The programming process: various execution paths.

Example 1.1. Changing a flat tire on a car,


the following 8 steps explain how to change a
flat tire :

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;

UFAS 1st Class Common-Trunk in ST blalalablabl3 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

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.

1.3 My First Algorithm

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.

As mentioned earlier, an algorithm is a sequence of steps to follow in order to solve a problem.


The process of solving the problem begins with a study that involves extracting modelling
elements from the problem statement; this is what we call problem analysis.
Problem analysis (see Figure 1.2) involves explaining the resolution method, which means
outlining the steps to follow, starting from the data and leading to the desired results while
adhering to a specific order.

Figure 1.2: The analysis process.

UFAS 1st Class Common-Trunk in ST blalalablabl4 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

The analysis step allows us to answer the following three questions to better understand the
problem:

1. What are the necessary data (inputs)?


2. What are the steps to follow to achieve the results and how to use the data (processing)?
3. What are the expected results (outputs)?

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!

Example 1.3. Calculate the average of two numbers:


1. Add the two numbers together.
2. Divide the sum by 2.
The result of this calculation will be the average of the two numbers. If we answer the three
questions, we will have the following responses:

1. Data Needed (Inputs): Two numbers, let’s call them X and Y ;


2. Steps for Calculation (Processing):

• Add x and Y together: (X + Y );


• Divide the sum by 2: M = (X + Y )/2.

3. Expected Results (Outputs): The average of the two numbers: M .

The algorithm (program) writing step involves transforming the solution described in the analysis
step into a more structured form.

Figure 1.3: The general form of an algorithm/program.

Therefore, based on the previous example, the algorithm should look something like this:

UFAS 1st Class Common-Trunk in ST blalalablabl5 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

• Inputs: Read or input the data; provide values for X and Y .


• Processing: Perform operations on the data; calculate the average M using the values of
X and Y .
• Outputs: Display and write the results; display the value of M .

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 data object is a fundamental structure in a programming language that holds information


or values. It can represent numbers, text, lists, or other types of information used in a
program.

Example 1.4. bla


120 is a data object that represents an integer number.
hello is a data object that represents a text.

a.blaIdentifier

Definition 1.8

An identifier is used to give a name to an object, allowing it to be distinguished from


other objects.

Syntax 1. bla

• We call a character a symbol or character from a sequence of characters, such as letters,


numbers, or special symbols ′ a′ ..′ z ′ ,′ A′ ..′ Z ′ , ’_’;
• We call a digit a character from ’0’ to ’9’;
• An algorithmic identifier (in Python) is a sequence of letters or digits concatenated together,
of any length, starting with a letter;
• An identifier must not contain a special character (’ ’, >,<, !, ?, +,-,...), except the
underline symbol ’_’;
• An identifier must be different from a keyword or reserved word (used by the system).
Refer to Figure 1.4 for the list of reserved keywords in Python 3.7;
• An identifier must be unique within an algorithm;

UFAS 1st Class Common-Trunk in ST blalalablabl6 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

• Ideally, an identifier should be meaningful;


• Uppercase and lowercase characters are distinct.

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.

Example 1.5. bla

Valid Identifiers : x, Y1, day, month, note, address, Student_name, NbColours


Invalid Identifiers : 1x, nb colours, , if
Distinct Identifiers : note, Note
Valid Identifiers (with special meaning): true, false
Note that these are valid identifiers but have different meanings than the reserved keywords
’True’ and ’False’ (see Figure 1.4).

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.

UFAS 1st Class Common-Trunk in ST blalalablabl7 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

Syntax 2. blabla
IDENTIFIER = value_constant

Example 1.6. bla


PI = 3.14 ; GRAVITATION = 10

Note 1.3

A non-numeric constant, such as a character or a string( set of characters), is enclosed


either in single quotes (’ ’) or double quotes (" "). For example: RHESUS = ’O_positif’.
GENDRE = "man", SIGN = ’+’

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.).

Syntax 3. blabla identifier = value

Example 1.7. blabla


name = "mohamed"
note = 15
note = 17.5 (in the statement we have modified the value associated with the variable ’note’.
We have assigned the new value ’7.5 to the ’note’ variable.

d.bla Predefined Basic Data Types

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.

UFAS 1st Class Common-Trunk in ST blalalablabl8 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

Figure 1.5: The basic data types in Python 3.7.

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.

Example 1.8. blabla


x = 3 blabla → x is of type int.
x = 4.5 blabla → x has become of type float.
x = ’hello’ bla → this time, x has become of type str.

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.

UFAS 1st Class Common-Trunk in ST blalalablabl9 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

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.

An operator can be binary or unary, as shown in the Figure 1.6

Figure 1.6: Basic Types of Python 3.7 Language


Syntax 4. blabla
For binary operators that act on two operands:

• operand1 operator operand2, ex : X+Y, Z< 5, not (A and B) or C.

For unary operators that act on one operand:

• operator operand, ex : cos (x).

Therefore, expressions, depending on the operators used, can be either arithmetic expressions or
logical expressions.

• Arithmetic expressions: The evaluation of this type of expression yields a numeric


value; they use arithmetic operators. ex: ‘2 * X + Y - Z‘.
• Logical expressions: The evaluation of this type of expression yields a Boolean value
(True or False); they use logical or comparison operators. Ex: ‘(X > Y) and (X < Z)‘,
‘((A and B) or not(C))‘.

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.

UFAS 1st Class Common-Trunk in ST blalalablabl10 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

Domain Operation Signification Types Example Result


+ addition 5+7 12
− subtraction 6−4 2
∗ multiplication 2∗7 14
Arithmetic ∗∗ exponential (power) int, float, bool 2 ∗ ∗3 8
/ division 7/3 3.5
% remainder of division(modulo) 7%3 1
// quotient 7//3 2
+ concatenation ’grand’ + ’father’ grandfather
∗ repetition ’ab’ ∗ 3 ababab
String str
in membership ’a’ in ’year’ True
not in non-membership ’a’ not in ’ month’ False
and logical And x and y
Logical or logical Or bool x or y see Figure 1.7
not logical Not not x
> superiority: greater 6>5 True
< inferiority: less 6<5 False
Relational == equality: equal 6 == 6 True
int, float
comparison <= less than or equal to 6 <= 6 True
>= greater than or equal 5>= 6 True
!= not equal 6 != 5 True

Table 1.1: Fundamental Operations and Expressions.

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.

Example 1.9. blabla

• 5 +’ab’ * 3 : It is an ill-formed expression, we cannot apply the arithmetic operators +


and ∗ to numeric operands and a string.
• 5 + 3 ∗ 2 : This is an example of an ill-formed expression because it yields a result of 11

UFAS 1st Class Common-Trunk in ST blalalablabl11 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

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.

Example 1.10. blabla


E1= 4+8*2-6*(4+3)/ 3 // 3 % 3 *(16 % 9 % 4)
E2= (10>3) or (12+2*3>16-8/4) and not (18 // 2 // 3 == 21 // 3 % 3)
E3=4+8*2-6*4+3/ 3 // 3 % 3 *16 % 9 % 4

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.

UFAS 1st Class Common-Trunk in ST blalalablabl12 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

Figure 1.8: Evaluation of the expression E1.

Figure 1.9: Evaluation of the expression E2.

1.3.3 Assignment: assigning values to variables


The assignment statement allows you to assign a new value or modify the values of data
referenced by variables. The value can be a constant, an immediate value, an expression to be
evaluated, or another variable. The value will also be stored in a memory location.

Definition 1.13

The assignment statement " = " corresponds to the operation of assigning a value to a
variable.

UFAS 1st Class Common-Trunk in ST blalalablabl13 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

Syntax 5. blabla
variable = other_variable
variable = value
variable = constant
variable = expression

Example 1.11. blabla


X=Y
Z=5
If you want to place multiple statements on the same line, you should separate them with a
semicolon ’;’.
Y = X + Z – 2; T = True; P = ’S’

Principles: blabla

• The assignment statement, noted as (X = Y), is read as: X receives Y or X is assigned


the value of Y ;
• It can be observed that assignment has two parts, with its left-hand side always representing
a variable, while the right-hand side can be a value, a variable, or an expression ;

Note 1.9

In Python, assignment can be written in a contracted form. See the table 1.2.

Form Example Equivalent to


= x=5 x=5
+= x += 5 =x+5
-= x -= 6 x=x-6
*= x *= 4 x=x*4
/= x/= 8 x=x/8
//= x //= 5 x = x // 5
%= x%5 x=x%5
**= x** = 2 x = x**2

Table 1.2: Main assignments in Python.

In Python, we can assign a value to multiple variables simultaneously.

Example 1.12. blabla


x = y = z = 4 blablablabla all variables receive the same value 4.

You can also perform parallel assignments using a single operator.

Example 1.13. blabla


x , y , z = a, ’hello’, 5 blablaEquivalent to x = a; y =′ hello′ ; z = 5

UFAS 1st Class Common-Trunk in ST blalalablabl14 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

1.3.4 Input/Output Instructions (I/O)


In this section, we will explore two types of instructions that work with fundamental objects
and facilitate a form of interaction with the user of our algorithm or script: namely, print and
input.

a. blablaThe output statement (print)

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)

Example 1.14. blabla


print( X, Y); print(10); print(’ programming course ’); print(X + Y - 3); print(’My name is: ’,
name)

b. blablaThe input statement (input)


In a program, it is highly useful to be able to request user enter (input) for data.

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.

UFAS 1st Class Common-Trunk in ST blalalablabl15 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

Syntax 7. blabla

• Form 1: blabla name = input()


• Form 2: blabla name = input(”Enterbyourbnamebplease : ”)

Note 1.10

In Python 3, the input() function always returns a string.

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.

1.3.5 Predefined Methods and Functions


Python includes a wide array of predefined methods and functions, which are part of the Python
Standard Library, consisting of numerous modules. The two instructions we have already
encountered, input() and print(), are examples of such predefined functions.

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

• Enter an integer value: blabla x = int(input());


• Enter a floating value: blablaa y = f loat(input());

Example 1.15. blabla


name = input (’ Enter your name :’)
age = int( input(’How old are you ?’))
height = float(input(’What is your height ?’))

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.

UFAS 1st Class Common-Trunk in ST blalalablabl16 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.3. MY FIRST ALGORITHM

Figure 1.10: int() and type() functions.

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

• To import the module:blablablablimport module_name


• To use the imported module :blabla identif ier = module_name.f unction()_name

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.

Example 1.16. blabla


import blmath
x = math.sqrt(9)blablabla which means x = 3

1.3.6 Trace of execution and debugging


Debugging, involving the manual execution of the script step by step with the trace of execution,
is not a part of the algorithm itself. However, it is crucial for verifying whether the script
produces the desired results.

UFAS 1st Class Common-Trunk in ST blalalablabl17 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.4. EXERCISES

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:

• Inputs : Get the coordinates of points A(ax, ay) and


B(bx, by);
• processing : D= square_root((bx - ax)**2 + (by -
ay)**2) ;
• Outputs : The distance variable D will contain the
distance between points A and B;
Python implementation of the algorithm: (see Listing 1.1).
1 import math
2 # inputs
3 ax = float ( input ( " Enter the x - coordinate of point A : " ) )
4 ay = float ( input ( ’ Enter the y - coordinate of point A : ’) )
5 bx = float ( input ( ’ Enter the x - coordinate of point B : ’) )
6 by = float ( input ( ’ Enter the y - coordinate of point B : ’) )
7 # Calculate the Distance
8 distance = math . sqrt (( bx - ax ) **2 + ( by - ay ) **2)
9 # the result or outputs
10 print ( " the distance between points A and B = " , distance )

Listing 1.1: Calculating the distance between two points.

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.

UFAS 1st Class Common-Trunk in ST blalalablabl18 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.4. EXERCISES

Figure 1.11: Script: Calculating the distance between two points.

The trace of execution:


Code lines in the program are sequentially numbered from the first instruction to the last,
excluding comments. The execution follows this numerical order, as illustrated in the table
below:(see Figure 1.12)

Figure 1.12: Trace of execution of the script 1.1.

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

Breaking down a complex problem into simpler sub-problems is a very common


approach in programming and problem-solving in general.It makes the solution more
modular and easier to understand. Each sub-problem can be tackled separately before
combining them to obtain the final solution.

UFAS 1st Class Common-Trunk in ST blalalablabl19 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.4. EXERCISES

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.

The first sub-problem consists of calculating the


perimeters and areas of objects (rectangle and
circle).

The second sub-problem is to calculate the sur-


face area and volume of the cylinder based on
the solution found for the first problem.

For this problem, here is how we can organise the resolution:


Sub problem 1: Calculations of perimeters and areas of the rectangle and the circle.

• 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

• Outputs : display the results: ra, rp, ca, cp.

Sub problem 2 : Calculations of the surface and volume of the cylinder.

• 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

• Outputs : display the results: lsa, cv

Python implementation of the solution : see the code in Listing 1.2 and execution console
in Figure 1.13.

UFAS 1st Class Common-Trunk in ST blalalablabl20 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.4. EXERCISES

1 # A script that performs geometric calculations on a rectangle , a circle ,


and a cylinder .
2 import math
3 # Inputting data for sub - problem 1.
4 l = float ( input ( ’ Provide the length of the rectangle : ’) )
5 w = float ( input ( ’ Provide the width of the rectangle : ’) )
6 # Calculation of the area and perimeter of the rectangle
7 ra = l * w
8 rp = 2*( l + w )
9 # Displaying results
10 print ( ’ The perimeter = ’ , rp , ’ and area = ’ , ra )
11 r = float ( input ( ’ Provide the radius of the circle : ’) )
12 # Calculation of area and perimeter of the circle
13 cp =2* r * math . pi
14 ca = r **2* math . pi
15 # Displaying results
16 print ( ’ The perimeter = ’ , cp , ’ and the area = ’ , ca )
17 # Inputting data for sub - problem 2
18 H = float ( input ( ’ Enter the height of the cylinder : ’) )
19 # Calculation of the surface area and volume of the cylinder
20 lsa = 2* ca + H * cp
21 cv = ca * H
22 # Displaying results
23 print ( " The surface area of the cylinder = " ,lsa , ’ and its volume = ’ , cv )

Listing 1.2: geometric calculations.

Figure 1.13: Code execution console 1.2.

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.

Syntax 10. blabla


round(number, number_of_decimal_places)

UFAS 1st Class Common-Trunk in ST blalalablabl21 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.4. EXERCISES

Example 1.17. blabla

1. round(3.26957845331 , 2 ) → 3.27 blabla rounds to two decimal places

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 :

• Inputs : quantity n, number of Avogadro N a = 6.02214076 ∗ 1023 ;


• Processing : number of moles: nm = n/N a ;
• Outputs : display the result : nm ;

3. Analysis of the problem that converts a temperature in degrees Celsius to degrees Fahrenheit

. Problem analysis :

• Inputs : Celsius temperature C;


• Processing :Fahrenheit temperature: F = (C ∗ 9/5) + 32 ;
• Outputs : display the result : F ;

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 :

• Inputs : magnitude n, angle θ;


• Processing : convert θ to radians: θ = θ ∗ 3.14/180
blablavector’s components : x = magnitude∗cos(θ),
blablay = magnitude ∗ sin(θ) ;
• Outputs : display the results : x, y;

UFAS 1st Class Common-Trunk in ST blalalablabl22 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.4. EXERCISES

5. Analysis of the problem which reads the components x and y of a vector V and calculates
its magnitude.
Problem analysis:

• Inputs : Vector’s components V (Xv, Y v);


• Processing : The magnitude: m = sqrt(Xv 2 + Y v 2 );
• Outputs : display the result: m;

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:

• Inputs : Points coordinates: A(Ax, Ay), B(Bx, By);


• Processing: Segment’s midpoint coordinates:
blablaM x = (Ax + Bx)/2 , M y = (Ay + By)/2;
• Outputs : display the result : M (M x, M y);

7. The analysis involves reading a time duration provided in hours, minutes, and seconds, and
then converting it into seconds.
Problem analysis :

• Inputs : time duration: h, m, s;


• Processing: duration in seconds : ds = (h ∗ 3600 + m ∗ 60 + s);
• Outputs : display the result : ds ;
7.1. Try to resolve the reversed version of the same problem, which is converting a given
number of seconds into hours, minutes, and remaining seconds.

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 :

• Inputs : Points coordinates A(Ax, Ay)


blabla and B(Bx, By);
• Processing:
blabla slope: a = (By − Ay)/(Bx − Ax);
blabla y_intercepts: b = By − a ∗ Bx;
• Outputs : display the line’s equation :
blablay = a ∗ x + b;

UFAS 1st Class Common-Trunk in ST blalalablabl23 N. CHERGUIbla


CHAPTER 1. ALGORITHMIC FUNDAMENTALS
1.4. EXERCISES

9. Analysis of the problem that reads a four-digit number and decomposes it into thousands,
hundreds, tens, and units.

Problem analysis :

• Inputs : the number n;

• Processing : the decomposition:


blabla The number in thousands : t = n//1000;
blabla The number in hundreds: c = (n//100)%10;
blabla The number in tens: d = (n%100)//10;
blabla The number in units : u = (n%100)%10;

• Outputs : display the results : t, h, d, u;

Exercise 1.4. Convert the previously analysed problems into scripts.

UFAS 1st Class Common-Trunk in ST blalalablabl24 N. CHERGUIbla

You might also like