FBMI Exercise Book
FBMI Exercise Book
FBMI Exercise Book
(INGE1135) - Exercises
(2024)
L. Jacquet, C. Rodriguez Ameal
Contents
Solutions 45
i
Session 0
.
.
.
#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
.
.
.
.
.
.
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 ( )
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 )
▷ 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
▷ 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)
▷ 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.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 !
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)
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 ? ")
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")
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)
▷ 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.
9
Session 2 2.2. REMINDER ON BOOLEANS
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
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.
2. Assign values True and False to respectively p and q. Test the following lines :
print(p or q)
print(p and 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)
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.
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.
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
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
▷ 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 !" )
▷ 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)
▷ 8. Write an algorithm that computes and displays a household’s income taxes, given the following
specifications :
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");
• 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.
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 !"]
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)
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)
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))
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"]
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.
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.
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)
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 ?
▷ 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 )
▷ 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 ! " )
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]
4. f o r i in range ( 0 , 1 0 ) :
i f ( i % 3 ) == 0 :
numbers [ i ] = 0
else :
numbers [ i ] = i % 3
▷ 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
▷ 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)
▷ 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 ( ) )
11 i f ( v a l > m) :
12 m = val
13 print ( "We obtain " , m)
▷ 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 :
▷ 9. Write a program that search for the greatest element in a given list. With this list :
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.
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
▷ 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.
• 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 :
▷ 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
▷ 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 :
▷ 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.
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 )
4. print (F ( 0 , 0 , 0 ) )
6. F( hour , r a t e , month )
8. hour = 2 ∗ F ( 3 . 1 4 1 5 , amount ) / ( 2 . 7 1 ∗ r a t e )
12. if ( month == 2 ) :
y e a r = F( hour , F( r a t e , 3 . 1 4 1 5 , 2 ) , day )
• 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
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
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
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 ( )
Understand what this function does, then implement it in order to obtain the following :
▷ 3. Combine the two functions used in the previous exercises to obtain this display on screen :
▷ 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.
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
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
▷ 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.
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.
2 7 7 11 12
is increasing while
2 8 7
is not.
2. Write a function that determines if a list of integers is decreasing.
Start by determining what are the different information that the user should give, and what infor-
mation should the computer display.
45
Solutions
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
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
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
▷ 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
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)
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.
Writing programs
▷ 1. Income tax
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
▷ 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" )
n
X
i
i=1
▷ 4. This algorithm computes and display the product of the first n integers :
n
Y
i
i=1
▷ 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 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.
At line 26, the program displays : "We obtained : 14 and also : 3.5
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.
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.
▷ 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" )
▷ 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
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 )
▷ 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 )
▷ 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" )
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 !" )
▷ 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 ) :
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 " )
▷ 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 )
▷ 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" )
▷ 9. Fibonacci
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
▷ 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
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
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" ) )
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 ] ] ) )
▷ 2. testFunctions
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
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
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( )
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
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 :
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
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 ) :
▷ 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 ? ? " ) )
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