0% found this document useful (0 votes)
8 views13 pages

Python Exercises and Solutions Guide

This document contains numerous Python programming exercises with detailed statements. The exercises cover various concepts such as variables, operators, control structures, functions, data structures, and their manipulation.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views13 pages

Python Exercises and Solutions Guide

This document contains numerous Python programming exercises with detailed statements. The exercises cover various concepts such as variables, operators, control structures, functions, data structures, and their manipulation.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PHYSICAL MEASURES 1è year 2010 - 2011

ScientificComputing version2.2

Python3
Corrected exercises
Statements

Statements of exercises
Remark
The following exercises are provided as examples and models.
They are either simple or less simple (rated◃ in the margin) may be difficult (noted◃◃).

The course scripts


Course noFirst steps in Python

Assign the variables and by the values 6.892 and 19.7.


Calculate and display the value of the speed.
Improve the display by imposing one digit after the decimal point.

2. Enter a name and age using the instruction Display them.


Re-enter the name, but with the instruction The poster.
Finally, use the 'best practice': redo the exercise by typing the entries.
carried out with the instruction

Course no2: "Control of the instruction flow"

1. Enter a float. If it is positive or zero, display its root; otherwise, display a message.
of error.

2. The lexicographic order is that of the dictionary.


Enter two words, compare them to find the 'smaller' one and display the result.
Redo the exercise using the ternary statement:

3. We want to secure a pressurized enclosure.


We set a threshold pressure and a threshold volume: , .
We request to enter the current pressure and volume of the chamber and to write a script.
which simulates the following behavior:
if the volume and pressure are above the thresholds: immediate stop;
If only the pressure is above the threshold pressure: request to increase the vo-
light of the enclosure;
If only the volume is above the threshold volume: ask to lower the volume.
from the enclosure;
– or declare that "everything is fine".
This behavior will be implemented by a multiple alternative.

BC v2.1 -1- 2008 - 2009


Statements

4. Initialize two integers: and .


Write a loop displaying and incrementing the value as long as it remains less than
to that of .
Write another loop decrementing the value of and displaying its value if it is
Impair. Loop while b is not zero.

5. Write a filtered input of an integer in the interval from 1 to 10, inclusive. Display
the seizure.

6. Display each character of a string using a loop .


Display each item in a list using a loop .

7. Display the integers from 0 to 15 excluding, in threes, using a loop


and the instruction .

8. Use the instruction to interrupt a loop display of integers


from 1 to 10 inclusive, when the loop variable is equal to 5.

9. Use the instruction to modify a loop display of all in-


tiers from 1 to 10 included, except when the loop variable is equal to 5.

10. Use an exception to calculate, in a loop ranging from -3 to 3 inclusive,


value of sin(x)/x.

11. The clause loops. In this exercise, perform the inputs with some
and the displays with some , both belonging to the module .
Initialize a list with 5 integers of your choice and then input an integer.
In a for loop, iterate through the list. If the entered integer belongs to the list, save it.
and interrupt the loop (since you found it). If the loop completed successfully,
use a clause to display a message announcing it.
Now enter another integer, this time positive.
Write a loop to determine if this integer is prime. If it is not,
the loop should display the first divisor found and stop. If it is prime,
to display it in a clause .

Course no3: "The functions"

1. Write a procedure with four parameters: , , and .


This procedure must display the table of , of à , of in .
Test the procedure by making a call in the main program.

2. Write a function which returns the cube of its argument.

2008 - 2009 -2- BC v2.1


Statements

Write a function who calculates the volume of a sphere of given radius


in argument and which uses the function .
Test the function through a call in the main program.

3. Write a function who returns f(x)= 2x3+ x− 5. ▹


Write a procedure with four parameters: , ,
and This procedure displays the values of , of à ,
all She must respect< amI notenough.
Test this procedure by calling it in the main program after entering the
two terminals in a and the number of steps in a (use the
module ).

4. Write a function which returns the volume and mass of an el-


ellipsoid thanks to a tuple. The parameters are the three semi-axes and the mass volume
We will assign default values to these four parameters.
4
We give= 3 πabc
Test this function with calls using different numbers of arguments.

5. Write a function with a "variable-length tuple" argument that calculates


the sum of the numbers contained in the tuple.
Test this function with calls using different tuples of integers or floats.

6. Write another function with three arguments, and which returns their sum.
In the main program, define a tuple of three numbers, then use the syn-
call tax for the function that decompresses the tuple. Display the result.

7. Write a function with an argument "length dictionary goes-


variable," and displays its argument.
In the main program, define a dictionary, then use the call syntax.
to the function that decompresses the dictionary. Display the result.

Course no4: "Python Data Structures"

define the list: , then perform the following actions:


Sort and display the list;
Add element 12 to the list and display the list;
– reverse and display the list;
– post the index of element 17;
Remove element 38 and display the list;
– post the sub-list of 2 eto 3eelement ;
Post the sublist from the beginning to 2eelement
– post the sublist of 3eelement at the end of the list;
– post the complete sub-list of the list;

BC v2.1 3 2008 - 2009


Statements

Display the last element using negative indexing.

Note that some list methods do not return anything.

2. Initialize like an empty list, and like a list of five null floats.
Display these lists.
Use the function to display:
the integers from 0 to 3;
the integers from 4 to 7;
the integers from 2 to 8 in steps of 2.

Define like a list of integers from 0 to 5 and test the membership of the elements
items 3 and 6 to .

3. Use a list comprehension to add 3 to each element of a list of...


tiers from 0 to 5.

4. Use a comprehension list to add 3 to each element of a list of...


tiers from 0 to 5, but only if the element is greater than or equal to 2.

◃ 5. Use a list comprehension to get the list


from the chains and .
Indication: use two loops nested.

6. Use a list comprehension to calculate the sum of a list of integers from 0


at 9.

7. Define two sets: X= {a,b,c,d} and Y= {s,b,d}, then display the results
following:
the initial sets;
the membership test of the element àX;
the membership test of the element àY;
the setsX− YetY− X;
the set X∪ Y(union) ;
the set X∩ Y(intersection).

◃◃ 8. Write a function having an argument (a string) and which


returns a dictionary that contains the frequency of all the words in the input string.

9. The dictionary type (or associative array) allows representing structured arrays.
Indeed, each key is associated with a value in a dictionary, and this value can
itself be a data structure (list, tuple or a dictionary...).

2008 - 2009 4 BC v2.1


Statements

Here is the following table representing physicochemical information about ele-


Simple elements (boiling point (Te ) and merge (Tf), number (Z) and mass
(M) atomic:

Te /Tf2970 1063
At
Z/A79 196.967
Te Tf2237 29.8
Go
Z/A31 69.72

Assign the data from this table to a dictionary in a way that allows
write for example:

10. Implement a LIFO stack with a list.


To do this, define three functions:
which returns a stack from a variable list of elements passed as parameters
meter
push an element to the "top" of the stack;
pop an element from the 'top' of the stack.

11. In the same way, implement a FIFO queue with a list. Try to add▹
a queue manipulation menu.

Advice: Only use procedures without arguments and a list as a global variable.

Course no5: Interlude: perfect numbers and lucky numbers

Definitions:
We call a prime number any natural number greater than 1 that has exactly
two divisors, itself and one;
A proper divisor of n is any divisor of n, excluding n itself.
A natural number is said to be perfect if it is equal to the sum of all its proper divisors;
– numbers such as: (a+ n+ n 2 is prime for all such that 06n < (a− 1), are
called lucky numbers.

Write a module ( defining four functions: , ,


, and a self-test:
• the function returns the sum of the proper divisors of its argument;
• the other three functions verify the property given by their definition and return a
boolean. More specifically, if for example the function verify that his argument
first, it returns , otherwise it returns .

BC v2.1 5 2008 - 2009


Statements

The test part must include four calls to the function allowing to test
, , and .

Then write the main program ( ) which includes :


– the initialization of two lists: and ;
– a loop iterating over the interval [2,1000] including necessary tests to fill
these lists;
Finally, the display of these lists in message boxes of the module .

Course numbero6: "Modules and files"

1. Write a module to calculate the roots of the real trinomial: ax2+ bx+ c.
The module defines a function with the three parameters of the trinomial, a, beta
c. The function must return a tuple whose first element is the number of roots
of the trinomial (0, 1 or 2), and the other elements are the possible roots.

Test your function with the following three sets of values: 1,−3, 2, 1−2.1 and 1.1,1.

2. Write a main program using the previous module.


The three parameters will be entered in a of the module and the results-
will be displayed in a .

Course no7: "Object-Oriented Programming"

Define a class possessing the following attributes:


data: two class attributes: and .
method: a method containing an instance attribute and the affi-
changes of and of.

In the main program, instantiate an object of the class and invoke the
method .

2. Define a class with a constructor providing the coordinates by


defect of a vector in the plane (for example: and ).

In the main program, instantiate a without parameter, a


with its two parameters, and display them.

3. Enrich the class previous by adding a display method


and a method for overloading the addition of two vectors in the plane.

In the main program, instantiate two show them and show their
sum.

2008 - 2009 6 BC v2.1


Statements

Course no8 : "Notions of COO and encapsulation"

1. Define a class with a constructor providing values and


) by default and an attribute , a display method and
a method returning the surface of an instance.

Define a class inheriting from and which overloads the instance attribute:
.
In the main program, instantiate a and one and display them.

2. Define a class with a constructor providing default coordinates


from a point in the plane (for example: and ).

Define a class where the constructor has four parameters: two


for the origin and two for the end. This constructor defines two attributes:
and, instances of the class In this way, you design a class
The class is composed of two instances of the class .
Add a display method.

Finally write a self-test that displays an instance of Segment initialized with the values
1, 2, 3 and 4.

3. Define a factory function returning a closure function . ▹


to an argument His code contains only the function yes
she also has an argument and whose code simply returns
the sum: .
In the main program, create two functions, for example
and then display and . the values given by

4. Writing a function that returns an instance of a class. ▹


Define a class containing a method who displays .
Define a class containing a method who displays .
Finally, define the factory function with a parameter this
defaulted to If the parameter is verified, the body of the function returns a
instance of the class otherwise it returns an instance of the class .

In the main program, create the instance you desire through the factory.
then verify its type by calling the method on it .

BC v2.1 -7- 2008 - 2009


Statements

Additional scripts
1. Write a program that, based on the input of a radius and a height, calculates the
volume of a right cone.

2. A while loop: enter a price excluding tax (enter 0 to finish) and display its total price including tax.

3. Another while loop: calculate the sum of a sequence of positive or zero numbers.
Count how many data points there were and how many were above 100.
A number less than or equal to 0 indicates the end of the sequence.

4. The user gives a positive integer and the program displays if it is divisible by
2 and otherwise.

5. The user provides a positive integer and the program announces how many times in a row
this integer is divisible by 2.

◃ The user provides an integer greater than 1 and the program displays, if there are any, all its
propressing divisors repeated as well as their number. If there are none, it indicates that it
is first. For example:

7. Write a program that estimates the value of the mathematical constant using
the formula:
n 1
e = ∑ i!
i =0

To do this, define the factorial function and, in your main program, input
the order shows the corresponding approximation of.

A lighthouse keeper goes to the bathroom five times a day but the restrooms are on the ground floor...
Write a procedure (thus without return) which receives two parameters
the number of steps of the lighthouse and the height of each step (in cm), and which displays:

We will not forget:


that a week has 7 days;
- that once at the bottom, the guard must go back up;
that the result is to be expressed in m.

2008 - 2009 -8- BC v2.1


Statements

A point-based hunting permit now replaces the traditional hunting permit.


Each hunter starts with a capital of 100 points. If he kills a chicken, he loses
1 point, 3 points for 1 dog, 5 points for a cow, and 10 points for a friend. The
The permit costs 200 euros.
Write a function who receives the number of victims from the hunter and who returns
the amount due.
Use this function in a main program that inputs the number of victims
and which displays the amount that the hunter has to pay.

10. I am tied to the tracks at the Arras station. Write a program that displays a table.
allowing me to know the time at which I will be shredded by the train that left from
the Gare du Nord at 9 am (there are 170 km between the Gare du Nord and Arras).
The table will predict the different possible times for all speeds of 100 km/h
at 300 km/h, in increments of 10 km/h, the results being rounded down to the nearest minute.
Write a procedure who receives the speed of the train and displays the time
of the drama;
Write the main program that displays the requested table.

11. A main program inputs a valid DNA strand and a DNA sequence will-▹
"Valid" means that they are not empty and are exclusively formed of a
arbitrary combination of , , or ).
Write a function which returns true if the input is valid, false otherwise.
Write a function who performs a valid entry and returns the entered value under
form of a string.
Write a function who receives two arguments, the string and the sequence and
which returns the proportion of sequence in the chain (i.e. its number of o-
currencies).
The main program calls the function for the chain and for the sequence
and display the result.
Sample display:

12. It is a matter of writing, on one hand, a main program, and on the other hand, a function to...
listed in the main program.
The user fills in a table of N= 100 integers with random integers using
saint a function a, b which returns an integer between a and b− A function
named receives this table and returns the index of the cell that contains
the minimum.
Write the function .
Write the program that swaps the first element of the array with the minimum.
this table.

13. A table has N= 100 floating variables, of which the first (n< 100)
are used.

BC v2.1 9 2008 - 2009


Statements

Write a function which returns the index of the largest floating point among
cesn, and another which returns the index of the smallest.
Then write a main program that performs the following actions:
– filtered input (you must ensure that it cannot be entered outside of its
limits);
– random filling of the first values of the table (we will use the module ,
without arguments, which returns a float randomly between 0.0 and+1.0) ;
display of the amplitude of the table (difference between its largest and smallest)
their) ;
Display of the average of the first values of the table.

14. Write a function which receives two parameters, a temperature and an integer
, and which returns the Celsius conversion→ Fahrenheit (= 1), or Fahrenheit→ Celsius
( = 2).
Reminder: TF= 32+ 1.8× TC

15. Function returning multiple values as a tuple.


Write a function which receives a list of integers and returns the minimum,
the maximum and the average of this list. The main program will call this function
action with the list: .

16. Enter an integer between 1 and 3999 (why this limitation?). Display it in Roman numerals.
main.

◃ 17. Improve the previous script by using the function .

◃ 18. A table contains integers (2< n< 100), all between 0 and 500. Verify that they
are all different.

[Link] user enters an integer between 2 and 12, the program gives the number of ways
of fairening launching two dice.

20. Same problem as the previous one but with between 3 and 18 and three dice.

◃◃ 21. Generalization of the two previous questions. The user enters two inputs, of a
first the number of dice, nbd (which we will practically limit to 10), and on the other hand the
sum, s, included between [Link]. The program calculates and displays the number
ways to do with the ideas.

◃◃ 22. Same problem as the previous one but coded recursively.

2008 - 2009 -10- BC v2.1


Statements

23. To perform calculations on square matrices, we can use the "list of lists" type.
and index an element of the 3è line and 4è column parm[2][3] (considering that the
indices start at 0).
We declare three square matrices of dimension N: m1, m2, and m3 containing integers.
We affect them, line by line, by the N2the first even integers starting from 2; m2 is
the identity matrix, that is to say it contains 1s on the main diagonal (NW-SE)
and 0 everywhere else.
Practically, we will limit ourselves to Nmax.= 10. Write the algorithm for the calculation of:

m3= m1− m2

BC v2.1 -11- 2008 - 2009

You might also like