Download as pdf or txt
Download as pdf or txt
You are on page 1of 75

Foundations in Business Information Management

(INGE1135) - Exercises
(2024)
L. Jacquet, C. Rodriguez Ameal
Contents

1 Assignments, inputs and ouputs, and first steps with Python 1


1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Basic exercices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 First steps with Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1 Repl.it . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.2 The script editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.3 Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Console tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Writing programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2 Decision & choices in Python 9


2.1 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Reminder on booleans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.3 Basic exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4 Choice structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.5 Introduction exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.6 Writing programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

3 Data structures and loops 19


3.1 Lists and dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.1.1 Tutorial on lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.1.2 Tutorial on dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.2 Loop syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3 Tutorial on loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.3.1 While loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.3.2 For loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.4 Basic exercises : reading algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.5 Simple exercises with loops & lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.6 Writing programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.7 Advanced exercises on algorithmic complexity . . . . . . . . . . . . . . . . . . . . . . . . 34

4 Modules : procedures and functions 35


4.1 Reading algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.2 Modules in python : tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
4.3 Implementing functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.4 Small exercises on modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.5 Writing methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4.6 Writing programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

Solutions 45

i
Session 0

Python cheat sheet


Script without functions
instruction nb
# affectation else :
a = 0 # i n i t i a l i z a t i o n at 0 ; type int instruction 1c
b = 3 # b takes 3 ; type int instruction 2c
y = 5.0/2 # y takes 2.5 ; type f l o a t .
z = b //4 # z t a k e s 0 : e u c l i d i a n d i v i s o n ( whole .
.
division ) instruction nc
z = float (b/4) # z takes 0.5
a g a i n = True #t y p e b o o l ; o t h e r v a l u e : F a l s e # Loops
l i n e = " Hello " #t y p e s t r
#c o n t r o l l e d by g e n e r a l c o n d i t i o n
# s t r i n g concatenation while c o n d i t i o n :
o t h e r L i n e = l i n e + " everyone " i n s t r u c t i o n 1a
# otherLine contains ” Hello everyone ” i n s t r u c t i o n 2a
.
.
# i n p u t s and o u t p u t s .
x= f l o a t ( input ( "a float pls " ) ) i n s t r u c t i o n na
print ( " The value is : " , x )
# c o n t r o l l e d by c o u n t i n g
# Decisions : # incremental loop
# c o n d i t i o n a l s are booleans f o r i in range ( i v , f v +1) :
# the i n s t r u c t i o n b l o c s are d e l i m i t e d with the i n s t r u c t i o n 1a
indent i n s t r u c t i o n 2a
.
.
.
# conditional
i n s t r u c t i o n na
i f condition :
instruction 1
# decremental loop
instruction 2
. f o r i in range ( i v , f v −1,−1) :
. i n s t r u c t i o n 1a
.
instruction n i n s t r u c t i o n 2a
.
.
.
# alternative
i n s t r u c t i o n na
i f condition :
instruction 1a
# L i s t s and d i c t i o n n a r i e s :
instruction 2a
. # C r e a t i n g and m a n i p u l a t i n g l i s t s :
. t =[3.1415 , 2.7182] # list
.
instruction na v =[] # list
else : v [ : ] = ’ifo ’
instruction 1b print v [ 1 : 3 ]
instruction 2b print len ( v )
. import copy
.
. q=copy . copy ( v )
instruction nb d = {" Name " : " James " , " Surname " : " Bond " , " Age " : 7}
d [ " Age " ] = 37
# thrid alternative
i f condition1 : # Method r e l a t e d t o lists
i n s t r u c t i o n 1a v . pop ( )
i n s t r u c t i o n 2a v . i n s e r t ( 1 , ’n’ )
. v . extend ( [ 3 , 4 ] )
.
. v . append ( 2 )
i n s t r u c t i o n na v . reverse ()
e l i f condition2 : v . sort ()
i n s t r u c t i o n 1b w. index (2)
i n s t r u c t i o n 2b w. count ( 1 )
.
.
.

Foundations in Business Information Management (INGE1135) 1 SESSIONS - 2024


- Exercises
Session 0

Script with functions


# D e f i n i t i o n s o f modules

def aFct ( param1 , param2 , param3 ) :


#PRE : l i s t o f pa ra m et re s
#POST : d e s c r i p t i o n o f what t h e p r o c e d u r e doe s
#s t a r t o f t h e i n s t r u c t i o n s o f t h e f u n c t i o n

.
.
.

#end o f t h e i n s t r u c t i o n s o f t h e f u n c t i o n

def a n o t h e r F c t ( otherParam ) :
#PRE : l i s t o f pa ra m et re s
#POST : d e s c r i p t i o n o f t h e v a l u e t h a t i s r e t u r n e d
#s t a r t o f t h e i n s t r u c t i o n s o f t h e f u n c t i o n

.
.
.

return v a l u e #r e t u r n e d v a l u e
#end o f t h e i n s t r u c t i o n s o f t h e f u n c t i o n

.
.
.

def main ( ) :
#The main one
#s t a r t o f t h e i n s t r u c t i o n s o f t h e main

.
.
.

aFct ( paramain1 , paramain2 , paramain3 )


#The name o f t h e f u n c t i o n becomes an i n s t r u c t i o n
#t h e f u n c t i o n has no ” r e t u r n ”
#t h e same number o f arguments , o r d e r i s i m p o r t a n t

.
.
.

print ( a n o t h e r F c t ( otherParam ) )
#The f u n c t i o n can be c a l l e d i n an i n s t r u c t i o n
#t h e f u n c t i o n has a ” r e t u r n ”
#t h e same number o f arguments , o r d e r i s i m p o r t a n t

.
.
.

#end o f t h e i n s t r u c t i o n s o f t h e main

#s t a r t i n g t h e program : c a l l i n g t h e main ( )
main ( )

Foundations in Business Information Management (INGE1135) 2 SESSIONS - 2024


- Exercises
Session 1

Assignments, inputs and ouputs,


and first steps with Python

1.1 Introduction
Welcome to the Foundations in Business Information Management exercise book. We think it is impor-
tant that one understands how to decipher code without the use of a computer. So we are not diving
into the computers with python quite yet. In the following exercises, we are going to try and ”think”
like a computer. We will use states of the algorithms. They are tables that illustrate a computer’s
memory after each instruction. Here is an example :

The algorithm :
1 A = 1
2 B = A + 2
3 print ( b )

The state of the algorithm :


Next variables
instruction A B comments
1. A = 1 / / The computer begins with an empty memory. First instruc-
tion is assigning 1 to A.
2. B = A + 2 1 / A took value 1. Next instruction : we assign A+2 to B,
and we take into account that A is 1 at the moment.
3. print(B) 1 3 B took 3. A did not change. Next instruction : display B’s
value on screen.
end 1 3 3 was displayed on screen. End of the algorithm.

1.2 Basic exercices


▷ 1. What was the initial value of variable A, given that its value is 8 after executing the line A = A + 2
?

▷ 2. What is the effect of this instruction block ?


A = 1
B = 2
A = B
B = A

▷ 3. Does this instruction block have the same effect as the previous one ?
A = 1
B = 2
B = A
A = B

1
Session 1 1.2. BASIC EXERCICES

▷ 4. What value will A, B and C contain after executing this instruction block ? Give the state of the
algorithm.

1 A = 1
2 B = 2
3 C = 3
4 A = A + 5
5 B = C
6 C = A + B
7 B = 2 ∗ B

▷ 5. What value will A, B and C contain after executing the following block of instruction ? Give a state
of the algorithm.

1 A = 1
2 B = 2
3 C = A + B
4 A = C
5 C = B
6 B = A
7 A = ( 3 ∗ B) − ( 4 ∗ C)
8 B = B + 1
9 C = 2 ∗ C

▷ 6. For each pair of instruction, identify when a change in the order of the instructions can change the
state of the algorithm after the second line. Does the order of the instructions matter ? We assume
that the variables were preemptively assigned an integer.

1. xx = z z 2. z z = yy 3. xx = yy
xx = yy xx = yy z z = xx

▷ 7. Do the following instruction block have the same effect on variables xx, yy and zz ? We assume
that the variables were preemptively assigned an integer.

1. ww = yy 2. ww = zz 3. ww = zz
yy = xx zz = yy zz = xx
xx = zz yy = xx xx = yy
zz = ww xx = ww yy = ww

Foundations in Business Information Management (INGE1135) 2 SESSIONS - 2024


- Exercises
1.2. BASIC EXERCICES Session 1

▷ 8. For each pair of instruction, replace the pair of instruction by only one line so that the one line has
the same effect on the variables as the pair of instruction. Let the variables Depth, Mesure and Height
be preemptively initialized with an integer.
1. Depth = 37 − Mesure
Depth = 19 − H e i g h t

2. Bul = Groz ∗5 + 75
Bul = Bul % 5 + 17

3. Bul = B r o l + 5
Bul = Bul ∗ 2

▷ 9. Give the state of the algorithm. Then, give the specifications for it. In other words, explain what
this algorithm does. What will the algorithm display if the user gives 1, 3 and 5 ?
1 #−∗−c o d i n g : u t f −8−∗−
2 #a l g o r i t h m FaitKwa
3 #v a r i a b l e s : A, B, C, D : i n t e g e r
4
5 A = i n t ( input ( "first value A ? " ) )
6 B = i n t ( input ( "second value B ? " ) )
7 C = i n t ( input ( "third value C ? " ) )
8 print ( "Values at the start :" )
9 print ( "A == " , A)
10 print ( "B == " , B)
11 print ( "C == " , C)
12 D = B
13 B = A
14 A = C
15 C = D
16 print ( "Values at the end :" )
17 print ( "A == " , A)
18 print ( "B == " , B)
19 print ( "C == " , C)

▷ 10. Give the state of the algorithm. Then, give the specifications for it. In other words, explain what
this algorithm does. What are the differences with the previous algorithm ?
1 #−∗−c o d i n g : u t f −8−∗−
2 #a l g o r i t h m FaitKwaBis
3 #v a r i a b l e s : A, B, C, D : i n t e g e r
4
5 A = i n t ( input ( "first value A ? " ) )
6 B = i n t ( input ( "second value B ? " ) )
7 C = i n t ( input ( "third value C ? " ) )
8 print ( "Values a the start :" )
9 print ( "A == " , A)
10 print ( "B == " , B)
11 print ( "C == " , C)
12 D = C
13 C = A
14 A = B
15 B = D
16 print ( "Values at the end :" )
17 print ( "A == " , A)
18 print ( "B == " , B)
19 print ( "C == " , C)

Foundations in Business Information Management (INGE1135) 3 SESSIONS - 2024


- Exercises
Session 1 1.3. FIRST STEPS WITH PYTHON

▷ 11. Give the state of the algorithm. Then, give the specifications for it. In other words, explain what
this algorithm does.
1 #−∗−c o d i n g : u t f −8−∗−
2 #a l g o r i t h m FaitEncoreKwa
3 #v a r i a b l e s : A, B, C, D, E : f l o a t
4
5 A = i n t ( input ( "first value A ? " ) )
6 B = i n t ( input ( "second value B ? " ) )
7 C = i n t ( input ( "third value C ? " ) )
8 print ( "Values at the start :" )
9 print ( "A == " , A)
10 print ( "B == " , B)
11 print ( "C == " , C)
12 D = i n t ( input ( "What is the value of D ? " ) )
13 print ( "Value given : " , D)
14 E = (A∗ (D∗D) ) + (B∗D) + C
15 print ( "Value at the end :" , E)

1.3 First steps with Python


1.3.1 Repl.it
There are numerous ways to get acquainted with Python. We will use the website https://repl.it
for learning purposes. Go to Replit, and create a free account.

1.3.2 The script editor


To find the script editor, create a new repl (upper left of your homepage once logged in), and use the
white part of the screen to the left. This editor is where you can run the entire code once written, as
opposed to the console (black part of the screen, to the right) where you can have a direct dialogue
with the computer.

1.3.3 Tips
• It is not always easy to understand the error messages that Python returns. Your job is to learn
to react efficiently to these error messages by reading them carefully and trying to figure out what
went wrong.
• In this course, we do not ask you to find a solution to a problem. Rather, we ask you to figure out
how to solve a problem. You have to think sequentially, much like a computer does, to find the
right steps to solve the problem. Usually, there are infinite ways to solve one particular problem,
so do not be afraid if your answer is not the same as others ! Perhaps everyone is right.

• Be autonomous. Do not hesitate to use online tutorials and other such sources. Sometimes, all
you need is a different explanation from a different teacher to clarify a concept !

1.4 Console tutorial


Warning In the following exercices, you will perform tests with different basic instructions. We kindly
ask you to use the Python console and try to anticipate, or take note of the results. Unfortunately, what
you will do with the console is not savable, but the important lesson is that you familiarize yourself
with how a computer works.

Foundations in Business Information Management (INGE1135) 4 SESSIONS - 2024


- Exercises
1.4. CONSOLE TUTORIAL Session 1

Assignments and calculations


1. Describe as clearly and as completely as possible what occurs at each of the following instructions
:
1 width = 20
2 height = 5 * 9.3
3 print(width * height)

Note : Make sure that you are indeed using a dot to write a float such as 9.3, and not a comma.
A comma would create a list instead of a float. More on lists in upcoming sessions.
2. Assign 3, 5, 7 to a, b, c respectively. Predict the result of a - b/c
3. Test and describe the following instructions :
1 r , pi = 12, 3.14159
2 s = pi * r**2
3 print (s)
4 print (type(r), type(pi), type(s))

4. Focus on the ∗∗ operator. What does it do ? Which of the following instruction yields an
unexpected result ?
1 a = 2**5
2 b = 2.2**0.5
3 c = -2.2**0.5
4 d = (-2.2)**0.5
5 print(a)
6 print(b)
7 print(c)
8 print(d)

5. Are the instructions : a=b et b=a equivalent ?


6. Predict the results of the following instructions :
1 a=15
2 print (a/2)
3 print (a//2)
4 b=15.0
5 print (a+b/2)
6 print ((a+b)/2 )
7 print (type(a)==type(b))
8 print (a%2)

7. What does the // operator do ?


8. What is the difference between these two instructions b = a*a and b = aa ?

Inputs and outputs


1. Write the following instruction
1 a=input("Hello, what is your name ? ")

What is the value of a. What is its type ? What is the role of the input instruction and of its
argument ?
2. Write the following instruction
1 a=input("How old are you ? ")

Foundations in Business Information Management (INGE1135) 5 SESSIONS - 2024


- Exercises
Session 1 1.4. CONSOLE TUTORIAL

What is the value of a. What is its type ? What is the role of the input instruction and of its
argument ?
3. Write the following instruction
1 a=int(input("How old are you ? "))

What is the value of a. What is its type ? What is the role of the int() instruction ? We could
also write the following instruction and ask the same questions :
1 a=float(input("How tall are you (in m) "))

4. Create two variables : number and movie. Assign them with values 12 and "The life of
Brian" respectively. What is the result of the following instruction ?
1 print ("I have watched", movie, "at least", number, "times")

Try the next instructions :


1 print ("I have watched\n", movie, "at least", number, "times")
2 print ("Romanes", "\t", "eunt \t domus")

Note : The backslash \ is done with the shortcut Alt+Shift+: on Mac.


5. Predict that will be displayed at the print() instruction :
1 Hello=2.5
2 b="Hello"
3 print (Hello, 2.5, "b",b)

The math library

When you type import math, you load a set of predefined mathematical functions. Tapez dans la
console : import math. Check https://docs.python.org/3/library/math.html for more
information.
Try the following instruction :
1 import math
2 r=2
3 a = math.pi*r**2
4 c = math.exp(2)
5 d = math.sqrt(c)

Concatenation of strings

It might be useful to construct a string little by little. To this end, we will concatenate. It is kind
of like additions, but with strings. Example :
1 string1 = "Knight "
2 string2 = "of NEE"
3 print(string1 + string2)

Please note that the space at the end of ”Knight ”. You can only concatenate a string with another
string. If you wish to concatenate a number, you must first cast the variable. For example :
1 n = 33
2 string1 = "knights "
3 string2 = "of NEE"
4 print(str(n) + " " + string1 + string2)

Foundations in Business Information Management (INGE1135) 6 SESSIONS - 2024


- Exercises
1.5. WRITING PROGRAMS Session 1

1.5 Writing programs


▷ 1. Given an individual’s gross revenue between 2000 and 3000 e, write an algorithm that computes
the taxes levied on this individual.
We know that, between 2000 and 3000e, taxes amount to 500e+ 47.5 % of the part that exceeds
2000e.

▷ 2. Explain what this algorithm does, and give its specifications.


1 # −∗− c o d i n g : Utf −8 −∗−
2
3 A=i n t ( input ( "first value A ? " ) )
4 B=i n t ( input ( "second valuree B ? " ) )
5 C=i n t ( input ( "third value C ? " ) )
6 print ( "Values at the start " )
7 print ( "A =" , A)
8 print ( "B =" , B)
9 print ( "C =" , C)
10 D = B
11 B = A
12 A = C
13 C = D
14 print ( "Values at the end:" )
15 print ( "A =" , A)
16 print ( "B =" , B)
17 print ( "C =" , C)

▷ 3. Write a program that gives a disc’s perimeter given its radius. The radius length is given in mm.
What do you have to add or modify to compute and display the disc’s area ?

▷ 4. Write a program that receives five values from the user, and displays their average.
▷ 5. Write a program that asks the user for parameters a, b, c for the quadratic formula f (x) = ax2 +bx+c.
Then, the program asks the user to provide a specific x, and calculates f (x).
▷ 6. Write a program that swaps the values contained in variables A and B. The values are provided by
the user.

Foundations in Business Information Management (INGE1135) 7 SESSIONS - 2024


- Exercises
Session 1 1.5. WRITING PROGRAMS

Foundations in Business Information Management (INGE1135) 8 SESSIONS - 2024


- Exercises
Session 2

Decision & choices in Python


2.1 Syntax
1 #The i n d e n t s ( d i s t a n c e from margin ) d e l i m i t t h e i n s t r u c t i o n b l o c s
2
3 if condition1 :
4 i n s t r u c t i o n 1a
5 i n s t r u c t i o n 2a
.
.
6 .
7 i n s t r u c t i o n na
8
9 e l i f condition2 :
10 i n s t r u c t i o n 1b
11 i n s t r u c t i o n 2b
.
.
12 .
13 i n s t r u c t i o n nb
14
15 else :
16 instruction 1c
17 instruction 2c
.
.
18 .
19 i n s t r u c t i o n nc

9
Session 2 2.2. REMINDER ON BOOLEANS

2.2 Reminder on booleans


Booleans are types of variables that can take either True or False as value ( alternatively 1 or 0).
Let us assume we have two logical propositions P and Q. For this example, we pose that P is x > 3,
and Q is x < 5. If x = 6, then P is True, and Q is False. The two following pieces of codes are equivalent
:

1 x = 6 1 P = True
2 P = x>3 #P t a k e s v a l u e True 2 Q = False
3 Q = x<6 #Q t a k e s v a l u e F a l s e 3 print (P and Q)
4 print (P and Q) 4

In both cases, False will be displayed on screen. In the case of a logical and, the proposition P
and Q will be True if and only if both P and Q are True. In the case of a logical or, the proposition P
or Q will be False if and only if P and Q are False. The logical not simply returns the boolean inverse
of the proposition. The following Truth table sums up all possibles cases.

Truth table :
P Q P or Q P and Q not P
True True True True False
True False True False False
False True True False True
False False False False True

2.3 Basic exercises


Manipulating booleans

Warning In the following exercises, you will test basic instructions in Python. We kindly ask you to
use the Python Console to that end, and to take note of the results that you obtain. Try to predict the
outcomes, and find an explanation of what happens on screen as well as behind the scenes.

1. What is the difference between a=b and a==b?

2. Assign values True and False to respectively p and q. Test the following lines :
print(p or q)
print(p and q)

Note that the logical negation is written not.


Test the following :
print(not q)

p!=q does the opposite of p==q and returns False if both variables are equivalent, and True
if they are not.

3. Assign values 3,4,3 to respectively a, b, c. Test the following commands. What type are they ?
print(a==b)
print(a!=b)
print(a==c)
print(b<=c)
print(b>=c)

What does the following instruction do ?


d=b>=c

Foundations in Business Information Management (INGE1135) 10 SESSIONS - 2024


- Exercises
2.4. CHOICE STRUCTURES Session 2

2.4 Choice structures


Indentation
In an algorithm, it often useful to only execute a piece under certain conditions. For example, we will
display text depending on the user’s age. This algorithm displays whether the user is legally minor or
adult.
1 age = int(input("How old are you ? "))
2 if age >= 18 :
3 print("You are an adult")
4 else :
5 print("You are a minor")

Indentation defines what bloc of code will be executed. The indent is the space between the margin
and the beginning of the line of code. In the example above, line 3 is indented. This means that it will
only be executed if the preceding boolean on line 2 is True. In the case where line 3 is False, then line
5 will be executed. This will only be the case if the user gave a integer strictly inferior to 18.

Conditional structures
In the case of the age of majority, the world is much more complex than the example above. Through-
out the world, legal adulthood is reached at ages anywhere between 15 and 21 (source https:
//en.wikipedia.org/wiki/Age_of_majority). For simplicity, we will ignore cases where the
age of majority is reached before 18.

1 age = int(input("How old are you ? "))


2 if age == 18 :
3 print("You are adult in most countries")
4 elif age == 19 :
5 print("You are adult in Algeria")
6 elif age > 19 and age < 21 :
7 print("You are adult in most countries")
8 elif age >= 21 :
9 print("You are adult in all countries")
10 else :
11 print("You are minor")

When the computer meets a series of conditionals starting with an if, and followed by elif(s) or an
else, it will only execute one of those structures. For example, if the user inputs 20, the computer would
proceed as follows :
1. The boolean on line 2 is False, so it does not execute line 3,

2. The boolean on line 4 is False, so it does not execute line 5,


3. The boolean on line 6 is True, so it executes line 7,
4. The rest of the conditionals are ignored, since the computer ran into a True,
5. If the computer meets a new series of conditionals starting with an if, it restarts the process.

Foundations in Business Information Management (INGE1135) 11 SESSIONS - 2024


- Exercises
Session 2 2.5. INTRODUCTION EXERCISES

2.5 Introduction exercises


▷ 1. What does variable X contain after executing these algorithms ?
1.
1 X = 7
2 i f (X > 5 ) :
3 X = X − 3
4
5 i f ( ( 3 < X) and (X <= 5 ) ) :
6 X = X−2
7
8 i f (X <= 3 ) :
9 X = X+5

2.
1 X = 7
2 i f (X > 5 ) :
3 X = X − 3
4
5 e l i f ( ( 3 < X) and (X <= 5 ) ) :
6 X = X−2
7
8 i f (X <= 3 ) :
9 X = X+5

3.
1 X = 7
2 i f (X > 5 ) :
3 X = X − 3
4
5 e l i f ( ( 3 < X) and (X <= 5 ) ) :
6 X = X−2
7
8 e l i f (X <= 3 ) :
9 X = X+5

Foundations in Business Information Management (INGE1135) 12 SESSIONS - 2024


- Exercises
2.5. INTRODUCTION EXERCISES Session 2

▷ 2. What does variable X contain after executing these algorithms ?

1.
1 X = 4
2 i f (X > 5 ) :
3 X = X − 3
4
5 e l i f ( ( 3 < X) and (X <= 5 ) ) :
6 X = X−2
7
8 i f (X <= 3 ) :
9 X = X+5

2.
1 X = 4
2 i f (X > 5 ) :
3 X = X − 3
4
5 e l i f ( ( 3 < X) and (X <= 5 ) ) :
6 X = X−2
7
8 else :
9 X = X+5

3.
1 X = 4
2 i f (X > 5 ) :
3 X = X − 3
4
5 else :
6 X = X−2
7
8 i f (X <= 3 ) :
9 X = X+5

Foundations in Business Information Management (INGE1135) 13 SESSIONS - 2024


- Exercises
Session 2 2.5. INTRODUCTION EXERCISES

▷ 3. Give the states of the following program with successively 45, 3, and 26 as user input. What does
this program do ? Test it.
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 x= i n t ( input ( "A first integer :" ) )
4 y= i n t ( input ( "A second integer :" ) )
5 z= i n t ( input ( "A third integer :" ) )
6
7 i f x<y :
8 i f y<z :
9 print ( x , "<" , y , "<" , z )
10 else :
11 i f x<z :
12 print ( x , "<" , z , "<" , y )
13 else :
14 print ( z , "<" , x , "<" , y )
15 else :
16 i f x<z :
17 print ( y , "<" , x , "<" , z )
18 else :
19 i f y<z :
20 print ( y , "<" , z , "<" , x )
21 else :
22 print ( z , "<" , y , "<" , x )

▷ 4. Give the states of the algorithm. Explain what it does. In other words, give its specifications. Use
the user inputs 1515, 1600, 1900, and 2004 to test the algorithm.
1 #A l g o r i t h m QuoiJeFais
2 #v a r i a b l e s : A : i n t
3 A = i n t ( input ( "Input an integer" ) )
4 i f ( (A % 4 ) == 0 ) :
5 i f ( (A % 1 0 0 ) != 0 ) :
6 print (A, " BINGO" )
7 e l i f ( (A % 4 0 0 ) == 0 ) :
8 print (A, " BINGO" )
9 else :
10 print (A, " OUT" )
11 else :
12 print (A, " OUT" )

▷ 5. Give the states of the algorithm for the following user inputs : 6436 and 5346.
1 #a l g o r i t h m QuoiJeFaisEncore
2 #v a r i a b l e s : c , n , c1 , c2 , c3 , c4 : i n t
3
4 c = i n t ( input ( "Input an integer" ) )
5
6 n = c
7 c4 = n % 10
8 n = n //10
9 c3 = n % 10
10 n = n //10
11 c2 = n % 10
12 n = n //10
13 c1 = n % 10
14 i f ( c4 == ( c3 + c2 + c1 ) % 7 ) :
15 print ( "Bravo !" )
16 else :
17 print ( "Broken !" )

Foundations in Business Information Management (INGE1135) 14 SESSIONS - 2024


- Exercises
2.5. INTRODUCTION EXERCISES Session 2

▷ 6. Write the correct variable in the □ given the algorithm prints the largest of the 4 integers input
by the user.
1 #a l g o r i t h m P l u s G r a n d 4
2 #v a r i a b l e s : X, Y, Z ,D : i n t
3 X = i n t ( input ( "Input an integer" ) )
4 Y = i n t ( input ( "Input a second integer" ) )
5 Z = i n t ( input ( "Input a third integer" ) )
6 D = i n t ( input ( "Input a fourth integer" ) )
7 i f (X < Y) :
8 i f (Y < Z ) :
9 i f ( Z < D) :
10 print ( "The largest number between " ,X, Y, Z , D, " is " , □)
11 else :
12 print ( "The largest number betweene " ,X, Y, Z , D, " is " , □)
13 else :
14 i f (Y < D) :
15 print ( "The largest number between " ,X, Y, Z , D, " is " , □)
16 else :
17 print ( "The largest number between " ,X, Y, Z , D, " is " , □)
18 else :
19 i f (X < Z ) :
20 i f ( Z < D) :
21 print ( "The largest number between " ,X, Y, Z , D, " is " , □)
22 else :
23 print ( "The largest number between " ,X, Y, Z , D, " is " , □)
24 else :
25 i f (X < D) :
26 print ( "The largest number between " ,X, Y, Z , D, " is " , □)
27 else :
28 print ( "The largest number between " ,X, Y, Z , D, " is " , □)

▷ 7. Which of these 2 algorithms corresponds to the following specifications : Write a program that,
given three different integers, displays them in increasing order. Tip : the difference between the two
algorithms is at the very last line.

1 #a l g o r i t h m Ordre3A 1 #a l g o r i t h m Ordre3B
2 #v a r i a b l e s : X, Y, Z : i n t 2 #v a r i a b l e s : X, Y, Z : i n t e g e r
3 3
4 X = i n t ( input ( "Input an integer" ) ) 4 X = i n t ( input ( "Input an integer" ) )
5 Y = i n t ( input ( "Input a second 5 Y = i n t ( input ( "Input a second
integer" ) ) integer" ) )
6 Z = i n t ( input ( "Input a third integer 6 Z = i n t ( input ( "Input a third integer
") ) ") )
7 7
8 i f (X < Y) : 8 i f (X < Y) :
9 i f (Y < Z ) : 9 i f (Y < Z ) :
10 print (X, "<" ,Y, "<" , Z ) ; 10 print (X, "<" ,Y, "<" , Z ) ;
11 else : 11 else :
12 i f (X < Z ) : 12 i f (X < Z ) :
13 print (X, "<" , Z , "<" ,Y) 13 print (X, "<" , Z , "<" ,Y)
14 else : 14 else :
15 print ( Z , "<" ,X, "<" ,Y) 15 print ( Z , "<" ,X, "<" ,Y)
16 else : 16 else :
17 i f (X < Z ) : 17 i f (X < Z ) :
18 print (Y, "<" ,X, "<" , Z ) 18 print (Y, "<" ,X, "<" , Z )
19 else : 19 else :
20 i f (Y < Z ) : 20 i f (Y < Z ) :
21 print (Y, "<" , Z , "<" ,X) 21 print (Y, "<" , Z , "<" ,X)
22 else : 22 else :
23 print ( Z , "<" ,X, "<" ,Y) 23 print ( Z , "<" ,Y, "<" ,X)

Foundations in Business Information Management (INGE1135) 15 SESSIONS - 2024


- Exercises
Session 2 2.6. WRITING PROGRAMS

▷ 8. Write an algorithm that computes and displays a household’s income taxes, given the following
specifications :

• no taxes if the income is inferior to 1250e


• otherwise, taxes are a sum of
– 20 % of the part of the income between 1250 and 7500e(not included),
– 30 % of the part of the income between 7500 and 20 000e(not included),
– 47.5 % of the part of the income that exceeds 20 000e.

Note : The function that represents the income tax is piecewise linear. For example, if the income is
e10.000, the income tax will be calculated like so : 20% of 7.500−1.250, added to 30% of 10.000−7.500.
Why are both following algorithms not correct ?
1 #a l g o r i t h m C a l c u l I m p o t 1
2 #v a r i a b l e s : X : f l o a t
3 X = f l o a t ( input ( What i s your income ( in e ) ? "))
4 if (X <= 1250.0) :
5 print ("Tax : " ,0,"e")
6 elif (1250.0 < X <= 7500.0) :
7 print ("Tax : " ,0.2 * (X -1250) ,"e")
8 elif (7500.0 < X <= 20000.0) :
9 print ("Tax : " ,0.2 * (X -1250) +0.3 * (X -7500) ,"e")
10 elif (20000.0 < X) :
11 print ("Tax : " ,0.2 * (X -1250) +0.3 * (X -7500) +0.475 * ( X -20000) ,"e")

1 #a l g o r i t h m C a l c u l I m p o t 2
2 #v a r i a b l e s : X,A, B,C : f l o a t
3
4 X = f l o a t ( input ( Income in e ? "))
5 R = 0
6 A = 0
7 B = 0
8 C = 0
9
10 if (1250.0 < X <= 7500.0) :
11 A = 0.2 * (X -1250)
12 if (7500.0 < X <= 20000.0) :
13 B = 0.3 * (X -7500)
14 if (20000.0 < X) :
15 C = 0.475 * ( X -20000)
16 R = A+B+C;
17 print ("Tax : ",R,"e");

2.6 Writing programs


▷ 1. Given a person’s taxable income, between 2000 eand 3000e, create an algorithm that computes
the person’s income tax.
We know that between 2000 eand 3000 e, the income tax is calculated as follows : 500 e + 47.5 % of
the part of the income that exceeds 2000 e.
If the user gives an invalid value as income, then the algorithm will not compute the income tax, and
display an error message.
▷ 2. Write an algorithm that, given a real number input by the user, returns its absolute value.
▷ 3. Write an alogirhtm that reads an integer input by the user, then displays a message if that number
corresponds to a leap year.
A year is ”leap” when it has 366 days. For a year to be a leap one, it must be divisible by 4.
However, if a year is divisible by 100, then it must also be divisible. For example, 2000 was a leap year,
but 1700, 1800, and 1900 were not.
▷ 4. Your local post office wants you to write a program for the postal clerks that determines the tax to
apply to a parcel. The post office lays the following specifications : given the length, width, and height
of the parcel in cm, and its weight in kg, write a program that prints the taxes to be applied, or the
error message invalid parcel.

• if the weight of the parcel is above 10kg, then it is invalid ;


• if one of the dimensions of the parcel (length, width, or height) is more than 50cm, then it is
invalid ;

Foundations in Business Information Management (INGE1135) 16 SESSIONS - 2024


- Exercises
2.6. WRITING PROGRAMS Session 2

• the regular tax applied to all parcels is 2.50e;


• if the weight is between 5 and 10 kg, then an additional tax of 0.50e is applied ;

• if the volume exceeds 27 dm3 , then an additional tax proportional to the exceeding volume is
applied. That tax is of 0.15e by exceeding dm3 .
• all taxes are cumulative.

Reminder : volume = width ∗ length ∗ height; 1 dm3 = 1000 cm3 .


▷ 5. Write a program that, given the grade obtained by a student, displays their mention. The rule are
the following. The greatest distinction is obtained with 86% or more, the great distinction is obtained
at 76% or more, the distinction is obtained at 69% or more, the satisfaction is obtained at 60% or more.
Otherwise, the student is adjourned. The students only obtains the highest mention they qualify for on
their diploma.
▷ 6. Follow the instructions to write a program that answers the following question :
On what week day was your grand mother born ?
The user will give the birthday in the following format : Day Month Year. Year must be between
1901 and 1999, Month must be between 1 and 12, and Day must be between 1 and 31. For example, if
your grand mother is born on the 20th of April 1969, the user will input 20, 4, 1969. We assume that
the user gives a correct and coherent birth date.
Then, the program must do the following :
1. Obtain :
A: the last two digits of the birth year ;
B: b = the euclidian result of A divided by 4. If it is a leap year and the birth month is January
or February, we subtract 1 to b.
M: a number according to the month :
jan.= 0, feb.= 3 mar.= 3, apr.= 6, may= 1, june= 4, july.= 6, aug.= 2, sept.= 5, oct.= 0,
nov.= 3, dec.= 5 ;
D: the number of the birth day.
2. Compute the sum of A, B, M and D ;
3. Take a look at the rest of the division by 7 of this sum. If it is a 0, then your grand mother is
born on a sunday ; if it is 1, then she is born on monday ; ... ; if it is 6, then she is born on a
saturday.
Example : if your grand mother is born on the 16 05 1943
A = 43 ; B = 10 ; M = 1 ; D = 16 ; A +B + M + D = 70 . 70 divided by 7, rest is 0.
Your grand mother is born on a sunday !

Foundations in Business Information Management (INGE1135) 17 SESSIONS - 2024


- Exercises
Session 2 2.6. WRITING PROGRAMS

Foundations in Business Information Management (INGE1135) 18 SESSIONS - 2024


- Exercises
Session 3

Data structures and loops

3.1 Lists and dictionaries


For this tutorial, try each of the instructions in the python console and analyse its effects. Be curious :
modify, test, and dissect ! You actually need to tinker a bit to fully understand the concept of lists/tuples.

3.1.1 Tutorial on lists


Definitions and manipulations The list is an object that represents a collection of heterogeneous
data, of dynamic size, and modifiable. Each elements is accessible by an index. We illustrate with this
list of size n :

Each of the terms in the above definition is important, and we are going to analyze each and everyone
of them.
First, let us learn how to create a list (homogeneous at first), and access the elements stored inside.
You will see that the indexation begins at 0, thus the last index will be list size-1.
1 b=[1,8,10]
2 print(b)
3 print(b[0])
4 print(b[1])
5 print(b[2])
6 print(b[3] #this returns an error, why ?

Note : On Mac, the square brackets are made with shortcuts Alt+Shift+( and Alt+Shift+).
It is also possible to use negative index to access elements (see picture below). Accessing the last
element is done with b[-1], so we do not need to know the list size to access it.

1 print(b[-1])
2 print(b[-3])

We can modify the elements of the list, and the elements can be of different types (heterogeneous).
To modify the list, one must simply assign a new value to the desired index.

19
Session 3 3.1. LISTS AND DICTIONARIES

1 b[1]="Hello"
2 print(b)

Now, let us demonstrate the dynamic size property. The list size is never fixed and can always
increase or decrease. Here are two methods that we can use with lists. Beware that these methods only
work with objects of type list.
1 a=[1,2,3]
2 a.append(4)
3 print(a)
4 a.pop()
5 print(a)

The first method allows us to add an element at the end of the list (increases its size one unit). The
new element must be given in the argument (the value between parentheses). Then, method pop()
prints and deletes the last element of the list.
It is also possible to insert elements at a particular index, to add multiple at the same time, and to
delete an element without printing it. The effect of the next instructions are rather intuitive :
1 a=["s","p","a","m"] # this is equivalent creating an empty list (a=[])
, and completing it by slicing : (a[:]="spam"). See next paragraph.
2 a.extend([3,4,5])
3 print(a)
4 del a[3]
5 print(a)
6 a.insert(3,"m")
7 print(a)
8 del a[4:]
9 print(a)

Slicing (also valid for string) Slicing, as the name implies, allows us to access slices of a collection
of data, or to access specific elements. For example :
1 a = ["spam","Spam","SPAM!"]
2 print(a[0:2])
3 print(a[0:1])
4 print(a[1:])
5 print(a[:])
6 b=a[1:]
7 print(b)

Line #2 indicates that we access elements 0 through 2 not included. If lis is a list, its general
structure is the following : list[iv : fv] (initial value, final value). It allows us to access elements
indexed iv through fv-1. Omitting vi (vf) allows us to tell the computer that the initial (final) value
is the beginning (end) of the list. So, instruction #4 accesses all elements from index 1 through the end.
Instruction #5 allows us to access all elements. Finally, instruction #6 assigns a piece of list to b.

Modifying a list by slicing It is possible to replace the last two elements by 1 and 2 by writing
instruction #1 in the box below. The principle here is to replace a slice of list by another slice of list.
If the new slice has a greater size than the old one, then the list will increase in size (see #3), even if
it is in the middle of the list (see #5). On the opposite, if the new slice is smaller than the old one,
then the list will decrease in size (see #7). Note that, after the following instruction, a should contain
["spam","Spam","SPAM!"].
1 a[1:3] = [1,2]
2 print(a)
3 a[1:3] = [1,2,3,4]
4 print(a)
5 a[1:2] = ["hello", "inserting !"]

Foundations in Business Information Management (INGE1135) 20 SESSIONS - 2024


- Exercises
3.1. LISTS AND DICTIONARIES Session 3

6 print(a)
7 a[1:]=["Spam","SPAM!"]
8 print(a)

Iterating on a list, and small introduction on loop for Instruction range(stop) or range(start,
stop[, step]) (the step is optional) creates a special kind of list. Note that the default step is 1.
Let us use a for loop to analyze what is lies inside a :

1 a = range(1,11)
2 for i in a:
3 print (i) #do not forget the indent

In this instruction, i is an iterator, a variable that will take as successive values the ones in the
special range list given after keyword in. You can try the same with the next lists. Note that it is
possible to create lists of lists :

1 b = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday
"]
2 c = [1,"Monday",2.3,["try",2]]
3 print(b)
4 print(c)

We can also go through elements of a string :

1 text = "hello there !"


2 for i in text:
3 print (i)

Order modifying methods The next method modify the order of the elements in a list. Beware,
these do not create a new list and modify the order of the object. With the help of the following
example, you will notice how Python deals with capital letters.

1 a = ["sb","sa","Sb","u","U","Sa","su"]
2 a.reverse()
3 print(a)
4 a.sort()
5 print(a)

Addition and multiplication of lists (also valid for string) It is possible to add two lists :

1 a=[1,2]
2 b=["one","two"]
3 c=a+b
4 print(c)

Here, elements from b are added after the elements from list a. Now, is the addition commutative,
like in mathematics ? Is a+b equivalent to b+a ?
It is also possible to multiply a list by an integer. This is the same as repeating a number of times
the elements of the list. This is not to be confused with multiplying each element individually (this
would use arrays, which is outside the scope of this course). Example :

1 a=[1,2]
2 c=a*2
3 print(c)

Foundations in Business Information Management (INGE1135) 21 SESSIONS - 2024


- Exercises
Session 3 3.1. LISTS AND DICTIONARIES

Miscellaneous (also valid for string) Next are three interesting functionalities : a method that
returns the index of the first element corresponding to a given value, a method that counts the number
of times a given value appears in the list, and a function that returns the length of the list.
1 a=[]
2 a[:]="abracadabra"
3 print(a)
4 print(a.index("a"))
5 print(a.index("c"))
6 print(a.count("a"))
7 print(len(a))

3.1.2 Tutorial on dictionaries


Dictionaries are objects similar to lists. The key difference is that the programmer can choose each
item’s index, whereas a list will always assign index 0,1,2,3,... Let us create a Chair dictionary that
contains all info on a specific model of chair :
1 Chair = {"Width" : 48, "Length" : 55, "Height" : 30, "Color" : "Red"}

Note : On Mac, curly brackets { } are inputted with shortcuts Alt+( and Alt+).

Like lists, dictionaries are modifiable objects, and their contents can be heterogeneous. We can
apply the methods we saw above, give them a try !
Some particular cases. We create a dictionary to give each person’s surname, and their office number
at Saint-Louis :
1 a = {"Laurier" : "E12", "Collet" : "F02", "Appraxine" : "F02"}
2 print(a["Laurier"])
3 print(a["F02"])

Note that dictionaries are defined by accolades, but we access to their index by square brackets [ ]
nonetheless. In the example, we saw that it is possible to access a value only by using its key, but not
the opposite. Here, keys are each person’s surname, and the values are office number.
Let us see what happens if two keys are the same in a dictionary :
1 Flower = {"Color" : "Pink", "Color" : "Yellow", "Color" : "White"}
2 Flower["Color"]

Python only returns the last item with index ”Color”.

Foundations in Business Information Management (INGE1135) 22 SESSIONS - 2024


- Exercises
3.2. LOOP SYNTAX Session 3

3.2 Loop syntax


1. while
1 while c o n d i t i o n :
2 i n s t r u c t i o n 1a
3 i n s t r u c t i o n 2a
..
4 .
5
6 i n s t r u c t i o n na

2. Incremental for
1 f o r i in range ( i v , f v +1) :
2 i n s t r u c t i o n 1a
3 i n s t r u c t i o n 2a
..
4 .
5
6 i n s t r u c t i o n na

3. Decremental for :
1 f o r i in range ( i v , f v −1,−1) :
2 i n s t r u c t i o n 1a
3 i n s t r u c t i o n 2a
..
4 .
5
6 i n s t r u c t i o n na

Attention : You noticed the indent (space between the margin and the first character) that delimits
the instruction bloc that must be repeated. To create an indent, use the Tab key, next to your A (Q)
key on your AZERTY (QWERTY) keyboard.
Attention : When implementing for loops, we use a special function range() that creates a list of
values. When calling this function with two arguments a and b (range(a,b), assuming that a < b),
it generates a list of values from a to b not included with step 1 (step 1 is implicit). If you wish to
create a decremental loop, then you need to specify the −1 step, for example range(a,b,-1) where
a > b. The step can be modified to any positive or negative integer value.

Foundations in Business Information Management (INGE1135) 23 SESSIONS - 2024


- Exercises
Session 3 3.3. TUTORIAL ON LOOPS

3.3 Tutorial on loops


When writing algorithms, we often need to make the computer repeat some instructions. For example,
we would like to fill a list with names, or display a countdown, or display a mathematical series. For
these purposes, we must use loops. In python, there are two kinds : while and for.

3.3.1 While loop


The while loop is used to repeat a bloc of instructions as long as a condition holds true. For example,
we want to gather numbers in a list as long as the user inputs a positive number.
1 a = []
2 x = float(input("Input a positive number ? (<0 to stop) "))
3 while x > 0 :
4 a.append(x)
5 x = float(input("Input a positive number ? (<0 to stop) "))
6 print("List a contans :",a)

We ask a number before entering the while loop. As the exit condition is x > 0, then x must exist
in the computer’s memory before the loop begins. The while loop functions much in the same way
as a if that would be re-checked once the instruction bloc has been executed. Here, the instruction
bloc is composed of lines 4 and 5. Once these two lines have been executed, the computer comes back
to line 3 to check whether the condition hold true or not. If it holds true, then the bloc is re-executed,
etc. If the condition is false, then the loop ends and line 6 is next to be executed. Note that if the user
inputs a negative number as first number, then the loop is not entered, and the script will display an
empty list.
We can imagine a loop where the exit condition is more arbitrary, by using a sentinel value. For
example, the next algorithm tries to find an even number in a list. As soon as an even number is found,
then the loop is exited and the number is displayed.
1 a = [1,5,19,11,5,4,21,7]
2 i = 0
3 found = False
4 while found == False :
5 if a[i]%2==0 :
6 n = a[i]
7 found = True
8 i = i + 1
9 print("The first even number of the list :",n)

We start by initializing a counter on line 2. This counter will be incremented (increased by 1) at the
end of each iteration and is used to loop through all the indices of list a. The boolean variable found
is initialized with False. This symbolizes that we have not yet found the even number. The variable
will take True as soon as the even number is found.
Next, inside of the loop, the computer evaluated whether the element at index i of list a is even. If
so, that number is assigned to n and True is assigned to found. If not, then i is incremented to check
the next index during the following iteration.

3.3.2 For loop


The for loop will execute a set number of times that is determined before the loop starts, as opposed
to the while loop. In the previous example, the loop could theoretically never end, and the user could
keep on inputting values indefinitely.
Here, with the for loop, the programmer exactly knows how many times a given bloc of instruction
will be executed. For example, we want to display the multiplication table if x (given by the user) from
x ∗ 1 to x ∗ 10. The programmer asks the user a number to multiply, then the computer will simply
display 10 times a different multiplication.
1 x = int(input("Give a number to multiply : "))
2 for i in range(1,11) :
3 result = x * i

Foundations in Business Information Management (INGE1135) 24 SESSIONS - 2024


- Exercises
3.3. TUTORIAL ON LOOPS Session 3

4 print (x,"ties",i,"=", result)

At each iteration, i will successively take values 1,2,3, etc. until 10 because 11 is not included. x
will remain the same throughout the loop.
It is possible to write a for loop and only specify a superior threshold (still not included). In this
case, the default starting value of the counter j will be 0.
1 x = int(input("Give a number to multiply :"))
2 for j in range(x) :
3 result = x * j
4 print (x,"times",j,"=", result)

As we have covered earlier, it is possible to read through the elements in a list that was initialized
before the loop.
1 fruits = ["bananas","apples","pears","strawberries"]
2 for element in fruits :
3 print("I like to eat",element)

Foundations in Business Information Management (INGE1135) 25 SESSIONS - 2024


- Exercises
Session 3 3.4. BASIC EXERCISES : READING ALGORITHMS

3.4 Basic exercises : reading algorithms


▷ 1. The boolean in this while loop was not written :
Response = "hello"
Count = 5
Attempt = input ( "Give me a word" )
while ( . . . ) : #what s h o u l d be t h e b o o l e a n h e r e ?
Count = Count − 1
Attempt = input ( "Give me a word" )

Give the condition so that the computer can end the loop if Attempt is equivalent to Response
or if 5 attempts have been made. What is the boolean ?

▷ 2. Do the state of the following algorithm, and give its specifications.


1 #a l g o r i t h m C h o c o l a t i n e
2 #v a r i a b l e s : i , pre , n : i n t ; i n c r : b o o l ; t : list
3
4 n = 4
5 t = [5 , 2 , 3 , 6]
6 i n c r = True
7 prev = t [ 0 ]
8
9 f o r i in range ( 1 , n ) :
10 i f ( t [ i ] < prev ) :
11 incr = False
12 prev = t [ i ]
13
14 print ( t , "is" , i n c r )

▷ 3. Explain what the following algorithm displays, depending on the user’s input. Give the state of the
algorithm and chose your own user input.
1 #a l g o r i t h m Alpha
2 #v a r i a b l e s : n , i , s : i n t
3
4 n = i n t ( input ( "An integer ? " ) )
5 s = 0
6
7 f o r i in range ( 1 , n+1) :
8 s = s + i
9
10 print ( "With " , n , " we obtain " , s )

▷ 4. Explain what the following algorithm displays, depending on the user’s input. Give the state of the
algorithm and chose your own user input.
1 #a l g o r i t h m Beta
2 #v a r i a b l e s : i , n , p : i n t ;
3
4 n= i n t ( input ( "Give an integer " ) )
5 p = 1
6 f o r i in range ( 1 , n+1) :
7 p = p∗ i
8
9 print ( "With " , n , " we obtain " , p )

Foundations in Business Information Management (INGE1135) 26 SESSIONS - 2024


- Exercises
3.4. BASIC EXERCISES : READING ALGORITHMS Session 3

▷ 5. Give the states of the algorithm if the user input is 8, and do the same with 10.
For both of these algorithms :
1 #a l g o r i t h m Hoho
2 #v a r i a b l e s : n , p , i : i n t
3
4 n = i n t ( input ( " Input an integer ." ) )
5
6 p = 1
7 i = 0
8
9 while ( p < n ) :
10 p = p ∗ 2
11 i = i + 1
12 i f ( p == n ) :
13 print ( " Bingo ! " , " i is : " , i )
14 else :
15 print ( " Broken ! " )

1 #a l g o r i t h m Haha
2 #v a r i a b l e s : n , tmp , i : i n t
3
4 n = i n t ( input ( " Input an int ." ) )
5
6 tmp = n
7 i = 0
8
9 while ( tmp % 2 == 0 ) :
10 tmp = tmp / 2
11 i = i + 1
12
13 if ( tmp == 1 ) :
14 print ( " Bingo ! " , " i is : " , i )
15 else :
16 print ( " Broken ! " )

▷ 6. We have the following information :


#v a r i a b l e s : numbers : i n t [ ]
#i : i n t ; loop counter

And the following list creation instruction :


numbers = [ 0 ] ∗ 1 0
# c r e a t i n g a l i s t o f 10 z e r o e s w i t h i n d e x [ 0 . . . 9 ] ;
# the elements are a l l i n t e g e r s

For each of the following questions, and independently of the previous ones, determine the index
and content of the list that are modified by the following instructions. You are expected to fill this kind
of table as answer to these exercises :

i 0 1 2 3 4 5 6 7 8 9
numbers[i]

1. for i in range(0, 10) : numbers[i] = 10 − i


2. for i in range(0, 10) : numbers[i] = i//2

3. for i in range(0, 6) : numbers[i] = i ∗ i


for i in range(6, 10): numbers[i] = numbers[i−5]

4. f o r i in range ( 0 , 1 0 ) :
i f ( i % 3 ) == 0 :
numbers [ i ] = 0
else :
numbers [ i ] = i % 3

Foundations in Business Information Management (INGE1135) 27 SESSIONS - 2024


- Exercises
Session 3 3.4. BASIC EXERCISES : READING ALGORITHMS

▷ 7. Suppose that the list x is declared and initialized. Suppose also that n contains an integer that is
the size of x. Suppose further that all the other variables are integers.
What does the instruction bloc display in each case :

i 0 1 2 3
1. x=[1,2,3,4]
x[i] 1 2 3 4

i 0 1 2
2. x=[9,6,-1]
x[i] 9 6 -1

The instruction bloc :


c = 0
f o r j in range ( 0 , len ( x ) +1) :
c = c + x[ j ]

print ( x [ i ] , " " , c )

▷ 8. What is the program going to display if the following values are given by the user (in order) :
2 5 3 10 1 11 2 8 3 8
Then, the opposite. Find what integers the user gave is the display is :
9 26 4 11 11 8
1 #a l g o r i t h m F a i t Q q c h o s e
2 #v a r i a b l e s : i , n , m : e n t i e r
3
4 f o r i in range ( 1 , 6 ) :
5 n = i n t ( input ( ) )
6 m = i n t ( input ( ) )
7 i f ( n == 1 ) :
8 print ( 2 ∗m, " " )
9 e l i f ( n == 2 ) :
10 print (m∗m, " " )
11 else :
12 print (m+3 , " " )
13
14 i f ( ( n % 2 ) != 0 ) :
15 print (m)

▷ 9. What does the following algorithm display if the values given by the user are (in order) : 3,2,4,4
? Give the specifications.
1 #Al go r i t h m KwaEncor
2 #v a r i a b l e s :
3 # v : int [ ] ;
4 # n, i : int ;
5 # s : int ;
6 # m : float ;
7
8 # how many v a r i a b l e s t o t a k e ?
9 n = i n t ( input ( " How many values do you wish to input ? " ) )
10 v = [0]∗n
11 s = 0
12
13 # gathering the values
14 f o r i in range ( 0 , n ) :
15 v [ i ] = i n t ( input ( " Enter an integer " ) )
16 s = s + v[ i ]
17
18 # computation
19 m = s /n
20
21 # Display
22 print ( "(" , )
23 f o r i in range ( 0 , ( n−1) ) :
24 print ( v [ i ] , "+" , )
25 print ( v [ n − 1 ] , )
26 print ( ")/" , n , " = " , m)

Foundations in Business Information Management (INGE1135) 28 SESSIONS - 2024


- Exercises
3.4. BASIC EXERCISES : READING ALGORITHMS Session 3

▷ 10. What does the algorithm display if the values given by the user are 2,7,3,2,-1 ? Give the state
of the algorithm. Do the same if the only value given is -1. What does this algorithm do ? What are
its specifications ?
1 #a l g o r i t h m SansNom
2 #v a r i a b l e s :
3 #v , n , s : i n t
4 #m : f l o a t
5
6
7
8 #i n i t i a l i z i n g
9 n = 0
10 s = 0
11 #i n p u t 1 s t v a l u e
12 v = i n t ( input ( "an integer pls !" ) )
13
14
15 while ( v != −1) :
16 #p r o c e s s i n g
17 s = s + v #a c c u m u l a t i n g v a l u e s
18 n = n + 1 #c o u n t e r increment
19 #n e x t i n p u t
20 v = i n t ( input ( "an integer pls !" ) )
21
22 #i f we ar e here , we a r e s u r e t h a t : .....................................
23 i f ( n!=0) :
24 m = s /n
25 print ( "We obtained : " , s , " and also : " , m)
26
27 e l s e : # how can we l a n d h e r e ?
28 print ( "!?" )

▷ 11. What does this algorithm display if the values given are 4,2,7,3,2 ? Give the state of the
algorithm Do the same if the only value given is 0. What does this algorithm do ? Give its specifications.
1 #a l g o r i t h m Nobody
2 #v a r i a b l e s : n , v , s , i : i n t
3 # i : loop conter
4 # m : float
5 n = i n t ( input ( " How many values do you want to input ? " ) )
6 i f (n > 0) :
7 s = 0
8 f o r i in range ( 1 , n+1) :
9 v = i n t ( input ( "an integer pls ! " ) )
10 s = s + v
11 m = s /n
12 print ( "We obtained : " , s , " and also : " , m)
13 e l s e : # i n what c a s e do we l a n d h e r e ?
14 print ( "!?" )

▷ 12. What does this algorithm display if the values given are 5,3,2,10,1,9 ? What does this
algorithm do ? Give its specifications.
1 #a l g o r i t h m EncoreKwa
2 #v a r i a b l e s : nbVal , v a l , m, i : i n t
3
4 nbVal = i n t ( input ( " How many inputs ? " ) )
5
6 if ( nbVal > 0 ) :
7 m = i n t ( input ( " Give a first value : " ) )
8 f o r i in range ( 2 , nbVal +1) :
9 v a l = i n t ( input ( " Give value number " , i , " : " ) )
10 i f ( v a l < m) :
11 m = val
12 print ( "We obtain : " , m)

▷ 13. What does this algorithm display if the values given are 5,3,2,10,1,9 ? What does this
algorithm do ? Give its specifications.
1 #a l g o r i t h m EncoreKwaKwa
2 #v a r i a b l e s : nbVal , v a l , m, i : i n t
3
4 nbVal = i n t ( input ( "How many inputs ? " ) )
5
6 i f ( nbVal > 0 ) :
7 m = i n t ( input ( "Give the first value : " ) )
8 f o r i in range ( 2 , nbVal +1) :
9 print ( "Give value number" , i , ": " )
10 v a l = i n t ( input ( ) )

Foundations in Business Information Management (INGE1135) 29 SESSIONS - 2024


- Exercises
Session 3 3.5. SIMPLE EXERCISES WITH LOOPS & LISTS

11 i f ( v a l > m) :
12 m = val
13 print ( "We obtain " , m)

▷ 14. What does this algorithm display ?


1 #a l g o r i t h m Gamma
2 #v a r i a b l e s : n , a , b , t1 , t2 , l a s t , i : i n t
3 print ( "Give two integers : " )
4 a = i n t ( input ( "The first one : " ) )
5 b = i n t ( input ( "The second one : " ) )
6 n = i n t ( input ( "How many do you want ? " ) )
7 print ( "Here is the series :" )
8 t1 = a
9 print ( "term 1 : " , t 1 )
10 t2 = b
11 print ( "term 2 : " , t 2 )
12 f o r i in range ( 3 , n+1) :
13 l a s t = t1 + t2
14 print ( "term " , i , " : " , l a s t )
15 t1 = t2
16 t2 = l a s t

3.5 Simple exercises with loops & lists


▷ 1. Write a program that prints 100 times the sentence ”Romani ite domum” on screen. There must
be two sentences per line on screen (so 50 lines total).
▷ 2. Write a program that displays the 20 first multiples of 7.
▷ 3. Write a program that displays a conversion table from euros to Canadian dollars. The table
progression is geometric, as in the following example :

1 euro(s) = 1.65 dollar(s)


2 euro(s) = 3.30 dollar(s)
4 euro(s) = 6.60 dollar(s)
8 euro(s) = 13.20 dollar(s)
16 euro(s) = 26.40 dollar(s)
etc. (stop at 16384 euros)

▷ 4. Write a program that display a series of 12 numbers, each term is the triple of the previous term.
▷ 5. Write an algorithm that displays the first 20 multiples of 7. For each of the terms that are also
multiples of 3, display an star beside them.
Exemple : 7 14 21* 28 35 42* 49
▷ 6. Write an algorithm that calculates the first 50 multiples of 13, but only displays the ones that are
also multiples of 7.
▷ 7. Write a program that displays the 10 first multiples of 13 that are also multiple of 7.
▷ 8. We have the following lists :
t1 = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
t2 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec"]

1. Write a program that displays cleanly all elements from the list on one line. You should obtain
the following :

Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

2. Write a program that creates a new dict t3 that contains the keys from t2, and the values from
t1. So each month will be followed by its number of days like so :

[’Jan’: 31,’Feb’: 28, ’Mar’: 31, etc...]

Foundations in Business Information Management (INGE1135) 30 SESSIONS - 2024


- Exercises
3.6. WRITING PROGRAMS Session 3

▷ 9. Write a program that search for the greatest element in a given list. With this list :

[32, 5, 12, 8, 3, 75, 2, 15]

the program should display the following :


the greatest element in the list is : 75
▷ 10. Write a program that analyzes one by one all the element in a list of numbers (the one from
previous exercise) to generate two new lists. One with even numbers, the other one with odd numbers.
▷ 11. Write a program that analyzes each element of a list one by one, for example :

[’Jean’, ’Maximilien’, ’Brigitte’, ’Sonia’, ’Jean-Pierre’, ’Sandra’]

to create two new lists. One that contains words that have fewer than 6 characters, and another one
that contains words with 6 characters or more.

3.6 Writing programs


▷ 1. 1. Given a person’s income between 2000 e and 3000 e, write an algorithm that computes the
personal income tax.
We know that, for revenues between 2000 e et 3000 e, the personal income tax is calculated as
follows : 500 e + 47.5 % of the part of the income that exceeds 2000 e.
If the user gives an invalid income, then no calculation will occur and the computer will ask the
income again, as long as the user gives an invalid income.
2. Variante: limit the number of attempts to 10 (like an ATM, for example).
▷ 2. Write an algorithm that computes and displays the mean of a series of values given by the user.
The number of values can very from one user to another and is not asked to the user. The user must
input -9999 to stop inputting values.
▷ 3. Write an algorithm that reads the user’s integer input, then displays the sum of the integers between
1 and that input included. This process is repeated as long as a non-negative integer is given. So, the
algorithm stops when the user inputs a negative number.
▷ 4. Write an algorithm that computes and displays the mean of a series of values given by the user.
The number of values can very from one user to another and is asked to the user beforehand.
▷ 5. Write an algorithm that reads a series of N random integers inputs. The user first gives N. Then,
the algorithm computes the mean of the inputs. Finally, the algorithm displays the deviation from the
mean for each value.
▷ 6. Write an algorithm that reads the integer inputs, and counts the number of negative even, negative
odd, positive even, and positive odd values entered. When the input is 0, the results are displayed.s
▷ 7. A survey on household expenses was done for households with children above 5.
The results of this survey give, for each household, the number of children above 5 (1,2,3,...,10).
Mind that no surveyed household has more than 10 children. The survey also gives the expenses for
each household on a monthly basis.
Given the survey data, (the user will input the results), write a program that computes and displays
the mean expense per child for each type of household. The households are classified into types simply
according to the number of children (1,2,3,...,10).
The user signals for no more data to enter is inputting 0 for the number of children. If no data
is available for a type of household, the program will not compute the mean expenses per children for
that type of household and instead display ”-”.
The following is an example use of the program :
Number of children : 2
Expenses : 600
Number of children : 3
Expenses : 1000
Number of children : 2
Expenses : 500

Foundations in Business Information Management (INGE1135) 31 SESSIONS - 2024


- Exercises
Session 3 3.6. WRITING PROGRAMS

Number of children : 4
Expenses : 1000
Number of children : 5
Expenses : 800
Number of children : 3
Expenses : 800
Number of children : 5
Expenses : 1500
Number of children : 0

Number of children Mean expenses per children


1 -
2 275.00
3 300.00
4 250.00
5 230.00
6 -
7 -
8 -
9 -
10 -

▷ 8. Write a program that computes the final balance of a bank account given its initial balance and
the financial movements in a period of time. The deposits are reported as positive numbers, and
withdrawals are reported as negative numbers. When the user inputs 0, it means that the program
must stop gathering movements and display : the final balance, the mean of the deposits, or the message
”no deposit” the mean of the withdrawals, or the message ”no withdrawal”.
Example :
Initial balance ? 1000
Movement ? 100
Movement ? -200
Movement ? 300
Movement ? 400
Movement ? -500
Movement ? 0
Final balance : 1100
Mean of the deposits : 266.66
Mean of the withdrawals : 350

Same question but with a twist : the movements are stopped as soon as the balance is negative.
What must we change in the previous program ?
▷ 9. A Fibonacci series is a series of integers which strats with two numbers a and b. The next numbers
are each the sum of the two previous ones in the series. For example : (3, 7, 10, 17, 27 . . . ). Write an
algorithm that asks for a and b, and then prints a Fibonacci series of 20 terms
▷ 10. Investors want to know the return of any financial investments before committing to them. Given
the investment period in years, the interest rate in percentage, the initial capital in euros, write an
algorithm that computes the return of a term deposit. For each year during the investment, the
program must display the annual return, and the deposit amount at the end of the year.
We know that :
• annual return = deposit amount at the beginning of th year * interest rate
• deposit amount at the end of the year = deposit amount at the beginning of the year + annual
return
▷ 11. At a diving contest, each contestant must do one dive. The jury is made up of nine person. The
judges give a mark between 0 and 10 to each dive.
The final score of the diver is calculated as follows. The lowest and highest marks are not taken
into account. If the lowest or highest mark was given by multiple judges, then it is only deleted once.
In principle, two marks are always deleted. Then, the 7 last marks are added, and this represents the
final score.
Write an algorithm that reads the marks attributed by the judges to a diver. Then, the algorithm
must display the diver’ final score.
▷ 12. Given the list of purchases made by each member of a book club during the past year, write a
program that displays the mean of annual purchases of the members, as well as the list of members
whom spent more than the mean.

Foundations in Business Information Management (INGE1135) 32 SESSIONS - 2024


- Exercises
3.6. WRITING PROGRAMS Session 3

• the user will tell, at the beginning of the execution of the program, the number of members in
the club ;
• all members are identified by a digit code which are not necessarily consecutive ;
• the number of purchases varies from one member to another ;
• when all purchases of a member were entered, the user signals it with sentinel value -1 ;
• if a member did not make any purchase during the year, they still are taken into account when
calculating the mean.
Here is an example of the dialog between the computer and the user :

Number of members ? 5 Purchase (-1 to stop) ? -1

Id code ? 101 Id code ? 315


Purchase (-1 to stop) ? 10 Purchase (-1 to stop) ? -1
Purchase (-1 to stop) ? 50
Purchase (-1 to stop) ? 30 Id code ? 132
Purchase (-1 to stop) ? -1 Purchase (-1 to stop) ? 60
Purchase (-1 to stop) ? 55
Id code ? 57 Purchase (-1 to stop) ? 45
Purchase (-1 to stop) ? 25 Purchase (-1 to stop) ? 90
Purchase (-1 to stop) ? 30 Purchase (-1 to stop) ? -1
Purchase (-1 to stop) ? 45
Purchase (-1 to stop) ? 40 Mean of annual purchases : 130 Euros
Purchase (-1 to stop) ? -1
The following members spent at least 130 Euros :
Id code ? 221 57
Purchase (-1 to stop) ? 20 221
Purchase (-1 to stop) ? 70 132
Purchase (-1 to stop) ? 80

▷ 13. Write an algorithm that displays on screen the highest positive value and highest negative value
given by the user. We assume that the user gives at least one positive and one negative value. You can
make additional hypothesis and assumptions. For example, the user will, or will not, give the number
of value they want to enter.
As an example, if the series of values is -3.1, 4.8, -2.34, -1.42, 2.2, the algorithm prints the following
result :
Highest positive value : 2.2
Highest negative value : -1.42
▷ 14. Write an algorithm that processes weather data. This algorithm must :
1. ask the user for daily temperature readings ; the inputs stop when the user enters 999,
2. compute and display the mean temperature on that period,
3. display the maximum and minimum temperature on that period,
4. compute and display the number of freezing degree days (temperature ⩽ 0).
Here is a use case scenario (user inputs are in bold) :
Temperature on day 1 (999 to stop): 6
Temperature on day 1 (999 to stop): 3
Temperature on day 1 (999 to stop): 1
Temperature on day 1 (999 to stop): -1
Temperature on day 1 (999 to stop): -2
Temperature on day 1 (999 to stop): 0
Temperature on day 1 (999 to stop): 2
Temperature on day 1 (999 to stop): 5
Temperature on day 1 (999 to stop): 0
Temperature on day 1 (999 to stop): 0
Temperature on day 1 (999 to stop): 999

Mean of temperatures : 1.4


Min temperature : -2
Max temperature : 6
Number of freezing degree days : 5

Foundations in Business Information Management (INGE1135) 33 SESSIONS - 2024


- Exercises
Session 3 3.7. ADVANCED EXERCISES ON ALGORITHMIC COMPLEXITY

3.7 Advanced exercises on algorithmic complexity


Warning These exercises are not exam content. However, students who want to dig deeper in computer
science could find them useful. These exercises are typically taken from interviews for Data Scientist
positions.
The objective of these exercises is not the solution per se, but the optimization of the solution in
terms of algorithmic complexity O(n). For most exercises, we aim at linear complexity, which can be
achieved through the use of dictionaries. If we had used lists, algorithmic complexity would typically
by quadratic or cubic.
If you have arrived here, please ask the teaching assistant for tips before beginning these tough
exercises. Should you attempt them, try to find a ”naive” solution first (as if you were doing it
yourself), then reduce your algorithm. Naive and optimized solutions are available for this section.

▷ 1. Write an algorithm that, given two lists of integers a and b, and a target value v, finds whether
a pair of elements taken from a and b sum up to v. If it is the case, return True, and return False
otherwise. For example :

1. a = [1,2,3]
b = [10,20,30,40]
v = 42
40 + 2 = 42
returns True
2. a = [0,0,-5,30212]
b = [-10,40,-3,9]
v = -8
-5 + -3 = -8
returns True
3. a = [1,2,3]
b = [4,5,-10]
v = -1
returns False

▷ 2. Write an algorithm that, given a string of characters, displays the first repeating character. For
example :

1. ”ABCA” displays ”A”


2. ”BCABA” displays ”B”

3. ”ABC” displays null/none

▷ 3. Write an algorithm that, given a list of intervals, returns a number that is in one of the intervals.
Each number must have the same probability of being chosen. We assume that intervals do not overlap.
For example, with the list of intervals [ [12,15], [1,5], [32,35] ], 4 would have the same
probability of being chosen as 12, but 17 could not be chosen. For this exercises, it is not necessary to
use a dict to reduce algorithmic complexity.

Foundations in Business Information Management (INGE1135) 34 SESSIONS - 2024


- Exercises
Session 4

Modules : procedures and functions

4.1 Reading algorithms


▷ 1. What does this algorithm display ?
1 #A l g o r i t h m JeSaisPasCeQueJeFais
2
3 def f o o ( number ) :
4 #PRE : an i n t
5 #POST : a s t r
6 #v a r i a b l e s : v a r : s t r
7
8 i f ( number <5) :
9 v a r = "insignificant"
10 else :
11 v a r = "significant"
12 return ( v a r )
13
14 def main ( ) :
15 #v a r i a b l e s :
16 # i : i n t ; #l o o p c o u n t e r
17 # error : int [ ]
18 # g r a v i t y : chaine
19
20 error = [1 ,5 ,10]
21 f o r i in range ( 0 , 3 ) :
22 gravite = foo ( error [ i ] )
23 print ( "The error is" , g r a v i t y )
24
25 main ( )

▷ 2. We have the following declarations :


#Al gorith m t e s t F o n c t i o n s

def F ( x , y , d ) :
#PRE : x , y : f l o a t ; d : int
#POST : f l o a t
#v a r i a b l e s
.
.
.

def compute ( a , b , m, k , n , c ) :
#PRE : a : f l o a t , b : f l o a t , m : i n t , k : i n t , n : i n t , c : str
#POST : p r i n t s something
#v a r i a b l e s
.
.
.

def main ( ) :
#v a r i a b l e s : day , month , year , p , q : i n t
# hour , r a t e , amount , u , v : f l o a t
# code , c l a s s : s t r
.
.
.

main ( )

For each of the following instructions, determine if it can be used in the main. Justify. We suppose
that all variables are initialized.

35
Session 4 4.2. MODULES IN PYTHON : TUTORIAL

1. montant = F ( 3 . 1 4 1 5 , r a t e , month )

2. compute ( u , v , 2 , p , q , c o d e )

3. taux = F( hour , day , 2 )

4. print (F ( 0 , 0 , 0 ) )

5. compute ( hour , abs ( −1) , 2 , day , y e a r , c l a s s )

6. F( hour , r a t e , month )

7. compute ( ’6’ , hour , 3 . 1 4 1 5 , 1 3 , y e a r , c l a s s )

8. hour = 2 ∗ F ( 3 . 1 4 1 5 , amount ) / ( 2 . 7 1 ∗ r a t e )

9. compute ( 3 . 1 4 1 5 ∗ hour , 3 . 1 4 1 5 , 2 , day , y e a r , c l a s s )

10. amount = F ( 3 . 1 4 1 5 ∗ hour , 2 . 7 1 / r a t e , 2 )

11. compute ( 3 . 1 4 1 5 , 1 . 5 ∗ hour , 2 , day , y e a r , c l a s s )

12. if ( month == 2 ) :
y e a r = F( hour , F( r a t e , 3 . 1 4 1 5 , 2 ) , day )

13. while ( u > 0 ) :


compute ( u , v , 2 , p , q , c o d e )

4.2 Modules in python : tutorial


Modules are useful when coding, especially for reducing a tough problem in many easy ones. That way,
it is much easier to solve smaller, easier problems, and then articulating them together to answer the
original problem.
For example :
The grades attributed to students are real numbers, and their maximum is 20. The jury declares
that a student fails if :
1. their average is below 10.5
2. or if there are a certain number of grades below 10 :
• one grade strictly below 8
• or two grades between 8 and 10 (10 not included)
• or inferior results.
Write an algorithm that, given the student’s grades (of which there are 10) displays ”has failed”
or ”has passed” according to the rule.
So, the program must compute the mean, the number of failures, and the balances (the grades
between 8 and 10).
The program must then compute each grade’s validity : if they are not between 0 and 20, then
the user must give a valid grade. Moreover, the grades between 9.5 and 10 must automatically
become 10.
The user enters the students names and their grades for each of them. Then, depending,
displays the messages ”student [NAME] has failed” or ”student [NAME] has passed”. Then,
the user must enter ”END” as student name to stop the program.
At the end, the program displays the name of the student with the best average.
Let us try to solve this question by thinking in modules. This problem is composed of several small
problems :

Foundations in Business Information Management (INGE1135) 36 SESSIONS - 2024


- Exercises
4.2. MODULES IN PYTHON : TUTORIAL Session 4

• gathering the grades and making sure that they are valid (grade > 20 or grade < 0 not accepted),
and transforms grades between 9.5 and 10 to 10.
• on the basis of the grades, determine :

– the average,
– the number of failures (cote < 8),
– the number of balances (8 ≤ cote < 10)
• decide, based the previous results, if the student passed or failed.

It appears relevant to use lists to keep track of the students’ grades. On the modules are written,
we can articulate them in the main().
We can do the modules in any order we want. Let us start by the very last one.
We are going to create a module that, given the average, the number of failures, and the number
of balances, decides if the student passed. It is obvious that avg, nb failures, and nb balances are the
parameters of this function. Then, a True or False boolean (passed or failed) will be returned.
This is the function success :
1 def s u c c e s s ( avg , n b f , n b b a l ) :
2 #PRE : a f l o a t avg , an i n t n b f and an i n t n b b a l
3 #POST : r e t u r n s a b o o l : True i f p a s s e d ; F a l s e i f f a i l e d ( see jury r u l e s )
4 i f ( avg <10.5 or n b f >0 or n b b a l >1) :
5 return F a l s e
6 else :
7 return True

Now, let us code a function that returns the average of the elements in a list that is given as argument
:
1 def a v e r a g e ( l ) :
2 # PRE : a l i s t ( l ) o f l e n g t h 10 , f i l l e d w i t h i n t or f l o a t
3 # POST : r e t u r n s a f l o a t ( avg ) : t h e a v e r a g e o f t h e e l e m e n t s i n l i s t l.
4 sum = 0
5 f o r i in range ( 0 , 1 0 ) :
6 sum=sum+l [ i ]
7
8 avg = f l o a t (sum) /10
9 return avg

In this function, we take advantage of the fact that we know the number of courses is 10. We could
rethink this function so that it works with any number of courses. So the function must be able to deal
with lists of varying length.
1 def a v e r a g e ( l ) :
2 # PRE : a l i s t ( l ) ( any l e n g t h ) , f i l l e d w i t h i n t or f l o a t
3 # POST : r e t u r n s a f l o a t ( avg ) : t h e a v e r a g e o f t h e e l e m e n t s i n l i s t l.
4 sum = 0
5 f o r i in l :
6 sum=sum+i
7
8 avg = f l o a t (sum) /10
9 return avg

Foundations in Business Information Management (INGE1135) 37 SESSIONS - 2024


- Exercises
Session 4 4.2. MODULES IN PYTHON : TUTORIAL

Now, we can try to solve the problem of the two functions that return the number of failures and the
number of balances, on the basis of a list of grades. In the following, we keep the principle of unknown
list length.
1 def n b f a i l u r e s ( l ) :
2 # PRE : a l i s t ( l ) or n u m e r i c a l v a l u e s
3 # POST : r e t u r n s t h e number o f v a l u e s i n f e r i o r t o 8
4 count=0
5 f o r i in l :
6 i f i <8 :
7 count=count+1
8
9 return count
10
11 def n b b a l a n c e ( l ) :
12 # PRE : a l i s t ( l ) or n u m e r i c a l v a l u e s
13 # POST : r e t u r n s t h e number o f v a l u e s b e t w e e n 8 and 10 (10 n o t i n c l u d e d )
14 count=0
15 f o r i in l :
16 i f i >=8 and i <10 :
17 count=count+1
18
19 return count

Now we build a function that asks 10 times the grades to the user. We keep in mind the case where
the user misinputs a grade, and we modify any grade between 9, 5 and 10 to 10. This function has no
parameter and returns a list of grandes.
1 def c o l l e c t ( ) :
2 # PRE : n o t h i n g
3 # POST : r e t u r n s a l i s t o f 10 f l o a t s b e t w e e n 0 and 20
4 l =[]
5 f o r i in range ( 0 , 1 0 ) :
6 g r a d e=f l o a t ( input ( "A grade : " ) )
7 while ( grade <0 or grade >20) :
8 g r a d e=f l o a t ( input ( "Invalid grade, try again : " ) )
9
10 i f ( grade >=9.5 and grade <10) :
11 g r a d e =10
12
13 l . append ( g r a d e )
14
15 return l

We could also modify the function so that it works with any number of grades to collect (so we keep
the same philosophy as earlier). The easiest solution for this is to add a parameter that represents the
number of grades to collect. In the case where no parameter is given, the number of grades will be 10
by default.
1 def c o l l e c t ( n b v a l =10) :
2 # PRE : n o t h i n g
3 # POST : r e t u r n s a l i s t o f f l o a t s (10 by d e f a u l t ) b e t w e e n 0 and 20
4 l =[]
5 f o r i in range ( 0 , n b v a l ) :
6 g r a d e=f l o a t ( input ( "A grade : " ) )
7 while ( grade <0 or grade >20) :
8 g r a d e=f l o a t ( input ( "Invalid grade, try again : " ) )
9
10 i f ( grade >=9.5 and grade <10) :
11 g r a d e =10
12
13 l . append ( g r a d e )
14
15 return l

Thanks to this parameter with a value by default, if the function is called by writing l grade=collect(18),
the parameter nb val will take 18. However, if the function is called using l cote=collect(), noth-
ing is specified and nb val takes its default value of 10. Note also the change in upper bound in for
i in range(0, nb val).
Given all the functions, it is time to construct a main() procedure to articulate them all together
to answer the problem. Clearly, this procedure contains a while because we have to collect data until

Foundations in Business Information Management (INGE1135) 38 SESSIONS - 2024


- Exercises
4.2. MODULES IN PYTHON : TUTORIAL Session 4

the user inputs END. Note that we do not anticipate the case where we have multiple students with the
best average. You could try to implement that for fun.
1 def main ( ) :
2
3 best avg = 0
4 best name = ""
5
6 s t u d e n t n a m e=input ( "Enter the student name (’END’ to stop) " )
7 while ( s t u d e n t n a m e !="END" ) :
8 l g r a d e=c o l l e c t ( )
9
10 avg=a v e r a g e ( l g r a d e )
11 n b f=n b f a i l u r e ( l g r a d e )
12 n b b a l=n b b a l a n c e ( l g r a d e )
13
14 i f avg>=b e s t a v g :
15 b e s t a v g=avg
16 best name=s t u de nt n a m e
17
18 i f ( s u c c e s s ( avg , n b f , n b b a l )==True ) :
19 print ( "Student" , student name , "has passed" )
20 else :
21 print ( "Student" , student name , "has failed" )
22
23
24 s t u d e n t n am e=input ( "Enter the student name (’END’ to stop) " )
25
26
27 print ( "Student" , best name , "has the best average :" , b e s t a v g )

In the end, the program looks like this (do not forget the instruction main() at the end !) :
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 def s u c c e s s ( avg , n b f , n b b a l ) :
4 #PRE : a f l o a t avg , an i n t n b f and an i n t n b b a l
5 #POST : r e t u r n s a b o o l : True i f p a s s e d ; F a l s e i f f a i l e d ( see jury r u l e s )
6 i f ( avg <10.5 or n b f >0 or n b b a l >1) :
7 return F a l s e
8 else :
9 return True
10
11 def c o l l e c t ( n b v a l =10) :
12 # PRE : n o t h i n g
13 # POST : r e t u r n s a l i s t o f f l o a t s (10 by d e f a u l t ) b e t w e e n 0 and 20
14 l =[]
15 f o r i in range ( 0 , n b v a l ) :
16 g r a d e=f l o a t ( input ( "A grade : " ) )
17 while ( grade <0 or grade >20) :
18 g r a d e=f l o a t ( input ( "Invalid grade, try again : " ) )
19 i f ( grade >=9.5 and grade <10) :
20 g r a d e =10
21 l . append ( g r a d e )
22 return l
23
24 def a v e r a g e ( l ) :
25 # PRE : a l i s t ( l ) ( any l e n g t h ) , f i l l e d w i t h i n t or f l o a t
26 # POST : r e t u r n s a f l o a t ( avg ) : t h e a v e r a g e o f t h e e l e m e n t s i n l i s t l.
27 sum = 0
28 f o r i in l :
29 sum=sum + i
30
31 avg = f l o a t (sum) /10
32 return avg
33
34 def n b f a i l u r e ( l ) :
35 # PRE : a l i s t ( l ) or n u m e r i c a l v a l u e s
36 # POST : r e t u r n s t h e number o f v a l u e s i n f e r i o r t o 8
37 count=0
38 f o r i in l :
39 i f i <8 :
40 count=count+1
41 return count
42

Foundations in Business Information Management (INGE1135) 39 SESSIONS - 2024


- Exercises
Session 4 4.2. MODULES IN PYTHON : TUTORIAL

43 def n b b a l a n c e ( l ) :
44 # PRE : a l i s t ( l ) or n u m e r i c a l v a l u e s
45 # POST : r e t u r n s t h e number o f v a l u e s b e t w e e n 8 and 10 (10 n o t i n c l u d e d )
46 count=0
47 f o r i in l :
48 i f i >=8 and i <10 :
49 count=count+1
50 return count
51
52
53 def main ( ) :
54
55 best avg = 0
56 best name = ""
57
58 s t u d e n t n a m e=input ( "Enter the student name (’END’ to stop) " )
59 while ( s t u d e n t n a m e !="END" ) :
60 l g r a d e=c o l l e c t ( )
61
62 avg=a v e r a g e ( l g r a d e )
63 n b f=n b f a i l u r e ( l g r a d e )
64 n b b a l=n b b a l a n c e ( l g r a d e )
65
66 i f avg>=b e s t a v g :
67 b e s t a v g=avg
68 best name=s t ud e n t n a m e
69
70 i f ( s u c c e s s ( avg , n b f , n b b a l )==True ) :
71 print ( "Student" , student name , "has passed" )
72 else :
73 print ( "Student" , student name , "has failed" )
74
75
76 s t u d e n t n a m e=input ( "Enter the student name (’END’ to stop) " )
77
78 print ( "Student" , best name , "has the best average :" , b e s t a v g )
79
80
81 main ( )

Foundations in Business Information Management (INGE1135) 40 SESSIONS - 2024


- Exercises
4.3. IMPLEMENTING FUNCTIONS Session 4

4.3 Implementing functions


▷ 1. We give a mean() function that, as indicated in the PRE and POST, takes a list as argument, and
returns its mean.
1 def mean ( n ) :
2 #PRE : n − a l i s t o f numbers
3 #POST : m − t h e mean o f number i n n
4 s = 0
5 f o r number in n :
6 s = s + nombre
7 m = s / len ( n )
8 return m

We ask you to use this function to display the following :

The mean of [4, 5, 6, 7] is 5.5


The mean of [2, 3] is 2.5
▷ 2. We have the following function :
1 def c o l l e c t ( q u e s t i o n ) :
2 #PRE : q u e s t i o n − a q u e s t i o n o f t y p e s t r t h a t w i l l be p o s e d x times , u n t i l t h e u s e r
inputs ’ stop ’
3 #POST : l − a l i s t w i t h answers t o t h e q u e s i t o n p o s e d x t i m e s
4 # t h e answers t y p e w i l l be f l o a t
5 l = []
6 print ( "Write ’stop’ to stop collecting data" )
7 reponse = input ( question )
8 while r e p o n s e != "stop" :
9 reponse = f l o a t ( reponse )
10 l . append ( r e p o n s e )
11 reponse = input ( question )
12 return l

Understand what this function does, then implement it in order to obtain the following :

Write ’stop’ to stop collecting data


Give a number to compute a mean : 3
Give a number to compute a mean : 5
Give a number to compute a mean : 6
Give a number to compute a mean : stop
The answers to the question ’ Give a number to compute a mean : ’ are : [3.0, 5.0, 6.0]

▷ 3. Combine the two functions used in the previous exercises to obtain this display on screen :

Write ’stop’ to stop collecting data


Give a number to compute a mean : 10
Give a number to compute a mean : 13
Give a number to compute a mean : 8
Give a number to compute a mean : 15
Give a number to compute a mean : stop
The mean of [10.0, 13.0, 8.0, 15.0] is 11.5

▷ 4. Take the collect() function from above, and modify it to obtain a new function collect str()
that will gather variables of types str instead of type float. This function could, for example, be
used to gather a series of names.

4.4 Small exercises on modules


To represent x ∈ Rn , we use a tuple (an immutable list) of n floats.
n
X
▷ 1. Write and test a function that computes and returns x i = x 1 + x 2 + · · · + x n , x ∈ Rn .
i=1

Foundations in Business Information Management (INGE1135) 41 SESSIONS - 2024


- Exercises
Session 4 4.5. WRITING METHODS

n
X
▷ 2. Write and test a function that computes and returns (−1)i−1 xi , x ∈ Rn .
i=1
i−1
Try to think of a way without explicitly computing (−1) .
n−1
X
▷ 3. Write and test a function that computes and returns (xi+1 − xi )(xi+1 − xi ) , x ∈ Rn .
i=1

4.5 Writing methods


▷ 1. Display the sum of the n first factorials (n is given by the user). Reminder : n! = 1∗2∗3∗...∗(n−1)∗n
(n must be a positive integer).

n
X n
X
i! = (1 ∗ 2 ∗ 3 ∗ ... ∗ (i − 1) ∗ i)
i=1 i=1

We divide the problem : first, we must calculate a factorial, then we must do a sum of factorials. The
first problem is ”included” in the the second one. So we will solve the first one by creating a function.

▷ 2. Write a function power that, given two integers > 0 h and q, returns hq .
Then, use that function in a program that computes :
n
X n
X
ib and bi ,
i=1 i=1

n and b are positive integers given by the user.

▷ 3. 1. Write a function that, given a real number x and a natural integer n, compute xn by using
the following definition : (
1 si n = 0,
xn =
x · xn−1 si n > 0.

2. Write a function that, given a real number x and an integer n, computes xn by using the following
definition :
1
xn = −n , ∀n < 0.
x
▷ 4. 1. Write a function Facto that returns the factorial of a given integer.

2. Use the Facto function to write a fonction Arr that takes the arguments k and n and computes
Akn as defined by
n!
Akn = .
(n − k)!

3. The use Facto function to write a function Comb that takes two natural integers k and n, and
computes the coefficient Cnk as defined by

n!
Cnk = .
(n − k)!k!

4. With the help of the functions created, write a program that computes and displays C42 as well as
C41 − C43 . The display should be 6 and 0.

5. Write an algorithm that allows the user to compute any coefficient and as many times as wanted.

▷ 5. 1. Write a function that fills a list with integers given by the user.

2. Write a function that displays on screen the elements of a list of integers.

3. Write a program that creates a list of integers, then displays them back to the user once they
have entered all the integers they wanted.

Foundations in Business Information Management (INGE1135) 42 SESSIONS - 2024


- Exercises
4.6. WRITING PROGRAMS Session 4

▷ 6. 1. Write a function that determines if a list of integers is increasing. For example,

2 7 7 11 12

t[0] t[1] t[2] t[3] t[4]

is increasing while

2 8 7

r[0] r[1] r[2]

is not.
2. Write a function that determines if a list of integers is decreasing.

4.6 Writing programs


▷ 1. Write a procedure that, given a time in seconds, returns the time in hours, minutes, and seconds.
Do not forget to write the #PRE and #POST.
▷ 2. Write a function InInterval that takes two integers a and b and a float x, and returns True if
a < x < b and False otherwise.
▷ 3. A car dealership employs 20 employees that are paid in the following way :
500.00 e per month + 100.00 e per car sold + 5 % of the total amount the sales.
Write a program that allows the business manager to compute their employees’ salary, as well as
the share of cars sold by each of them.
The total amount of sales will be computed : it is the sum of each employees’ sales.
The program should display the list of employees’ names, their salary, and their share of sales.

Start by determining what are the different information that the user should give, and what infor-
mation should the computer display.

Foundations in Business Information Management (INGE1135) 43 SESSIONS - 2024


- Exercises
Session 4 4.6. WRITING PROGRAMS

Foundations in Business Information Management (INGE1135) 44 SESSIONS - 2024


- Exercises
Solutions

45
Solutions

Foundations in Business Information Management (INGE1135) 46 SOLUTIONS - 2024


- Exercises
Solutions

S1 : Assignments, inputs and ouputs and first steps with Python


Basic exercices
Next variables
instruction A B
A=1 / /
▷ 2. B=2 1 /
A=B 1 2
B=A 2 2
end 2 2

This algorithm assigns to variable A the initial value of variable B. The value of B does not change.

Next variables
instruction A B
A ←1 / /
▷ 3. B ←2 1 /
B ←A 1 2
A ←B 1 1
end 1 1

No, this algorithm assigns A’s initial value to B. A does not change.

Next variables
instruction A B C
1 / / /
2 1 / /
3 1 2 /
▷ 4.
4 1 2 3
5 6 2 3
6 6 3 3
7 6 3 9
end 6 6 9

At the end, A contains 6, B contains 6, and C contains 9.

Next variables
instruction A B C
1 / / /
2 1 / /
3 1 2 /
4 1 2 3
▷ 5.
5 3 2 3
6 3 2 2
7 3 3 2
8 1 3 2
9 1 4 2
end 1 4 4

At the end, A contains 1, B contains 4, and C contains 4.

▷ 6. 1. No. The order cannot be changed.

Foundations in Business Information Management (INGE1135) 47 SOLUTIONS - 2024


- Exercises
Solutions

2. Yes. The order can be changed.

3. No. The order cannot be changed.

▷ 7. The instruction blocks do not yield the same results.

1. The algorithm swaps the value contained in xx, yy, zz as follows : xx → yy, yy → zz, zz → xx.

2. Same as above.

3. The algorithm swaps the value contained in xx, yy, zz as follows : xx → zz, zz → yy, yy → xx.
They swap the other way around.

▷ 8. 1. Depth = 19 − H e i g h t

2. Bul = 17

3. Bul = B r o l ∗ 2 + 10

▷ 9. The algorithm swaps the values contained in A, B and C as follows : A → B, B → C, C → A.

▷ 10. The algorithm swaps the values contained in A, B and C as follows : A → C, C → B, B → A. It


swaps them the other way around.

▷ 11. This program asks the user for parameters of the quadradic formula : a, b, c for the quadratic formula
f (x) = ax2 + bx + c. Then, the program asks the user to provide a specific x, and calculates f (x).

Writing programs
▷ 1. Taxes
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 BASE = 5 0 0 . 0
4 RATE = 4 7 . 5
5 REVENUE MIN = 2 0 0 0 . 0
6 #f l o a t i s f o r r e a l numbers
7 #i n t i s f o r i n t e g e r
8 #b o o l i s f o r b o o l e a n
9 #s t r i s f o r c h a r a c t e r s t r i n g s
10
11 t a x a b l e r e v e n u e = f l o a t ( input ( "What is your revenue ?(between 2000 and 3000 euros) :" ) )
12
13 tax = BASE + (RATE/ 1 0 0 ) ∗ ( t a x a b l e r e v e n u e −REVENU MIN)
14
15 print ( "You have to pay" , tax , "euros" )

▷ 3. Disc :
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 import math
4
5 r= f l o a t ( input ( "What is the radius ? (in mm) : " ) )
6 p e r i m e t e r = 2 . 0 ∗ math . p i ∗ r
7 print ( "The circle’s perimeter is :" , p e r i m e t e r s , " mm" )

▷ 5. Quadratic

Foundations in Business Information Management (INGE1135) 48 SOLUTIONS - 2024


- Exercises
Solutions

1 #a l g o r i t h m SecondDegre
2 #v a r i a b l e s : a , b , c , x , ordonnee : float
3
4 a = f l o a t ( input ( " parameter a for x2 ? " ) )
5 b = f l o a t ( input ( " parameter b for x ? " ) )
6 c = f l o a t ( input ( " parameter c ? " ) )
7 print ( " Your equation is y == " , a , " x2 + " , b , " x + " , c )
8 x = f l o a t ( input ( " Value of x ? " ) )
9 o r d i n a t e = ( a ∗ ( ( x∗x ) ) + ( b∗x ) + c
10 print ( " y(" , x , ")" , " yields " , o r d i n a t e )

▷ 6. Exchange
1 #a l g o r i t h m EchangeDeuxVal
2 #v a r i a b l e s : A, B, tmp : i n t
3 A = i n t ( input ( " first value A ? " ) )
4 B = i n t ( input ( " second value B ? " ) )
5 print ( " Initial values :" )
6 print ( "A == " , A)
7 print ( "B == " , B)
8
9 # swapping v a l u e s i n A and B
10 tmp = A
11 A = B
12 B = tmp
13 print ( " Values after swap :" )
14 print ( "A == " , A)
15 print ( "B == " , B)

S2 : Decision & choices in Python


Basic exercises

Introduction exercises
▷ 1. 1. 7

2. 4

3. 4

▷ 2. 1. 6

2. 4

3. 6

▷ 2.5. This program takes three integers as input, and displays them in ascending order.

▷ 4. The algorithm prints OUT for value 1515, BINGO for 1600, OUT for 1900, and BINGO for 2004. It
determines whether the year entered is a leap year or not.

▷ 5. The algorithm prints Bravo ! for 6436, and Broken ! for 5346.

▷ 6. In order : D, Z, D, Y, D, Z, D, X.

▷ 7. The correct one is Ordre3B.

Writing programs
▷ 1. Income tax

Foundations in Business Information Management (INGE1135) 49 SOLUTIONS - 2024


- Exercises
Solutions

1 #a l g o r i t h m LesImpots
2 #v a r i a b l e s : t a x a b l e i n c o m e , t a x : float
3 #c o n s t a n t e s : ( r e e l )
4 BASE = 5 0 0 . 0
5 RATE = 4 7 . 5
6 INCOME MIN = 2 0 0 0 . 0
7 INCOME MAX = 3 0 0 0 . 0
8
9 print ( " Please enter your income " )
10 print ( " ( between " , INCOME MIN, " and " , INCOME MAX, " euros ) : " )
11 t a x a b l e i n c o m e = f l o a t ( input ( ) )
12
13 if ( ( INCOME MIN <= t a x a l b e i n c o m e ) and ( t a x a b l e i n c o m e <= INCOME MAX ) ) :
14 t a x = BASE + (RATE/ 1 0 0 ) ∗ ( t a x a b l e i n c o m e − INCOME MIN)
15 print ( " The income tax is " , tax , " euros " )
16 else :
17 print ( " Invalid income ! " )
18 print ( "It must be between " , INCOME MIN, " and " , INCOME MAX, " euros " )

▷ 2. Absolute value
1 #a l g o r i t h m V a l e u r a b s o l u e
2 #v a r i a b l e s : X, a b s o l : f l o a t
3
4 X = f l o a t ( input ( " Input a float ." ) )
5 i f (X >= 0 ) :
6 absol = X
7 else :
8 a b s o l = −X
9 print ( " The absolute value of " ,X, " is " , a b s o l )

▷ 3. Leap year
1 #a l g o r i t h m B i s s e x t i l e
2 #v a r i a b l e s : A : i n t e g e r
3
4 A = i n t ( input ( " Input an integer " ) )
5 i f ( (A % 4 ) == 0 ) :
6 i f ( (A % 1 0 0 ) != 0 ) :
7 print (A, "is a leap year " )
8 e l i f ( (A % 4 0 0 ) == 0 ) :
9 print (A, "is a leap year " )
10 else :
11 print (A, " is not a leap year " )
12 else :
13 print (A, " is not a leap year " )

▷ 4. Post office
1 #a l g o r i t h m C o l i s P o s t a l
2 #v a r i a b l e s : l e n g t h , width , h e i g h t : f l o a t
3 # w e i g h t , t a x , volume : f l o a t
4 print ( " Please , enter the length , width , and height of the parcel (in cm) : " )
5 l o n g u e u r = f l o a t ( input ( " length ? " ) )
6 l a r g e u r = f l o a t ( input ( " width ? " ) )
7 h a u t e u r = f l o a t ( input ( " height ? " ) )
8 p o i d s = f l o a t ( input ( " Enter the weight of the parcel (in kg) : " ) )
9
10 if( ( w e i g h t > 1 0 ) or ( l e n g t h > 5 0 ) or ( width > 5 0 ) or ( h e i g h t > 5 0 ) ) :
11 print ( " Invalid parcel " )
12 else :
13 # volume i n dm3
14 volume = ( l e n g t h ∗ width ∗ h e i g h t ) / 1 0 0 0 . 0
15 # regular tax
16 tax = 2.5 0
17
18 # weight tax
19 i f (5 < weight ) :
20 tax = tax + 0.5 0
21
22 if ( volume > 2 7 ) :
23 t a x = t a x + 0 . 1 5 ∗ ( volume − 2 7 )
24
25 print ( " Taxes are :" , tax , " euros " )

▷ 5. Mentions
1 #a l g o r i t h m Grade
2 #v a r i a b l e s : pc : float
3

Foundations in Business Information Management (INGE1135) 50 SOLUTIONS - 2024


- Exercises
Solutions

4 pc = f l o a t ( input ( " Please , enter your grade : " ) )


5
6 if ( pc < 6 0 ) :
7 print ( " Adjourned " )
8 e l i f ( pc < 6 9 ) :
9 print ( " Satisfaction " )
10 e l i f ( pc < 7 9 ) :
11 print ( " Distinction " )
12 e l i f ( pc < 8 6 ) :
13 print ( " Great distinction " )
14 else :
15 print ( " Greatest distinction " )

▷ 6. Grand mother birth day.

1 #−∗− c o d i n g : Utf −8 −∗−


2
3 print ( "This progrma finds the day of the week of a date between 1900 and 1999" )
4
5 y e a r = i n t ( input ( "What year ?" ) )
6 month = i n t ( input ( "What month ? (a number between 1 and 12)" ) )
7 d = i n t ( input ( "What day of the month ? (a number between 1 and 31)" ) )
8
9 # a = t h e two l a s t d i g i t s of the b i r t h year
10 a = i n t ( y e a r %100)
11
12 # b = t h e e u c l i d i a n r e s u l t o f A//4 ( i n t e g e r )
13 # i f i t i s a l e a p y e a r AND t h e b i r t h month i s January or February , we s u b t r a c t 1 t o b .
14
15 b = a //4
16 i f ( a%4 == 0 ) and ( ( month == 1 or month == 2 ) ) :
17 i f ( a%100 != 0 ) :
18 b = b − 1
19 e l i f ( a%400 == 0 ) :
20 b = b − 1
21
22 # m = we a s s i g n an i n t e g e r a c c o r d i n g t o t h e b i r t h month
23 i f ( month == 1 or month == 10 ) :
24 m = 0
25 e l i f ( month == 5 ) :
26 m = 1
27 e l i f ( month == 8 ) :
28 m = 2
29 e l i f ( month == 2 or month == 3 or month == 11 ) :
30 m = 3
31 e l i f ( month == 6 ) :
32 m = 4
33 e l i f ( month == 9 or month == 1 2 ) :
34 m = 5
35 e l i f ( month == 4 or month == 7 ) :
36 m = 6
37
38 #On e n t r e dans l e v i f :
39 res = a + b + m + d
40
41 rest = res % 7
42
43 i f ( r e s t == 0 ) :
44 print ( d , "/" , month , "/" , year , "was a sunday " )
45 e l i f ( r e s t == 1 ) :
46 print ( d , "/" , month , "/" , year , "was a monday " )
47 e l i f ( r e s t == 2 ) :
48 print ( d , "/" , month , "/" , year , "was a tuesday" )
49 e l i f ( r e s t == 3 ) :
50 print ( d , "/" , month , "/" , year , "was a wednesday" )
51 e l i f ( r e s t == 4 ) :
52 print ( d , "/" , month , "/" , year , "was a thursday" )
53 e l i f ( r e s t == 5 ) :
54 print ( d , "/" , month , "/" , year , "was a friday" )
55 e l i f ( r e s t == 6 ) :
56 print ( d , "/" , month , "/" , year , "was a saturday" )

Foundations in Business Information Management (INGE1135) 51 SOLUTIONS - 2024


- Exercises
Solutions

S3 : Lists and loops

Basic exercises : reading algorithms

▷ 1. Response = "hello"
Count = 5
Attempt = input ( "Give me a word" )
while ( ( Attempt != Response ) and ( Count > 0 ) ) :
Count = Count − 1
Attempt = input ( "Give me a word" )

The boolean is (Attempt == Response)OU (Count == 0)

▷ 3. This algorithm computes and displays the sum of n first integers :

n
X
i
i=1

State of the algorithm if the user gives 4 :

variables N¡ next. Comments


i s n instr.
/ / / 5
/ / 4 6
/ 0 4 7
1 0 4 8 inside the loop
1 1 4 7
2 1 4 8 inside the loop
2 3 4 7
3 3 4 8 inside the loop
3 6 4 7
4 6 4 8 inside the loop
4 10 4 7
5 10 4 10 not inside the loop
/ 10 4 fin

▷ 4. This algorithm computes and display the product of the first n integers :

n
Y
i
i=1

States of the algorithm if the user input is 5 :

Foundations in Business Information Management (INGE1135) 52 SOLUTIONS - 2024


- Exercises
Solutions

N¡ proch. variables Commentaires


instr. i p n
5 / / /
6 / / 4
7 / 1 5
8 1 1 5 inside the loop
7 1 1 5
8 2 1 5 inside the loop
7 2 2 5
8 3 2 5 inside the loop
7 3 6 5
8 4 6 5 inside the loop
7 4 24 5
8 5 24 5 inside the loop
7 5 120 5
10 6 120 5 not inside the loop
fin / 120 5

▷ 5. For 8, the computers displays Bingo ! and for 10 it displays Cassé !. What do these algorithms do ?
What are the differences between them ?

▷ 6. We obtain :

i 0 1 2 3 4 5 6 7 8 9
(a) numbers[i] 10 9 8 7 6 5 4 3 2 1
(b) numbers[i] 0 0 1 1 2 2 3 3 4 4
(c) numbers[i] 0 1 4 9 16 25 1 4 9 16
(d) numbers[i] 0 1 2 0 1 2 0 1 2 0

▷ 7. 1. x=[1,2,3,4]
1 1
2 3
3 6
4 10

2. x=[9,6,-1]
9 9
6 15
-1 14

▷ 8. Display : 25 13 22 64 11 8

The user’s inputs : (this is one of many possibilities) 3 6 1 13 1 2 4 8 5 8

▷ 9. In bold, the user’s inputs

How many values do you wish to input ? 3


Enter an integer 2
Enter an integer 4
Enter an integer 4
(2+4+4)/3 = 3.33

The specifications are : Write a program that computes the mean of integers given by the user.
The user will input how many values they wish to enter. The program must display the details of the
calculations at the end.

Foundations in Business Information Management (INGE1135) 53 SOLUTIONS - 2024


- Exercises
Solutions

▷ 10. States of the algorithm if the values given are 2,7,3,2,-1 :


variables N¡ next
v s n instruction
... ... ... ...
2 0 0 15 True
2 0 0 17
2 2 0 18
2 2 1 21
7 2 1 15 True
7 2 1 17
7 9 1 18
7 9 2 21
3 9 2 15 True
3 9 2 17
3 12 2 18
3 12 3 21
2 12 3 15 True
2 12 3 17
2 14 3 18
2 14 4 21
-1 14 4 15 False
-1 14 4 24 ...
... ... ... ...

At line 26, the program displays : "We obtained : 14 and also : 3.5

States of the algorithm if the only value given is -1 :


variables N¡ next
v s n instruction
... ... ... ...
-1 0 0 15 False
-1 0 0 24 False
-1 0 0 28
-1 0 0 29
fin

At line 29, the algorithm displays : !?

This algorithm computes the mean of values given by the user. The number of values given by the
user is unknown. The user will have to input -1 to stop entering values.

▷ 11. At line 12, the algorithm displays : We obtained : 14 and also : 3.5
If the only value given is 0, the algorithm displays at line 14 : !?

This algorithm computes and displays the mean of a series of values given by the user. The algorithm
asks the user for how many values they want to enter first.

▷ 12. In bold, the user’s inputs.

How many inputs ? 5


Give a first value : 3
Give value number 2 : 2
Give value number 3 : 10
Give value number 4 : 1

Foundations in Business Information Management (INGE1135) 54 SOLUTIONS - 2024


- Exercises
Solutions

Give value number 5 : 9


We obtain : 1

This algorithm reads the number of inputs the user wishes to enter. Then, it gathers the values,
and displays the smallest of them.

▷ 13. This algorithm reads the number of inputs the user wishes to enter. Then, it gathers the values, and
displays the largest of them.

▷ 14. This displays a Fibonacci series. It is a series that begins with two numbers a and b. Then each
subsequent element is the sum of the two previous ones. For example : (3, 7, 10, 17, 27, 44, 71 . . . ). Here,
the user specifies the number of values to display and enters the first two integers.

Simple exercises with loops & lists


▷ 1. Romani ite domum
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 t e x t = "Romani ite domum"
4
5 f o r i in range ( 1 , 5 1 ) :
6 print ( t e x t , "\t" , t e x t )

▷ 2. Multiples of 7
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 f o r i in range ( 1 , 2 1 ) :
4 print ( i ∗ 7 )

With lists
1 #−∗− c o d i n g : Utf −8 −∗−
2
3 t = [ ] #we c r e a t e an empty l i s t
4 f o r i in range ( 0 , 2 1 ) :
5 t . append ( i ∗ 7 )
6 f o r i in range ( 1 , 2 1 ) :
7 print ( i , "x 7 =" , t [ i ] )

▷ 3. Conversion EUR/CAD
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 s euro = 1
4 while s e u r o <=16384:
5 print ( s e u r o , "euro(s) =" , s e u r o ∗ 1 . 6 5 , "dollar(s)" )
6 s e u r o = s e u r o ∗2

With lists :
1 # −∗− c o d i n g : cp1252 −∗−
2
3 rate = 1.65
4 i = 0
5 tab EUR = [ 1 ]
6 tab CAD = [ tab EUR [ 0 ] ∗ r a t e ] #we i n i t i a l i z e t h e f i r s t v a l u e i n each t a b l e
7
8
9 while ( tab EUR [ i ] <=16384/2) : #when t h e computer i s a t 8000 , t h e r e i s one more
o p e r a t i o n t o make
10 tab EUR . append ( tab EUR [ i ] ∗ 2 ) #g e o m e t r i c p r o g r e s s i o n
11 tab CAD . append ( tab EUR [ i +1]∗ r a t e )
12 i = i + 1
13 f o r j in range ( 0 , len ( tab EUR ) ) :
14 print ( tab EUR [ j ] , "euros = " , tab CAD [ j ] , "CAD" )

Foundations in Business Information Management (INGE1135) 55 SOLUTIONS - 2024


- Exercises
Solutions

▷ 4. Triple series
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 num = 1
4
5 f o r i in range ( 1 , 1 3 ) :
6 print (num)
7 num=num∗3

Avec des listes


1 # −∗− c o d i n g : cp1252 −∗−
2
3
4 t = [ i n t ( input ( "What is the first number of the series ? " ) ) ] #we p u t t h e u s e r ’ s i n p u t
in a l i s t d i r e c t l y
5
6 f o r i in range ( 1 , 1 2 ) :
7 t . append ( t [ i −1 ]∗3 )
8
9 f o r i in range ( 0 , len ( t ) ) :
10 print ( i +1 ,"th term :" , t [ i ] )

▷ 5. Multiples of 7 and 3 star


1 # −∗− c o d i n g : Utf −8 −∗−
2
3 #i n t h e q u e s t i o n , t h e example i s on one l i n e
4
5 s t r i n g = ""
6 f o r i in range ( 1 , 8 ) :
7 num = i ∗7
8 s t r i n g = s t r i n g+" "+s t r (num)
9 i f num%3 ==0:
10 s t r i n g = s t r i n g +" * "
11
12 print ( s t r i n g )

With lists :
1 # −∗− c o d i n g : cp1252 −∗−
2 t = []
3 f o r i in range ( 0 , 2 1 ) :
4 n = i ∗7
5 i f n%3==0 :
6 t . append ( s t r ( n )+" * " ) #we c o n c a t e n a t e : n becomes a s t r i n g , and we
attach a ∗
7 else :
8 t . append ( n )
9
10 f o r i in range ( 1 , 2 1 ) :
11 print ( i , "x 7 =" , t [ i ] )

▷ 6. Multiples of 13 and 7
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 s t r i n g = ""
4 f o r i in range ( 1 , 5 1 ) :
5 num = i ∗13
6
7 i f num%7 ==0:
8 s t r i n g = s t r i n g+" "+s t r (num)
9
10 print ( s t r i n g )

▷ 7. 10 first multiples of 13 and 7

Foundations in Business Information Management (INGE1135) 56 SOLUTIONS - 2024


- Exercises
Solutions

1 # −∗− c o d i n g : Utf −8 −∗−


2
3 s t r i n g = ""
4 num=0
5 count = 0
6 while count <10:
7 num = num+13
8
9 i f num%7 ==0:
10 s t r i n g = s t r i n g+" "+s t r (num)
11 count = count+1
12
13 print ( s t r i n g )

▷ 8. 1.
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 t 2 = [ ’Jan’ , ’Feb’ , ’Mar’ , ’Apr’ , ’May’ , ’Jun’ , ’Jul’ ,
4 ’Aug’ , ’Sep’ , ’Oct’ , ’Nov’ , ’Dec’ ]
5
6 print ( "First method :" )
7 t e x t=""
8 f o r i in range ( 0 , 1 2 ) :
9 t e x t=t e x t+t 2 [ i ]+" "
10
11 print ( t e x t )
12
13 print ( "Second method :" )
14 t e x t 2=""
15 f o r i in t 2 :
16 t e x t 2= t e x t 2+i+" "
17
18 print ( t e x t 2 )

2.
1 # −∗− c o d i n g : Utf −8 −∗−
2
3
4 t1 = [ 3 1 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31]
5 t 2 = [ ’Jan’ , ’Feb’ , ’Mar’ , ’Ap’ , ’May’ , ’Jun’ , ’Jul’ ,
6 ’Aug’ , ’Sept’ , ’Oct’ , ’Nov’ , ’Dec’ ]
7
8 t 3 ={}
9 f o r i in range ( len ( t 2 ) ) :
10 t3 [ t2 [ i ] ] = t1 [ i ]
11
12 print ( t 3 )

▷ 9.
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 a= [ 3 2 , 5 , 1 2 , 8 , 3 , 7 5 , 2 , 1 5 ]
4 a . sort ()
5
6 print ( "the greatest element in the list is :" , a [ − 1 ] )

▷ 10.
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 a= [ 3 2 , 5 , 1 2 , 8 , 3 , 7 5 , 2 , 1 5 ]
4 even = [ ]
5 odd = [ ]
6
7 f o r i in a :
8 i f i %2==0:
9 even . append ( i )
10 else :
11 odd . append ( i )
12
13 print ( even )
14 print ( odd )

Foundations in Business Information Management (INGE1135) 57 SOLUTIONS - 2024


- Exercises
Solutions

▷ 11.
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 name = [ ’Jean’ , ’Maximilien’ , ’Brigitte’ , ’Sonia’ , ’Jean-Pierre’ , ’Sandra’ ]
4 more6 = [ ]
5 fewer6 =[]
6
7 f o r i in name :
8 i f len ( i ) <6:
9 f e w e r 6 . append ( i )
10 else :
11 more6 . append ( i )
12
13 print ( f e w e r 6 )
14 print ( more6 )

Writing programs
▷ 1. Taxes
1 #−∗− c o d i n g : Utf −8 −∗−
2
3 b a s e = 500
4 rate = 47.5
5 r e v e n u e m i n = 2000
6 revenue max = 3000
7
8 print ( "This algorithm computes your personal income tax based on your revenue" )
9
10 #f l o a t ( . . . ) : t h e r e v e n u e i s p r o b a b l y a r e a l number
11
12 t a x a b l e i n c = f l o a t ( input ( "What is your income ? (between 2000 and 3000) " ) )
13
14 while ( ( t a x a b l e i n c > revenue max ) or ( t a x a b l e i n c < r e v e n u e m i n ) ) :
15 print ( "Invalid income" )
16 t a x a b l e i n c = f l o a t ( input ( "What is your income ? (between 2000 and 3000) " ) )
17
18 tax = base + ( r a t e /100) ∗ ( t a x a b l e i n c − revenue min )
19 print ( "Your personal income tax is :" , tax , "euros" )

Limit at 10 attempts :
1 b a s e = 500
2 rate = 47.5
3 r e v e n u e m i n = 2000
4 revenue max = 3000
5 i = 1
6
7 print ( "This algorithm computes your personal income tax based on your revenue" )
8
9 #f l o a t ( . . . ) : t h e r e v e n u e i s p r o b a b l y a r e a l number
10
11 t a x a b l e i n c = f l o a t ( input ( "What is your income ? (between 2000 and 3000) " ) )
12
13 while ( ( t a x a b l e i n c > revenue max ) or ( t a x a b l e i n c < r e v e n u e m i n ) and ( i <10) ) :
14 print ( "Invalid income" )
15 print ( "Only" ,10 − i , "attempts left" )
16 t a x a b l e i n c = f l o a t ( input ( "What is your income ? (between 2000 and 3000) " ) )
17 i += 1
18
19 i f i == 10 :
20 print ( "Too many attempts" )
21 else :
22 tax = base + ( r a t e /100) ∗ ( t a x a b l e i n c − revenue min )
23 print ( "Your personal income tax is :" , tax , "euros" )

▷ 2. Mean : no number of values asked.


1 #A l g o r i t h m e moyenne
2 #v a r i a b l e s :
3 #n , sum : i n t ;
4 #v a l u e , mean : f l o a t ;

Foundations in Business Information Management (INGE1135) 58 SOLUTIONS - 2024


- Exercises
Solutions

5
6 #i n i t i a l i z a t i o n s
7 n = 0
8 sum = 0
9
10 #r e a d i n g 1 s t v a l u e
11 v a l u e = f l o a t ( input ( "a number pls ! (-9999 to strop)" ) )
12
13 while ( v a l u e != −9999) :
14 #t r e a t i n g t h e v a l u e
15 sum = sum + v a l u e #a c c u m u l a t i n g v a l u e s
16 n = n + 1 #i n c r e m e n t i n g c o u n t e r
17 #r e a d i n g n e x t v a l u e
18 v a l u e = f l o a t ( input ( "a number pls ! (-9999 to stop)" ) )
19
20 #we a r e s u r e t h a t : v a l u e i s −9999
21 i f ( n !=0) :
22 mean = sum/n ;
23 print ( "The sum is : " ,sum, " and the mean is : " , mean )
24 else :
25 print ( "No value, no mean !" )

▷ 3. Here is one of many possible solutions :


1 #A l g o r i t h m e PlusieursSommes
2 #v a r i a b l e s : n , s , i : i n t ;
3 # reading a f i r s t int
4 n = i n t ( input ( "A sum ? If yes, input a positive number ; if no, input a negative number
") )
5 while ( n >= 0P ) :
n
6 #compute i=1 i
7 s = 0 # i n i t i a l i z i n g t h e sum
8 f o r i in range ( 0 , n+1) :
9 s = s+i
10 print ( "The sum of the " , n , " first integers is : " , s )
11 #r e a d i n g n e x t i n t
12 n = i n t ( input ( "A sum ? If yes, input a positive number ; if no, input a negative
number " ) )

▷ 4. Remarque : ici, le nombre de données est connu à priori (fourni par l’utilisateur).
1 #a l g o r i t h m Moyenne
2 #v a r i a b l e s : n , v , s , i : i n t
3 # i : loop counter , i n t
4 # m : float
5
6 n = i n t ( input ( " How many values to enter : " ) )
7
8 i f (n > 0) :
9 s = 0
10 f o r i in range ( 1 , n+1) :
11 v = i n t ( input ( "a value pls ! " ) )
12 s = s + v
13 m = s /n
14 print ( " The mean is :" , m)
15 else :
16 print ( "We can only take a positive number of values " )

Variant : write an algorithm that reads the number of values the user wants to input and that computes
the mean of the valid values, i.e. only the ones that are between 0 and 20. Ecrivez un algorithm qui lit
le nombre d’entiers que l’utilisateur souhaite introduire ainsi que leurs valeurs et qui calcule la moyenne
arithmétique des valeurs valides c-à-d comprises entre 0 et 20.
1 #Al gorith m Moyenne v a r i a n t e
2 #v a r i a b l e s : n , v , s , i , nValid : i n t
3 # i : l o o p co u n t e r , i n t
4 # m : float
5
6 nValid = 0
7 n = i n t ( input ( " How many values to enter : " ) )
8
9 if (n > 0) :
10 s = 0
11 f o r i in range ( 1 , n+1) :
12 v = i n t ( input ( "a value pls ! " ) )
13 i f ( v >= 0 ) and ( v <= 2 0 ) :

Foundations in Business Information Management (INGE1135) 59 SOLUTIONS - 2024


- Exercises
Solutions

14 s = s + v
15 n V a l i d += 1
16 i f nValid > 0 :
17 m = s / nValid
18 print ( " The mean is :" , m)
19 else :
20 print ( "No valid value " )
21 else :
22 print ( "We can only take a positive number of values " )

▷ 5. Deviation from mean


1 #A l g o r i t h m e Ecart Moyenne
2 #v a r i a b l e s : s t o c k : l i s t ;
3 # n, i : int ;
4 # sum , mean : f l o a t ;
5
6 n = i n t ( input ( "How many values do you want to input ?" ) )
7
8 s t o c k = [ 0 ] ∗ n #we have t o k e e p a l l v a l u e s . Why ?
9 sum = 0
10 # We compute t h e sum o f t h e u s e r i n p u t s
11 f o r i in range ( 0 , n ) :
12 s t o c k [ i ] = i n t ( input ( "An integer ?" ) )
13 sum = sum + s t o c k [ i ]
14 # Now we compute t h e mean
15 # s u p p o s i n g we have a t l e a s t one v a l u e
16 mean = sum / n
17 # Now we d i s p l a y t h e d e v i a t i o n from t h e mean
18 print ( "Deviation from the mean :" )
19 f o r i in range ( 0 , n ) :
20 print ( s t o c k [ i ]−mean , "," )

▷ 6. Classifying integers
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 print ( "This program counts and classifies the inputs by pos/neg and odd/even" )
4 x = i n t ( input ( "Enter an integer (pos or neg) (0 to stop)" ) )
5
6 even pos = 0
7 even neg = 0
8 odd pos = 0
9 odd neg = 0
10
11 while x != 0 :
12 i f x%2 == 0 : #p a i r s
13 i f x > 0 : #p a i r s p o s i t i f s
14 even pos = even pos + 1
15 e l s e : #p a i r s n e g a t i f s
16 even neg = even neg + 1
17 e l s e : #i m p a i r s
18 i f x > 0 : #i m p a i r s p o s i t i f s
19 odd pos = odd pos + 1
20 e l s e : #i m p a i r s n e g a t i f s
21 odd neg = odd neg + 1
22 x = i n t ( input ( "Enter an integer (pos or neg) (0 to stop)" ) )
23
24 print ( "Number of even positive integers given : " , even pos )
25 print ( "Number of even negative integers given : " , even neg )
26 print ( "Number of odd positive integers given: " , odd pos )
27 print ( "Number of odd negative integers given: " , odd neg )

▷ 7. Household mean expenses per children


1 #A l g o r i t h m e e c o l e
2 #v a r i a b l e s : number type : i n t [ ] ;
3 # expense : f l o a t [ ] ;
4 # type : int ;
5 # children : int ;
6 # value : f l o a t ;
7 # mean expense : f l o a t ;
8

Foundations in Business Information Management (INGE1135) 60 SOLUTIONS - 2024


- Exercises
Solutions

9 number type = [ 0 ] ∗ 11 # from 1 t o 10


10 e x p e n s e = [ 0 ] ∗ 11
11
12 c h i l d r e n = i n t ( input ( "Number of children ? " ) )
13 while ( c h i l d r e n != 0 ) :
14 v a l u e = f l o a t ( input ( "Expenses ? " ) )
15 expense [ c h i l d r e n ] = expense [ c h i l d r e n ] + value
16 number type [ c h i l d r e n ] = number type [ c h i l d r e n ] + 1
17 c h i l d r e n = i n t ( input ( "Number of children ? " ) )
18
19 # d i s p l a y and c a l c u l a t i o n s o f mean p e r c h i l d p e r h o u s e h o l d
20 print ( "Number of children per household Mean expenses per children" )
21 f o r type in range ( 1 , 1 1 ) :
22 print ( type , )
23 # computing mean
24 # o n l y happens i f a t l e a s t one o b s e r v a t i o n was i n p u t
25 i f ( number type [ type ] > 0 ) :
26 mean expense = e x p e n s e [ type ] / ( number type [ type ] ∗ type )
27 print ( "\t \t \t" , mean expense )
28 e l s e : # no o b s e r v a t i o n f o r t h i s t y p e
29 print ( "\t \t \t - " )

▷ 8. Bank account
1 #A l g o r i t h m e banque
2 #v a r i a b l e s :
3 #movement , s u m d e p o s i t , s u m w i t h d r a w a l , b a l a n c e : f l o a t
4 #n u m b e r d e p o s i t , n u m b e r w i t h d r a w a l : i n t ;
5
6 n u m b e r d e p o s i t = 0 #i n i t a l i z i n g number o f d e p o s i t
7 sum deposit = 0
8 number withdrawal = 0 #i n i t a l i z i n g number o f w i t h d r a w a l s
9 sum withdrawal = 0
10
11 #r e a d i n g i n i t i a l b a l a n c e
12 b a l a n c e = f l o a t ( input ( "Initial balance ? " ) )
13 #r e a d i n g f i r s t movement
14 movement = f l o a t ( input ( "Movement ? " ) )
15
16 while ( movement != 0 ) :
17 b a l a n c e = b a l a n c e + movement #u p d a t i n g b a l a n c e
18 i f ( movement > 0 ) : #t h e n i t ’ s a d e p o s i t
19 s u m d e p o s i t = s u m d e p o s i t + movement #u p d a t i n g sum o f d e p o s i t s
20 n u m b e r d e p o s i t = n u m b e r d e p o s i t + 1 #one more d e p o s i t
21 e l s e : #n e g a t i v e movement : w i t h d r a w a l
22 sum withdrawal = sum withdrawal + movement
23 number withdrawal = number withdrawal + 1
24 #r e a d i n g n e x t movement
25 movement = f l o a t ( input ( "movement ? " ) )
26
27
28 #d i s p l a y s
29 print ( "Final balance : " , b a l a n c e )
30 #computing means i f a p p l i c a b l e
31 i f ( number deposit > 0) :
32 print ( "Mean of deposits : " , s u m d e p o s i t / n u m b e r d e p o s i t )
33 else :
34 print ( "No deposit" )
35
36 i f ( number withdrawal > 0 ) :
37 print ( "Mean of withdrawals : " , −1 ∗ sum withdrawal / number withdrawal )
38 #we m u l t i p l y by −1 t o o b t a i n a p o s i t i v e number
39 else :
40 print ( "No withdrawal" )

Variant : the movements are stopped as soon as the balance is negative


We only have to modify the loop continuation condition :
16 while ( ( movement ̸= 0 ) and ( ( b a l a n c e ≥ 0 ) ) :

▷ 9. Fibonacci

Foundations in Business Information Management (INGE1135) 61 SOLUTIONS - 2024


- Exercises
Solutions

1 #a l g o r i t h m F i b o n a c c i
2 #v a r i a b l e s : n , a , b , t1 , t2 , l a s t , i : i n t
3
4 print ( "Enter two integers : " )
5 a = i n t ( input ( "First one : " ) )
6 b = i n t ( input ( "Second one : " ) )
7 n = i n t ( input ( "How many do you want ? " ) )
8 print ( "Here is the series :" )
9 t1 = a
10 print ( "term 1 : " , t 1 )
11 t2 = b
12 print ( "term 2 : " , t 2 )
13 f o r i in range ( 3 , n+1) :
14 d e r n i e r = t1 + t2
15 print ( "term " , i , " : " , l a s t )
16 t1 = t2
17 t2 = l a s t

▷ 11. Diving contest


1 #P l o n g e u r s
2 mini = 11 #t h e n e x t mark w i l l be l o w e r f o r s u r e
3 maxi = −1 #t h e n e x t mark w i l l be h i g h e r f o r s u r e
4 s = 0 #sum f o r t h e s c o r e
5 n b j u d g e s = 9 #number o f j u d g e s i n t h e c o n t e s t
6 f o r i in range ( 0 , n b j u d g e s ) :
7 print ( "What is the mark given by the" , i +1 ,"th judge ? " )
8 c = f l o a t ( input ( ) )
9
10 i f c > maxi :
11 maxi = c
12 i f c < mini :
13 mini = c
14
15 s = s + c
16
17 s = s − mini − maxi #we do n o t t a k e i n t o a c c o u n t t h e h i g h e s t and l o w e s t mark
18 print ( "The diver’s score is :" , s )

▷ 12. Book club purchase


1
2 n = i n t ( input ( "How many members in the club ? " ) )
3 member pur = [ ]
4 id member = [ ]
5 sum = 0
6 f o r i in range ( 0 , n ) :
7 code = i n t ( input ( "Id code ? " ) )
8 id member . append ( code )
9
10 total member = 0
11 x = f l o a t ( input ( "Purchase ? (-1 to stop) " ) )
12 while x != −1 :
13 total member = total member + x
14 x = f l o a t ( input ( "Purchase ? (-1 to stop) " ) )
15 member pur . append ( t o t a l m e m b e r )
16 sum = sum + t o t a l m e m b e r
17
18 mean = sum/n
19 print ( "Mean of annual purchases : " , mean )
20
21 print ( "The following members spent at least" , mean , "euros : " )
22 f o r i in range ( 0 , n ) :
23 i f ( member pur [ i ]>mean ) :
24 print ( id member [ i ] )

▷ 14. Temperature
1 #Temperature
2
3 i = 0 #i n i t i a l i z i n g c o u n t e r

Foundations in Business Information Management (INGE1135) 62 SOLUTIONS - 2024


- Exercises
Solutions

4 print ( "Temperature on day" , i +1 , "? (999 to stop) " )


5 temp = f l o a t ( input ( ) )
6 mini = temp #t h e f i r s t i n p u t i s b o t h t h e c o l d e s t and warmest t e m p e r a t u r e r e c o r d e d
7 maxi = temp
8 f r e e z = 0 #f r e e z i n g days c o u n t e r
9 sum = 0 #sum f o r mean t e m p e r a t u r e
10
11 while ( temp != 9 9 9 ) : #999 i s t h e end c o n d i t i o n o f t h e l o o p
12 sum = sum + temp #we add t h e t e m p e r a t u r e t o t h e sum o f a l l t e m p e r a t u r e
13 i = i + 1 #i n c r e m e n t a t i o n du compteur
14 i f temp < mini : #i f t h e g i v e n temp i s l o w e r than t h e p r e v i o u s l o w e s t one , t h e n i t
becomes t h e new l o w e s t temp
15 mini = temp
16 i f temp > maxi : #same w i t h h i g h e s t temp
17 maxi = temp
18 i f temp <= 0 : #f r e e z i n g day i f temp i s i n f e r i o r t o 0
19 freez = freez + 1
20
21 print ( "Temperature on day" , i +1 , "? (999 to stop) " )
22 temp = f l o a t ( input ( ) ) #new t e m p e r a t u r e
23 i f i > 0 : #i f t h e u s e r g a v e a t l e a s t temp
24 mean = sum / i
25 print ( "Mean temperature" , mean )
26 print ( "Max temperature :" , maxi )
27 print ( "Min temperature :" , mini )
28 print ( "Number of freezing days :" , f r e e z )
29 e l s e : #i f t h e u s e r d i r e c t l y g a v e 999
30 print ( "Pas de valeur" )

Advanced exercises on algorithmic complexity


▷ 3.7. Complexity O(n2 )
1 def SumOfTwoVal complexe ( a , b , v ) :
2 #s o l u t i o n O( n ˆ2)
3 f o r i in a :
4 f o r j in b :
5 i f i + j == v :
6 return True
7 return F a l s e
8
9
10 print ( SumOfTwoVal complexe ( [ 1 , 2 , 3 ] , [ 1 0 , 2 0 , 3 0 , 4 0 ] , 4 2 ) ) #t r u e
11 print ( SumOfTwoVal complexe ( [ 0 , 0 , − 5 , 3 0 2 1 2 ] , [ − 1 0 , 4 0 , − 3 , 9 ] , −8) ) #t r u e
12 print ( SumOfTwoVal complexe ( [ 1 , 2 , 3 ] , [ 4 , 5 , − 1 0 ] , −1) ) #f a l s e

Complexity 2 ∗ O(n)
1 def SumOfTwoVal ( a , b , v ) :
2 #s o l u t i o n 2∗O( n )
3 d i c t = {}
4 f o r i in a :
5 d i c t [ v−i ] = i
6 f o r i in b :
7 i f i in d i c t :
8 return True
9 return F a l s e
10
11
12 print ( SumOfTwoVal ( [ 1 , 2 , 3 ] , [ 1 0 , 2 0 , 3 0 , 4 0 ] , 4 2 ) ) #t r u e
13 print ( SumOfTwoVal ( [ 0 , 0 , − 5 , 3 0 2 1 2 ] , [ − 1 0 , 4 0 , − 3 , 9 ] , −8) ) #t r u e
14 print ( SumOfTwoVal ( [ 1 , 2 , 3 ] , [ 4 , 5 , − 1 0 ] , −1) ) #f a l s e

▷ 3.7. Complexity O(n2 )


1 def f i r s t r e c u r r i n g c h a r a c t e r c o m p l e x e ( c h a i n e ) :
2 #s o l u t i o n O( n ˆ2)
3 k = 1
4 f o r i in range ( 0 , len ( c h a i n e ) ) :
5 carac1 = chaine [ i ]

Foundations in Business Information Management (INGE1135) 63 SOLUTIONS - 2024


- Exercises
Solutions

6 f o r j in range ( k , len ( c h a i n e ) ) :
7 carac2 = chaine [ j ]
8 i f c a r a c 1 == c a r a c 2 :
9 return c a r a c 1
10 k += 1
11 return None
12
13 print ( f i r s t r e c u r r i n g c h a r a c t e r c o m p l e x e ( "ABCA" ) )
14 print ( f i r s t r e c u r r i n g c h a r a c t e r c o m p l e x e ( "BCABA" ) )
15 print ( f i r s t r e c u r r i n g c h a r a c t e r c o m p l e x e ( "ABC" ) )

Complexity O(n)
1 def f i r s t r e c u r r i n g c h a r a c t e r ( c h a i n e ) :
2 #s o l u t i o n O( n )
3 d i c t = {}
4 f o r i in c h a i n e :
5 i f i in d i c t :
6 return i
7 dict [ i ] = 1
8 return None
9
10 print ( f i r s t r e c u r r i n g c h a r a c t e r ( "ABCA" ) )
11 print ( f i r s t r e c u r r i n g c h a r a c t e r ( "BCABA" ) )
12 print ( f i r s t r e c u r r i n g c h a r a c t e r ( "ABC" ) )

▷ 3.7. Complexity O(n2 )


1 import random
2 def r a n d o m i n r a n g e s c o m p l e x e ( r a n g e s ) :
3 #s o l u t i o n O( n ˆ2)
4 list = []
5 f o r i in r a n g e s :
6 f o r j in range ( i [ 0 ] , i [ 1 ] + 1 ) :
7 l i s t . append ( j )
8 x = random . r a n d i n t ( 0 , len ( l i s t ) )
9 return l i s t [ x −1]
10
11 print ( r a n d o m i n r a n g e s c o m p l e x e ( [ [ 1 2 , 1 5 ] , [ 1 , 5 ] , [ 3 2 , 3 5 ] ] ) )
12 print ( r a n d o m i n r a n g e s c o m p l e x e ( [ [ 1 , 1 0 ] , [ 1 2 , 2 5 ] , [ 3 3 , 3 7 ] ] ) )

Complexity 2 ∗ O(n)
1 def r a n d o m i n r a n g e s ( r a n g e s ) :
2 #s o l u t i o n 2∗O( n )
3 total nums = 0
4 f o r i in r a n g e s :
5 t o t a l n u m s += i [ 1 ] − i [ 0 ] + 1
6 x = random . r a n d i n t ( 0 , t o t a l n u m s −1)
7 print ( "random number :" , x )
8 f o r i in r a n g e s :
9 i f i [ 1 ] − i [ 0 ] + 1 >= x :
10 return i [ 0 ] + x −1
11 x −= i [ 1 ] − i [ 0 ] + 1
12
13 print ( r a n d o m i n r a n g e s ( [ [ 1 2 , 1 5 ] , [ 1 , 5 ] , [ 3 2 , 3 5 ] ] ) )
14 print ( r a n d o m i n r a n g e s ( [ [ 1 , 1 0 ] , [ 1 2 , 2 5 ] , [ 3 3 , 3 7 ] ] ) )

S4 : Modules : procedures and functions


Reading algorithms
▷ 1. The error is insignificant
The error is significant
The error is significant

▷ 2. testFunctions

Foundations in Business Information Management (INGE1135) 64 SOLUTIONS - 2024


- Exercises
Solutions

1. amount = F ( 3 . 1 4 1 5 , r a t e , month ) # y e s

2. compute ( u , v , 2 , p , q , c o d e ) # y e s

3. r a t e = F( hour , day , 2 ) # y e s

4. print (F ( 0 , 0 , 0 ) ) # y e s

5. compute ( hour , abs ( −1) , 2 , day , y e a r , c l a s s ) ; # y e s

6. F( hour , r a t e , month ) # no
# a f u n c i t o n t h a t r e t u r n s a v a l u e can o n l y be used i n
# a p r i n t ( ) or an a s s i g n m e n t

7. compute ( ’6’ , hour , 3 . 1 4 1 5 , 1 3 , y e a r , c l a s s ) ; # no


# b e c a u s e ’ 6 ’ i s not f l o a t , ( and 3 . 1 4 1 5 i s not an i n t )

8. hur = 2 ∗ F ( 3 . 1 4 1 5 , amount ) / ( 2 . 7 1 ∗ r a t e ) ; # no
# t h e r e i s an argument m i s s i n g when c a l l i n g F( )

9. compute ( 3 . 1 4 1 5 ∗ hour , 3 . 1 4 1 5 , 2 , day , y e a r , c l a s s ) # y e s

10. amount = F ( 3 . 1 4 1 5 ∗ hour , 2 . 7 1 / r a t e , 2 ) ; # y e s

11. compute ( 3 . 1 4 1 5 , 1 . 5 ∗ hour , 2 , day , y e a r , c l a s s ) # Oui

12. if ( month == 2 ) :
y e a r = F( hour , F( r a t e , 3 . 1 4 1 5 , 2 ) , day )
# Yes , even i f t h e v a r i a b l e i s s u p p o s e d t o be an i n t
# i t can r e c e i v e F( ) ’ s r e s u l t
# which i s f l o a t

13. while ( u > 0 ) :


compute ( u , v , 2 , p , q , c o d e )
# No , b e c a u s e u c o r r e s p o n d s t o a l o c a l parametre .
# i t s v a l u e w i l l not be m o d i f i e d by compute ( )
# I f t h e b o o l e a n i s True f o r t h e f i r s t e x e c u t i o n o f t h e l o o p ,
# t h e program w i l l l o o p i n f i n i t e l y
# s i n c e u w i l l n e v e r r e c e i v e a new v a l u e .

Implementing functions
▷ 1. Using mean()
1 list a = [4 ,5 ,6 ,7]
2 list b = [2 ,3]
3
4 mean a = mean ( l i s t a )
5 mean b = mean ( l i s t b )
6 print ( "The mean of" , l i s t a , "is" , mean a )
7 print ( "The mean of" , l i s t b , "is" , mean b )

▷ 2. Using de collect() :
1 q = "Give a number to compute a mean : "
2 l i s t c = collect (q)
3 print ( "The" , len ( l i s t e c ) , "answers to the question ’" , q , "’ are" , l i s t c )

▷ 3. Complete solution :

Foundations in Business Information Management (INGE1135) 65 SOLUTIONS - 2024


- Exercises
Solutions

1 def mean ( n ) :
2 #PRE : n − a l i s t o f numbers
3 #POST : m − t h e mean o f number i n n
4 s = 0
5 f o r number in n :
6 s = s + nombre
7 m = s / len ( n )
8 return m
9
10 def c o l l e c t ( q u e s t i o n ) :
11 #PRE : q u e s t i o n − a q u e s t i o n o f t y p e s t r t h a t w i l l be p o s e d x times , u n t i l t h e
user inputs ’ stop ’
12 #POST : l − a l i s t w i t h answers t o t h e q u e s i t o n p o s e d x t i m e s
13 # t h e answers t y p e w i l l be f l o a t
14 l = []
15 print ( "Write ’stop’ to stop collecting data" )
16 reponse = input ( question )
17 while r e p o n s e != "stop" :
18 reponse = f l o a t ( reponse )
19 l . append ( r e p o n s e )
20 reponse = input ( question )
21 return l
22
23 q = "Give a number to compute a mean : "
24 l i s t c = collect (q)
25 mean c = mean ( l i s t c )
26 print ( "The mean of" , l i s t c , "is" , mean c )

▷ 4. collect str()
1
2 def c o l l e c t s t r ( q u e s t i o n ) :
3 #PRE : q u e s t i o n − a q u e s t i o n o f t y p e s t r t h a t w i l l be p o s e d x times , u n t i l t h e
user inputs ’ stop ’
4 #POST : l − a l i s t w i t h answers t o t h e q u e s i t o n p o s e d x t i m e s
5 # t h e answers t y p e w i l l be f l o a t
6 l = []
7 print ( "Write ’stop’ to stop collecting data" )
8 reponse = input ( question )
9 while r e p o n s e != "stop" :
10 #we s i m p l y d e l e t e d a l i n e here , i t c o u l d have been r e p l a c e d by :
11 #r e p o n s e = s t r ( r e p o n s e )
12 l . append ( r e p o n s e )
13 reponse = input ( question )
14 return l

Small exercises on modules


▷ 3. This script contains all functions, and a main. We also added data collection for a vector Rn .
1 # −∗− c o d i n g : Utf −8 −∗−
2
3 def sum elem ( v ) :
4 #PRE: v a t u p l e
5 #POST: t h e sum o f t h e e l e m e n t s i n v
6 s =0.0
7 f o r c in v :
8 s=s+c
9 return s
10
11 def s u m a l t e r n ( v ) :
12 #PRE: v a t u p l e
13 #POST: t h e sum : v1 − v2 + v3 − V4 + v5 . . .
14 s =0.0
15 f o r j in range ( 0 , len ( v ) ) : #from 0 t o n−1
16 i f j %2==0: #j i s a c t u a l l y i −1 !
17 s=s+v [ j ]
18 else :
19 s=s−v [ j ]
20 return s

Foundations in Business Information Management (INGE1135) 66 SOLUTIONS - 2024


- Exercises
Solutions

21
22 def sum sq ( v ) :
23 #PRE: v a t u p l e
24 #POST: sum o f ( v [ i ]− v [ i −1]) ∗( v [ i ]− v [ i −1])
25 s =0.0
26 n=len ( v )
27 f o r i in range ( 1 , n ) : #from 1 t o n−1 as i n t h e q u e s t i o n
28 s=s +(v [ i ]−v [ i −1]) ∗ ( v [ i ]−v [ i −1])
29 return s
30
31 def c r e a t e v e c t o r ( v ) :
32 #PRE: v an empty l i s t
33 #POST: a l i s t w i t h e l e m e n t s g i v e n by t h e u s e r
34 n=i n t ( input ( "dimensions of Rn ? " ) )
35 f o r i in range ( 0 , n ) :
36 c=f l o a t ( input ( "element "+ s t r ( i +1) + " ? " ) )
37 v . append ( c )
38
39 def main ( ) :
40
41 x=(1.0 ,2.0 ,0.0)
42 y=(3.0 ,0.0 ,0.0 ,5.0)
43 print ( x , "sum square = " , sum sq ( x ) )
44 print ( x , "sum elements = " , sum elem ( x ) )
45 print ( y , "sum squares = " , sum sq ( y ) )
46 print ( y , "sum elements = " , sum elem ( y ) )
47
48 z =[]
49 create vector (z)
50 z=tuple ( z )
51 print ( z , "alternate sum = " , s u m a l t e r n ( z ) )
52
53 w= [ ]
54 c r e a t e v e c t o r (w)
55 w=tuple (w)
56 print (w, "alternate sum = " , s u m a l t e r n (w) )
57
58 #c a l l i n g t h e main ( ) p r o c e d u r e !
59 main ( )

Writing methods
▷ 1. The final algorithm could be :
1 #a l g o r i t h m C a l c u l n p r e m i e r f a c t o
2
3 def f a c t o ( n ) :
4 #PRE : an i n t >= 0
5 #POST : an i n t : n f a c t o r i a l
6 #v a r i a b l e s : p: int ;
7 # i : i n t ; #l o o p c o u n t e r
8
9 p = 1
10 f o r i in range ( 1 , n+1) :
11 p = p∗ i
12 return ( p )
13
14 def main ( ) :
15 #v a r i a b l e s : i : i n t ; #l o o p c o u n t e r
16 # f a c t o r i a l , sum : i n t ;
17 # n : int ;
18
19 N = i n t ( input ( " How many factorials to sum ? " ) )
20 sum = 0
21 f o r i in range ( 1 , n+1) :
22 factorial = facto ( i )
23 sum = sum + f a c t o r i a l
24 print ( " The sum of the " , n , " first factorials is : " , sum)
25
26 main ( )

▷ 2. Complex sums

1 #a l g o r i t h m s o m m a t i o n s p u i s s a n c e s
2
3 def power ( h , q ) :

Foundations in Business Information Management (INGE1135) 67 SOLUTIONS - 2024


- Exercises
Solutions

4 # PRE : h and q , b o t h p o s i t i v e int


5 # POST : r e t u r n s hˆq , an i n t
6 #v a r i a b l e s : p : i n t ;
7 # i : int ;
8
9 p = 1
10 f o r i in range ( 1 , q+1) :
11 p = p ∗ h
12 return p
13
14 def main ( ) :
15 #main a l g o r i t h m
16 #v a r i a b l e s :
17 # i b , b i , b , n , sum : i n t ;
18
19 n = i n t ( i n p u t ( " Enter n, the number of elements in the sums iˆb and bˆi : " ) )
20 b = i n t ( i n p u t ( " Enter b, it will be the exponant in the first sum , and the base in the
second sum : " ) )
21
22 # sum o f i ˆ b
23 sum = 0
24 f o r i in range ( 1 , n+1) :
25 i b = power ( i , b ) #h e r e b i s t h e exponant
26 sum = sum + i b
27 print ( " The sum of iˆb is : " , sum)
28
29 # sum o f b ˆ i
30 sum = 0
31 f o r i in range ( 1 , n+1) :
32 b i = power ( b , i ) #h e r e b i s t h e b a s e
33 sum = sum + b i
34 print ( " The sum of bˆi is : " , sum)
35
36 main ( )

▷ 3. Powers
1 def power ( x , n ) :
2 # PRE : x i s a f l o a t and n an non−neg i n t
3 # POST : r e t u r n s x ˆn
4 #v a r i a b l e s : p : f l o a t ;
5 # i : int ;
6 p = 1.0
7 f o r i in range ( 1 , n+1) :
8 p = p ∗ x
9 return p

1 def power2 ( x , n ) :
2 # PRE : x i s a f l o a t and n i s any i n t
3 # POST : r e t u r n s x ˆn
4 # we use t h e power f u n c t i o n from above
5 i f ( n >= 0 ) :
6 return ( power ( x , n ) )
7 else : # n is negative
8 return ( 1 / power ( x,−n ) )

▷ 5. Here, we ask for the size of the list. This can also be done without asking for it.

1 #a l g o r i t h m r e m p l i r a f f i c h e r
2
3 def f i l l ( r , size ) :
4 # PRE : r i s an empty l i s t o f l e n g t h s i z e
5 # r w i l l be m o d i f i e d
6 # POST : r i s f i l l e d w i t h v a l u e s g i v e n by t h e u s e r
7 #v a r i a b l e s : i : int ;
8
9 f o r i in range ( 0 , s i z e ) :
10 r [ i ] = i n t ( input ( " list [" , i , " ]== ?" ) )
11
12 def d i s p l a y ( t , s i z e ) :
13 # PRE : t i s a l i s t o f l e n g t h s i z e
14 # t w i l l not be m o d i f i e d
15 # POST : components o f t a r e d i s p l a y e d on s c r e e n
16 #v a r i a b l e s : i : i n t ;
17
18 f o r i in range ( 0 , s i z e ) :
19 print ( " tab [" , i , " ]== " , t [ i ] )
20
21 def main ( ) :
22 #p r i n c i p a l
23 #v a r i a b l e s : h u b e r t : i n t [ ] ; n : i n t ;
24
25 n = i n t ( input ( " How many integers do you want to input ? ? " ) )

Foundations in Business Information Management (INGE1135) 68 SOLUTIONS - 2024


- Exercises
Solutions

26 h u b e r t = [ None ] ∗ n
27 f i l l ( hubert , n )
28 d i s p l a y ( hubert , n )
29
30 main ( )

▷ 6. Increasing :
1 Fonction i n c r e a s i n g ( t ) :
2 # PRE : t i s a l i s t
3 # t w i l l not be m o d i f i e d
4 # POST : r e t u r n s True i s a l l e l e m e n t s a r e i n i n c r e a s i n g order , F a l s e o t h e r w i s e
5 #v a r i a b l e s : i , p r e v : i n t ;
6 # incr : bool ;
7
8 i n c r = True
9 prev = t [ 0 ]
10 f o r i in t :
11 i f ( t [ i ] < p r e v ) : # not i n c r e a s i n g
12 incr = False
13 p r e v = t [ i ] # we c o n t i n u e t o compare
14 return i n c r

We could make this function more efficient. In this case, the whole list is analyzed even if the first component is
greater than the second one. How could we stop analyzing the list as soon as we find that incr = False without using
break ?

Writing programs
No solutions for this section

Foundations in Business Information Management (INGE1135) 69 SOLUTIONS - 2024


- Exercises

You might also like