├── .github
└── ISSUE_TEMPLATE
│ └── error-in-correction-subject.md
├── .gitignore
├── correction_00.png
├── correction_01.md
├── correction_02.md
├── correction_03.md
└── correction_04.md
/.github/ISSUE_TEMPLATE/error-in-correction-subject.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Error in correction subject
3 | about: To point out an error in the correction file
4 | title: ''
5 | labels: ''
6 | assignees: JBarmentlo
7 |
8 | ---
9 |
10 | Day : xx
11 | Ex : xx
12 |
13 | A description of the issue.
14 |
15 | A copy paste of the faulty line if possible.
16 |
17 | Thank you for contributing to making our bootcamp better !
18 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/correction_00.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/42-AI/Python-Bootcamp-Corrections/e6f53625226a73302c2dc00d52b2b6a9f83978c7/correction_00.png
--------------------------------------------------------------------------------
/correction_01.md:
--------------------------------------------------------------------------------
1 | # Module 01 - Basics 2
2 |
3 | ## Comment:
4 | This second module is the evolution of two original projects created by the
5 | Paris-based student association 42 AI.
6 | They are named Bootcamp Python and Bootcamp Machine Learning.
7 | active members of 42 AI re-designed both of them for the school curriculum.
8 |
9 | Bootcamps has been developped between August 2019 and March/April 2020.
10 | Active 42AI members organized severals sessions of 2 weeks to 42Paris students
11 | to offer them the possibility to get famliar with Python and basics concepts
12 | of machine learning.
13 |
14 | The success of those sections brings the pedagogy to accept the idea to integrate
15 | the 2 bootcamps to the curriculum (initial discussion (01-05/2019) with 42 Paris
16 | pedago team highlighted a categorical opposition/refusal to this idea)
17 |
18 | The transcription had been realized over the direction of Matthieu David.
19 | Several 42AI members contributed to the redaction on the correction scales.
20 | For futur corrections on the scale, please contact the 42AI association via
21 | contact@42ai.fr or the current 42AI pedagogical supervisor.
22 |
23 | ## Introduction
24 | The Bootcamp Python and Bootcamp Machine Learning were originally created by
25 | [42AI](https://github.com/42-AI) active members and were adapted to 'piscine'
26 | format for the school 42 curriculum.
27 | For any issue or suggestion: [42Paris](https://github.com/42-AI/bootcamp_python/issues) and
28 | [42AI](https://github.com/42-AI/bootcamp_machine-learning/issues).
29 |
30 | As usual, you have to observe the following courtesy rules:
31 |
32 | - Remain polite, courteous, respectful, and constructive throughout the
33 | evaluation process. The well-being of the community depends on it.
34 |
35 | - Identify with the evaluated person or group the eventual dysfunctions of
36 | the assignment. Take the time to discuss and debate the problems you may
37 | have identified.
38 |
39 | - You must consider that there might be some differences in the
40 | understanding of and approach to project instructions, and the scope of
41 | its functionalities, between you and your peers. Always remain open-minded
42 | and grade them as fairly as possible. The pedagogy is valid only and only
43 | if peer-evaluation is conducted seriously.
44 |
45 | The goal of this module is to get started with the Python language.
46 | You will study objects, classes, inheritance, built-in functions, magic methods,
47 | generator ...
48 |
49 | ## Disclaimer
50 | The serie of modules started to be produce at the time of the release of
51 | Python 3.7. Students are free to use later version of Python as long as they
52 | verified the producted code complies with all the aspects precised in the
53 | subjects.
54 | As a consequence we recommend to students to perform the modules with the
55 | the Python version 3.7 (but this is just an advice).
56 | Version can be checked with the command ```python -V```.
57 |
58 | ## guidelines
59 | General rules
60 | - Only grade the work that is in the student or group's GiT repository.
61 |
62 | - Double-check that the GiT repository does belong to the student.
63 | Ensure that the work is the one expected for the corrected exercise
64 | and don't forget to verify that the command "git clone" is run in an empty
65 | folder.
66 |
67 | - Check carefully that no malicious aliases were used to make
68 | you evaluate files that are not from the official repository.
69 |
70 | - To avoid any surprises, carefully check that both the evaluating
71 | and the evaluated students have reviewed the possible scripts used
72 | to facilitate the grading.
73 |
74 | - If the evaluating student has not completed that particular
75 | project yet, it is mandatory for them to read the
76 | entire subject prior to starting the defense.
77 |
78 | - Use the flags available on this scale to signal an empty repository,
79 | non-functioning program, a Norm error (specified next in general rules),
80 | cheating, and so forth.
81 | In these cases, the grading is over and the final grade is 0,
82 | or -42 in case of cheating. However, except the exception of cheating, you
83 | are encouraged to continue to discuss your work even if the later is in
84 | progress in order to identify any issues that may have caused the project
85 | failure and avoid repeating the same mistake in the future.
86 |
87 | - Use the appropriate flag.
88 |
89 | - Remember that for the duration of the defense, no other unexpected,
90 | premature, or uncontrolled termination of the program, else the final
91 | grade is 0.
92 |
93 | - You should never have to edit any file except the configuration file if
94 | the latter exists. If you want to edit a file, take the time to explain why
95 | with the evaluated student and make sure both of you agree on this.
96 |
97 | - The Norm: You will follow the PEP 8 standards.
98 |
99 | - The function eval is never allowed.
100 |
101 | - Your exercises are going to be evaluated by other students,
102 | make sure that your variable names and function names are appropriate and civil.
103 |
104 | - THE ERROR HANDLING WILL NOT BE PERFECT, IF THE CODE SHOWS THE USER IS AWARE OF THE POSSIBILITY AND HANDLED IT BY RAISING AN ERROR, PRINTING A MESSAGE AND EXITING OR RETURNING NONE IT IS CONSIDERED VALID. IF AN ABSURD VALUE IS RETURNED IT IS NOT VALID
105 |
106 | # Exercise 0: 'Exercise 00 - The Book'
107 | ## Description:
108 | The goal of the exercise is to get you familiar with the notions of
109 | classes and the manipulation of the objects related to those classes.
110 |
111 | ## Questions:
112 | - **'Error management and basic tests'**\
113 | There are 2 classes, Book in book.py and Recipe in recipe.py.
114 | A Book object stores and manages Recipe.
115 | With the help of the test.py file, carry out at least the following tests
116 | to try to stress the error management:
117 |
118 | In the terminal:
119 | ```bash
120 | python3
121 | ```
122 | ```python
123 | from book import Book
124 | from recipe import Recipe
125 | ```
126 | - ## Recipe:
127 | ```python
128 | Recipe("cooki", 0, 10, ["dough", "sugar", "love"], "deliciousness incarnate", "dessert")
129 | ```
130 | Should print an error because cooking_lvl < 1
131 |
132 | ```python
133 | Recipe("cooki", 1.5, 10, ["dough", "sugar", "love"], "deliciousness incarnate", "dessert")
134 | ```
135 | Should print an error because cooking_lvl is not an int
136 | OR
137 | cooking lvl should be converted to an int somewhere
138 |
139 | ```python
140 | Recipe("cooki", 1, 10, [], "deliciousness incarnate", "dessert")
141 | ```
142 | Should print an error because empty ingredients
143 |
144 | ```python
145 | Recipe("cooki", 1, 10, ["dough", "sugar", "love"], "deliciousness incarnate", "dessert")
146 | print("Congratulations you finally made sime delicous cookies")
147 | ```
148 |
149 | - ## Book:
150 | - After the initialization of a correct Book object, verify:
151 | ```python
152 | b = Book("My seductive recipes")
153 | print(b.creation_date)
154 | # should be the current date and time
155 | print(b.last_update)
156 | # should be the same as the creation date or None
157 | ```
158 | - **get_recipe_by_name()** tests:
159 | ```python
160 | crumble = Recipe("Crumble" , 1, 25, ["apples", "flour", "sugar"], "delicious", "dessert")
161 | b.add_recipe(crumble)
162 | print(b.last_update)
163 | ```
164 | Should be a different date / time than the one printed before
165 | ```python
166 | b.get_recipe_by_name("Crumble")
167 | # should print the recipe
168 | # AND
169 | #
170 |
171 | b.get_recipe_by_name("Liver Icecream")
172 | # The recipe does not exist
173 | # The error must be handled in a justifiable manner
174 | # such as returning None, [], or printing an error message
175 | ```
176 | - **get_recipes_by_types()** tests:
177 |
178 | ```python
179 | print(b.get_recipes_by_types("dessert")[0])
180 | # Should print the Crumble recipe
181 | b.get_recipes_by_types("asdasd")
182 | # The recipe type does not exist, error must be handled in a justifiable manner
183 | # such as returning None, [], or printing an error message
184 | ```
185 | - With an correct type (with at least a recipe), the function must
186 | print all the recipes which match the type.
187 | - With a correct type which exists but being empty. This case must be handled properly
188 | - Verify also 'last_update' did not change
189 | - With a non existing recipe type, the function must declare an
190 | error and handle it correctly. Returning an empty array is also acceptable.
191 |
192 |
193 | # Exercise 1: 'Exercise 01 - Family Tree'
194 | ## Description:
195 | The goal of the exercise is to tackle the notion inheritance of class.
196 |
197 | ## Questions:
198 | - **Notion of class**\
199 | The exercise shows an example of inheritance of a class from a parent class.
200 | - Verify the implementation of the differents classes (GotCharacter and
201 | the children), parent should contains the attributes 'first_name' and
202 | 'is_alive' while the children classes must have 'family_name',
203 | 'house_words' and the 2 methods 'print_house_words' and 'die'
204 | - Verify when creating an instance of the GotCharacter class without any
205 | value that you get an object with the attributes 'first_name' sets to None
206 | and 'is_alive' sets to True.
207 | - Perform the same test and specify a value for the first_name and and
208 | is_alive, for example:
209 | `luigi = GotCharacter("Name", True)`
210 | Verify that the GotCharacter instance is alive and it's name.
211 | - Check the presence of the docstring `print(luigi.\_\_doc\_\_)` (Some python setting can make this return None, if thats the case, go check in the code for an explanative text below `def GotCharacter():`)
212 |
213 | - Verify that the GotCharacter instance has no attributes 'house_words'
214 | or 'family_name' (of course you should not be able to call print_house_words()
215 | or the die() neither)
216 |
217 | - **children class**
218 | - Creates an instance of the children class and checks:
219 | `arya = Stark("Arya")`
220 | - Check the presence of the docstring
221 | `print(arya.\_\_doc\_\_)`
222 | - Verify all the attributes of the character
223 | - Verify that the methods associated to the character object
224 | - Use the method die() and verify the value of is_alive
225 | - Create a new instance with a different name, and verify it is alive
226 | and it name
227 |
228 |
229 |
230 | # Exercise 2: 'Exercise 02 - The Vector'
231 | ## Description:
232 | The goal of the exercise is to get you used with built-in methods,
233 | more particularly with those allowing to perform operations.
234 | Student is expected to code built-in methods for vector-vector and
235 | vector-scalar operations as rigorously as possible.
236 | Concerning the \_\_str\_\_ and \_\_repr\_\_ you have the opportunity to observe
237 | their behaviors through the tests.
238 |
239 | ## Questions:
240 | - **Implementation of built-in methods**\
241 | First, verifiy all the expected built-in methods are implemented, and
242 | then printing a vector you observe an output similar to:\
243 | ```(Vector [n1, ..., n2])```\
244 | You can note that clever implementation may used \_\_add\_\_ method within
245 | _radd_, \_\_sub\_\_ and \_\_rsub\_\_. Nethertheless it is perfectly fine if it is
246 | not the case.
247 |
248 | - **built-in method \_\_init\_\_**
249 | Verify the correct implementation of the \_\_init\_\_ method:
250 | Create multiple instances of Vector class according to the different
251 | possibilities and verify if the values and shape are correct:
252 | - ```python
253 | print(Vector([1. , 2e-3, 3.14, 5.]).values)
254 | ```
255 | Output: `[1.0, 2e-3, 3.14, 5.0]`
256 |
257 | - ```python
258 | print(Vector(4).values)
259 | ```
260 | Output: `[[0.0], [1.0], [2.0], [3.0]]`
261 |
262 | - ```python
263 | Vector(-1)
264 | ```
265 | This is an error and should be properly handled by displaying an error message.
266 |
267 | - ```python
268 | print(Vector((10, 12)).values)
269 | ```
270 | Output: `[[10.0], [11.0]]`
271 |
272 | - ```python
273 | print(Vector((3, 1)).values)
274 | ```
275 | Should display a properly handled error or [[3.0], [2.0]]
276 |
277 | - ``` python
278 | v = Vector((1, 1))
279 | print(v.values)
280 | ```
281 | three behviours are acceptable:
282 | raise an error or print `[]` or print `[[]]`
283 |
284 | - ```python
285 | Vector((4, 7.1)):
286 | ```
287 | This is an error and should be properly handled by displaying an
288 | error message.
289 |
290 |
291 | - **built-in methods \_\_mul\_\_ and \_\_rmul\_\_**
292 | Verify the correct implementation of the built-in method \_\_mul\_\_ and
293 | \_\_rmul\_\_ by performing several tests related to '*' operator:
294 | ```python
295 | v = Vector(4)
296 | print(v.values)
297 | ```
298 | Should output: `[[0.0], [1.0], [2.0], [3.0]]`
299 |
300 | ```python
301 | print(v * 4)
302 | ```
303 | Should output: `[[0.0], [4.0], [8.0], [12.0]]`
304 |
305 | ```python
306 | print(4.0 * v)
307 | ```
308 | Should output: `[[0.0], [4.0], [8.0], [12.0]]`
309 |
310 | ```python
311 | v * "hi"
312 | ```
313 |
314 | The error should be handled, it should say raise SomeError in the code or print a message or return None or exit().
315 |
316 |
317 |
318 | - **built-in method \_\_add\_\_, \_\_radd\_\_, \_\_sub\_\_ and \_\_rsub\_\_**\
319 | Verify the correct implementation of the built-in method \_\_add\_\_,
320 | \_\_radd\_\_, \_\_sub\_\_ and \_\_rsub\_\_ by performing several tests related
321 | to '+' and '-' operators:
322 | ```python
323 | v = Vector(4)
324 | v2 = Vector([[1.0], [1.0], [1.0], [1.0]])
325 | print((v + v2).values)
326 | ```
327 | Should output: `[[1.0], [2.0], [3.0], [4.0]]`
328 | ```python
329 | v + Vector([0.0, 0.0, 0.0, 0.0])
330 | ```
331 | The error should be handled in some way
332 |
333 | ```python
334 | v + "hello"
335 | ```
336 | The error should be handled in some way
337 |
338 | ```python
339 | v + None
340 | ```
341 | The error should be handled in some way
342 |
343 | ```pyton
344 | print((v - v2).values != (v2 - v).values)
345 | ```
346 | Should output: `True`
347 |
348 |
349 | - **built-in method \_\_div\_\_ and \_\_rdiv\_\_**\
350 | For division perform the following tests:
351 | - 'Vector(4) / 2'
352 | - 'Vector(4) / 3.14'
353 | - 'Vector(4) / 0'
354 | An error should be displayed, and properly handled.
355 | - 'Vector(4) / None' and 'None / Vector(4)'
356 | An error should be displayed, and properly handled
357 | - 3 / Vector(3) shoud raise an error or the choice of behaviour must be justifiable
358 | as multiple mathematical definitions of division by a vector exist.
359 |
360 |
361 | # Exercise 3: 'Exercise 03 - Generator!'
362 | ## Description:
363 | The goal of the exercise is to discover the concept of generator object
364 | in Python, throught the implementation of a function 'generator' which
365 | performs a splitting operation and an ordering class operation.
366 |
367 | ## Questions:
368 | - **Error managament and basic tests**
369 | - First, check the implementation of the function (all behaviors are
370 | implemented: 'shuffle', 'ordered' and 'unique').
371 | - Verify the following cases are correctly managed and the message "ERROR"
372 | is printed:
373 | - Parameter 'text' is None
374 | - Parameter 'text' has a type different than 'str'
375 | - Parameter 'option' has a type different than 'str'
376 | - Parameter 'option' is specified and is a string different than 'unique',
377 | 'ordered' and 'shuffle'
378 |
379 | - Secondly, with 'text' parameter being a string with multiple words and
380 | punctuation (for example text="This is a simple string for a basic test. Very simple."),
381 | runs the tests:
382 | ```
383 | for elem in my_generator:
384 | print(elem)
385 | ```
386 | With my_generator being:
387 | - `generator(txt, sep=' ')`
388 | - `generator(txt, sep='.')`
389 | - `generator(txt, sep='i')`
390 | - `generator(txt, sep='si')`
391 | For the given example the tests give (with line break between each strings):
392 | - First test: 'This' 'is' 'a' 'simple' 'string' 'for' 'a' 'basic' 'test.' 'Very' 'simple.'
393 | - Second test: 'This is a simple string for a basic test' ' Very simple' ''
394 | - Third test: 'Th' 's ' 's a s' 'mple str' 'ng for a bas' 'c test. Very s' 'mple.'
395 | - Fourth test: 'This is a ' 'mple strung for a ba' 'c test. Very ' 'mple.'
396 |
397 | - Finally, with 'text' parameter being a non empty string you must test
398 | 'option' parameter. Check the value 'ordered' gives a alphanumerical
399 | ordering, 'unique' gives a set of the words (no identical strings) and
400 | 'shuffle' randomly arrange the words. Spend a particular attention on
401 | the last value, 2 runs with 'shuffle' should not give the same
402 | arrangement (th opposite is highly unlikely). Verify also there is no missing words.
403 |
404 |
405 | # Exercise 4: 'Exercise 04 - Working with lists'
406 | ## Description:
407 | The goal of the exercise is to discover 2 useful methods for lists,
408 | tuples, dictionnaries (iterable class objects more generally) named
409 | zip and enumerate.
410 |
411 | ## Questions:
412 | - **Error managament and basic tests**
413 |
414 | - First, check that the implementation of the class and methods.
415 | You must find 'zip' in the method 'zip_evaluate' and 'enumerate'
416 | in 'enumerate_evaluate' and no while loop. It is a normal implementation
417 | to find 'enumerate(zip(coefs, words))' so do not be surpised.
418 | - Verify the following cases are correctly managed and -1 is returned:
419 | - `Evaluator.enumerate_evaluate(None, None)`
420 | - `Evaluator.enumerate_evaluate([1, 2, 3], [])`
421 | - `Evaluator.enumerate_evaluate([1, 2, 3], ["word", 2, "wordo"])`
422 |
423 | - Then, test a few cases with lists length 1 and 2 to check the
424 | validity of the implementation and check no term of lists are missing
425 | in the sum of products (especially the last one).
426 |
427 | # Exercise 5: 'Exercise 05 - Bank account'
428 | ## Description:
429 | The goals of this exercise is to teach you new built-in functions and
430 | get a deeper understanding about class manipulation and to be aware
431 | of possibility to modify instanced objects.
432 | In this exercise you learn how to modify or add attributes to an object.
433 |
434 | ## Questions:
435 | - **Basic tests**
436 | - First, you have to check the classes implementation, meaning that you
437 | have to check the presence of:
438 | - the class Account and Bank in the file bank.py
439 | - the methods' \_\_init\_\_', 'transfer' and the attribute 'ID_COUNT' in
440 | the class Account.
441 | - the methods '\_\_init\_\_', 'add', 'transfer' and 'fix_account' in the
442 | class Bank.
443 | Student may have implement extra methods to manage the security
444 | aspect, thus it is okay to have more than the methods mentionned.
445 |
446 |
447 |
448 | - **For the following accounts ask the defendee to run his corruption detection function** :
449 | ```bash
450 | python3 -i the_bank.py
451 | ```
452 |
453 | - The following account is corrupted because it has an attribute that starts with b:
454 | ```python
455 | from the_bank import Account, Bank
456 |
457 | bank = Bank()
458 | john = Account(
459 | 'William John',
460 | zip='100-064',
461 | brother="heyhey",
462 | value=6460.0,
463 | ref='58ba2b9954cd278eda8a84147ca73c87',
464 | info=None,
465 | other='This is the vice president of the corporation',
466 | lol = "hihi"
467 | )
468 | ```
469 | ```python
470 | bank.fix_account(john)
471 | # OR
472 | bank.fix_account('William John')
473 | ```
474 | This should fix john **OR** return a fixed copy of john
475 |
476 |
477 | - The following account is corrupted because it has an even number of attributes:
478 | ```python
479 | john = Account(
480 | 'William John',
481 | zip='100-064',
482 | rother="heyhey",
483 | value=6460.0,
484 | ref='58ba2b9954cd278eda8a84147ca73c87',
485 | info=None,
486 | other='This is the vice president of the corporation',
487 | )
488 | ```
489 |
490 | - The following account is corrupted because it has no attribute "value":
491 | ```python
492 | john = Account(
493 | 'William John',
494 | zip='100-064',
495 | rother="heyhey",
496 | ref='58ba2b9954cd278eda8a84147ca73c87',
497 | info=None,
498 | other='This is the vice president of the corporation',
499 | lol = "lolilol"
500 | )
501 | ```
502 |
503 | - **We will now test a bank transfer**
504 | ```python
505 | bank.add(Account(
506 | 'Jane',
507 | zip='911-745',
508 | value=1000.0,
509 | ref='1044618427ff2782f0bbece0abd05f31'
510 | ))
511 |
512 | jhon = Account(
513 | 'Jhon',
514 | zip='911-745',
515 | value=1000.0,
516 | ref='1044618427ff2782f0bbece0abd05f31'
517 | )
518 |
519 | bank.add(jhon)
520 |
521 | print("testing a valid transfer")
522 | print(jhon.value)
523 | bank.transfer("Jane", "Jhon", 500)
524 | print(jhon.value)
525 | ```
526 | Should output `1000.0` then `True` then `1500.0`. The transfer worked .
527 |
528 | ```python
529 | bank.transfer("Jane", "Jhon", 1000)
530 | print(jhon.value)
531 | ```
532 | Should output `False` then `1500.0` OR Raise an Error.
533 | Jhon's balance **MUST** not change.
534 |
--------------------------------------------------------------------------------
/correction_02.md:
--------------------------------------------------------------------------------
1 | # Module 02 - Basics 3
2 |
3 | ## Comment:
4 | This third module is the evolution of two original projects created by the
5 | Paris-based student organization 42 AI.
6 | They are named Bootcamp Python and Bootcamp Machine Learning.
7 | active members of 42 AI re-designed both of them for the school curriculum.
8 |
9 | Bootcamps has been developped between August 2019 and March/April 2020.
10 | Active 42AI members organized severals sessions of 2 weeks to 42Paris students
11 | to offer them the possibility to get famliar with Python and basics concepts
12 | of machine learning.
13 |
14 | The success of those sections brings the pedagogy to accept the idea to integrate
15 | the 2 bootcamps to the curriculum (initial discussion (01-05/2019) with 42 Paris
16 | pedago team highlighted a categorical opidea)
17 |
18 | The transcription had been realized over the direction of Matthieu David
19 | several 42AI members contributed to the redaction on the correction scales.
20 | For futur corrections on the scale, please contact the 42AI association via
21 | contact@42ai.fr or the current 42AI pedagogical supervisor.
22 |
23 | ## Introduction:
24 | The Bootcamp Python and Bootcamp Machine Learning were originally created by
25 | [42AI](https://github.com/42-AI) active members and were adapted to 'piscine'
26 | format for the school 42 curriculum.
27 | For any issue or suggestion: [42Paris](https://github.com/42-AI/bootcamp_python/issues) and
28 | [42AI](https://github.com/42-AI/bootcamp_machine-learning/issues).
29 |
30 | As usual, you have to observe the following courtesy rules:
31 |
32 | - Remain polite, courteous, respectful, and constructive throughout the
33 | evaluation process. The well-being of the community depends on it.
34 |
35 | - Identify with the evaluated person or group the eventual dysfunctions of
36 | the assignment. Take the time to discuss and debate the problems you may
37 | have identified.
38 |
39 | - You must consider that there might be some differences in the
40 | understanding of and approach to project instructions, and the scope of
41 | its functionalities, between you and your peers. Always remain open-minded
42 | and grade them as fairly as possible. The pedagogy is valid only and only
43 | if peer-evaluation is conducted seriously.
44 |
45 | The goal of this module is to get started with the Python language.
46 | You will study map, reduce, filter, args and kwargs ...
47 |
48 | ## Disclaimer:
49 | The serie of modules started to be produce at the time of the release of
50 | Python 3.7. Students are free to use later version of Python as long as they
51 | verified the producted code complies with all the aspects precised in the
52 | subjects.
53 | As a consequence we recommend to students to perform the modules with the
54 | the Python version 3.7 (but this is just an advice).
55 | Version can be checked with the command ```python -V```.
56 |
57 | # Guidelines:
58 | General rules:
59 | - Only grade the work that is in the student or group's GiT repository.
60 |
61 | - Double-check that the GiT repository does belong to the student.
62 | Ensure that the work is the one expected for the corrected exercise
63 | and don't forget to verify that the command "git clone" is run in an empty folder.
64 |
65 | - Check carefully that no malicious aliases were used to make you evaluate files that
66 | are not from the official repository.
67 |
68 | - To avoid any surprises, carefully check that both the evaluating and
69 | the evaluated students have reviewed the possible scripts used to facilitate the grading.
70 |
71 | - If the evaluating student has not completed that particular project yet,
72 | it is mandatory for them to read the entire subject prior to starting the defense.
73 |
74 | - Use the flags available on this scale to signal an empty repository,
75 | non-functioning program, a Norm error (specified next in general rules),
76 | cheating, and so forth.
77 | In these cases, the grading is over and the final grade is 0, or -42 in case of cheating.
78 | However, except the exception of cheating, you are encouraged to continue to discuss
79 | your work even if the later is in progress in order to identify any issues that may have
80 | caused the project failure and avoid repeating the same mistake in the future.
81 |
82 | - Use the appropriate flag.
83 |
84 | - Remember that for the duration of the defense, no other unexpected,
85 | premature, or uncontrolled termination of the program, else the final grade is 0.
86 |
87 | - You should never have to edit any file except the configuration file if the latter exists.
88 | If you want to edit a file, take the time to explain why with the evaluated student and make sure both of you agree on this.
89 |
90 | - The Norm: You will follow the PEP 8 standards.
91 |
92 | - The function eval is never allowed.
93 |
94 | - Your exercises are going to be evaluated by other students,
95 | make sure that your variable names and function names are appropriate and civil.
96 |
97 | # Exercise 0: Map, filter, reduce
98 | In the error management question, function refers to an object function
99 | (a lambda function as instance) and iter refers to an iterable object.
100 | As mentioned in the subject, we do not expect the identical exception messages
101 | to be exactly the same than those of the functions `map`, `filter` and `reduce`.
102 | The goal of the exercise is to work on the built-in functions `map`, `filter` and `reduce`.
103 |
104 | ## Errors management:
105 | ### Guidelines:
106 | each case:
107 | Launch python from the terminal:
108 | ```bash
109 | python3 -i
110 | ```
111 | Then import the functions in the python prompt
112 | ```python
113 | from ft_filter import ft_filter
114 | from ft_map import ft_map
115 | from ft_reduce import ft_reduce
116 | function = lambda x: x + 1
117 | iterable = [1, 2, 3]
118 | ```
119 | You can now copy paste the following bits of code into the python prompt in the terminal.
120 | - **ft_map function**:
121 | ```python
122 | ft_map(function_to_apply = None, iterable = iterable)
123 | ```
124 | Should print "< generator object at hexa_adress>"
125 | ```python
126 | list(ft_map(function_to_apply = None, iterable = iterable))
127 | ```
128 | You should get an Error
129 |
130 |
131 |
132 | - **ft_filter function**:
133 | ```python
134 | ft_filter(function_to_apply = None, iterable = iterable)
135 | ```
136 | Should print < generator object at hexa_adress>
137 |
138 | ```python
139 | list(ft_filter(function_to_apply = None, iterable = iterable))
140 | ```
141 | You should get an Error. (Returning None is also acceptable)
142 |
143 |
144 |
145 |
146 | - **ft_reduce function**:
147 | ```python
148 | ft_reduce(None, iterable = iterable)
149 | ```
150 | You should get an Error. (Returning None is also acceptable)
151 |
152 | ```python
153 | ft_reduce(function, None)
154 | ```
155 | You should get an Error. (Returning None is also acceptable)
156 |
157 |
158 | ## Basic tests:
159 | ### Guidelines:
160 | Perform some basic test such as the following:
161 | - `list(ft_map(lambda x: x + 2, []))`:
162 | you should get `[]`.
163 | - `list(ft_map(lambda x: x + 2, [1]))`:
164 | you should get `[3]`.
165 | - `list(ft_map(lambda x: x ** 2, [1, 2, 3, 4, 5]))`:
166 | you should get `[1, 4, 9, 16, 25]`.
167 | - `list(ft_filter(lambda x: x <= 1, []))`:
168 | you should get `[]`.
169 | - ft_reduce((lambda x, y: x + y), [1]):
170 | you should get `1`.
171 | - ft_reduce((lambda x, y: x * y), [1, 2, 3, 4]):
172 | you should get `24`.
173 | Feel free to realize few more tests.
174 |
175 |
176 | # Exercise 1: args and kwargs
177 | The goal of the exercise is to discover and manipulate `*args` and `**kwargs`.
178 |
179 | ## Basic tests
180 | ### Guidelines:
181 | ```
182 | python -i main.py
183 | ```
184 | - **With None as unique parameter**:
185 | ```python
186 | obj = what_are_the_vars(None)
187 | doom_printer(obj)
188 | ```
189 | Shoud print:
190 | ```
191 | var_0: None
192 | end
193 | ```
194 |
195 | - **With a function as argument and a function as keyword argument**:
196 | ```python
197 | obj = what_are_the_vars(lambda x: x, function=what_are_the_vars)
198 | doom_printer(obj)
199 | ```
200 | Shoud print:
201 | ```
202 | function:
203 | var_0: at 0x...>
204 | end
205 | ```
206 |
207 | - **With a kwarg named var_0**:
208 | ```python
209 | obj = what_are_the_vars(3, var_0=2)
210 | doom_printer(obj)
211 | ```
212 | Shoud print:
213 | ```
214 | ERROR
215 | end
216 | ```
217 | # Exercise 2: the logger
218 | The goal of the exercise is to discover the decorator in Python and work with
219 | a very current one: "@log".
220 |
221 | ## Basic tests
222 | ### Guidelines:
223 | Verify log decorator is correctly implemented:
224 | - It must be define in the same file.
225 | - The definition of log **takes only one parameter** which is supposed to be a
226 | function.
227 | - name is obtained via the function received as parameter (**function.\_\_name_**_).
228 | - username is obtained via the environment variable (**os.environ["USER"]**).
229 |
230 | ```bash
231 | python logger.py
232 | ```
233 | Verify the machine.log contains:
234 | ()Running: [ exec-time = ]
235 |
236 |
237 |
238 | # Exercise 3: Json issues
239 | ## Implementation
240 | ### Guidelines:
241 | Verify the different methods are implemented:
242 | - \_\_init__(self, filename=None, sep=',', header=False, skip_top=0, skip_bottom=0)
243 | - \_\_enter__(self)
244 | - \_\_exit__(self, type, value, traceback)
245 | - getdata(self)
246 | - getheader(self)
247 |
248 | **Ask the defendee to explain the \_\_func\_\_ functions to you.**
249 |
250 |
251 | ## Basic tests
252 | ### Guidelines:
253 | Perform the following tests. They should work and give correct results.
254 | Create a file called main.py and copy the following code in that file.
255 | ```python
256 | from csvreader import CsvReader
257 | import sys
258 |
259 | if __name__ == "__main__":
260 | filename = sys.argv[1]
261 | with CsvReader(filename, skip_top=18, skip_bottom=0) as reader:
262 | if reader == None:
263 | print("File is corrupted or missing")
264 | else:
265 | print(reader.getheader(), end = "\n")
266 | print(reader.getdata(), end = "\n\n")
267 |
268 | with CsvReader(filename, header = True, skip_top=17, skip_bottom=0) as reader:
269 | if reader == None:
270 | print("File is corrupted or missing")
271 | else:
272 | print(reader.getheader(), end = "\n")
273 | print(reader.getdata(), end = "\n\n")
274 | ```
275 | Put the files bad.csv and good.csv in the current folder then run in terminal:
276 | ```bash
277 | python main.py good.csv
278 | # None
279 | # [['Ruth', ' "F"', ' 28', ' 65', ' 131']]
280 |
281 | #['Name', ' "Sex"', ' "Age"', ' "Height (in)"', ' "Weight (lbs)"']
282 | #[['Ruth', ' "F"', ' 28', ' 65', ' 131']]
283 | ```
284 | The appearance of the output may vary slightly but the content and number of lines must be the same as the output above.
285 | ```bash
286 | python main.py bad.csv
287 | # File is corrupted or missing
288 | # File is corrupted or missing
289 | ```
290 |
291 | ```bash
292 | python main.py unicorn.csv
293 | # File is corrupted or missing
294 | # File is corrupted or missing
295 | ```
296 | Additional error messages may print no python messages containing `Traceback` (these indicate a crash of the python interpreter even though the python console keeps running in the terminal)
297 |
298 |
299 |
300 | # Exercise 4: MiniPack
301 | The goal of the exercise is to learn how to build a package and a distribution in Python.
302 |
303 | ## Turn-in files
304 | ### Guidelines:
305 | A python package has to be comprised of the following files according to a similar file structure (one the two setup files is enough):
306 | ```
307 | ex02/
308 | ├─ LICENSE.txt (mandatory for the exercise, recommended otherwise)
309 | ├─ pyproject.toml (recommended)
310 | ├─ README.md (mandatory for the exercise, recommended otherwise)
311 | ├─ setup.cfg (mandatory or setup.py)
312 | ├─ setup.py (mandatory or setup.cfg)
313 | ├─ src/
314 | | └───my_minipack/
315 | │ ├── __init__.py
316 | │ ├── logger.py
317 | │ └── progressbar.py
318 | └── tests/ (not asked here, recommended otherwise)
319 | ```
320 |
321 | First, check the different files in the directory. License, README,
322 | setup.py and setup.cfg files must be present and a directory containing the sources.
323 | In the sources directory you should have 3 python files (*names may not be exactly the same*):
324 | - __init__.py
325 | - logger.py
326 | - progressbar.py
327 | ## Build script
328 | ### Guidelines:
329 | Begin by running:
330 | ```bash
331 | find . -name "*.whl"
332 | find . -name "*.tar.gz"
333 | ```
334 | if any files are found delete them (make sure you are in the ex04 folder)
335 | ```bash
336 | python3 -m venv venv
337 | source venv/bin/activate
338 | bash build.sh
339 | ```
340 | **Now the defendee should tell you how to install his package in a few lines.**
341 |
342 | ```bash
343 | pip list | grep minipack
344 | # my-minipack 1.0.0
345 | ```
346 |
347 |
348 | you should now be able to import your package !
349 |
350 | ```bash
351 | python
352 | ```
353 | ```python
354 | import my_minipack.progressbar
355 | import my_minipack.logger
356 | ```
357 |
--------------------------------------------------------------------------------
/correction_03.md:
--------------------------------------------------------------------------------
1 | # Module 03 - Numpy
2 |
3 | ## Comment:
4 | This fourth module is the evolution of two original projects created by the
5 | Paris-based student organization 42 AI.
6 | They are named Bootcamp Python and Bootcamp Machine Learning.
7 | active members of 42 AI re-designed both of them for the school curriculum.
8 |
9 | Bootcamps has been developped between August 2019 and March/April 2020.
10 | Active 42AI members organized severals sessions of 2 weeks to 42Paris students
11 | to offer them the possibility to get famliar with Python and basics concepts
12 | of machine learning.
13 |
14 | The success of those sections brings the pedagogy to accept the idea to integrate
15 | the 2 bootcamps to the curriculum (initial discussion (01-05/2019) with 42 Paris
16 | pedago team highlighted a categorical opposition/refusal to this idea)
17 |
18 | The transcription had been realized over the direction of Matthieu David.
19 | Several 42AI members contributed to the redaction on the correction scales.
20 | For futur corrections on the scale, please contact the 42AI association via
21 | contact@42ai.fr or the current 42AI pedagogical supervisor.
22 |
23 | ## Introduction:
24 | The Bootcamp Python and Bootcamp Machine Learning were originally created by
25 | [42AI](https://github.com/42-AI) active members and were adapted to 'piscine'
26 | format for the school 42 curriculum.
27 | For any issue or suggestion: [42paris_staff_pedagogy](https://42born2code.slack.com/archives/C7NF60E0Z) and
28 | [42AI](https://github.com/42-AI/bootcamp_python/issues).
29 |
30 | As usual, you have to observe the following courtesy rules:
31 |
32 | - Remain polite, courteous, respectful, and constructive throughout the evaluation process.
33 | The well-being of the community depends on it.
34 |
35 | - Identify with the evaluated person or group the eventual dysfunctions of the assignment.
36 | Take the time to discuss and debate the problems you may have identified.
37 |
38 | - You must consider that there might be some differences in the
39 | understanding of and approach to project instructions, and the scope of
40 | its functionalities, between you and your peers. Always remain open-minded
41 | and grade them as fairly as possible. The pedagogy is valid only and only
42 | if peer-evaluation is conducted seriously.
43 |
44 | The goal of this module is to get started with the library Numpy.
45 |
46 | ## Disclaimer:
47 | The serie of modules started to be produce at the time of the release of
48 | Python 3.7. Students are free to use later version of Python as long as they
49 | verified the producted code complies with all the aspects precised in the
50 | subjects.
51 | As a consequence we recommend to students to perform the modules with the
52 | the Python version 3.7 (but this is just an advice).
53 | Version can be checked with the command ```python -V```.
54 |
55 | ## Guidelines:
56 | General rules
57 | - Only grade the work that is in the student or group's GiT repository.
58 |
59 | - Double-check that the GiT repository does belong to the student.
60 | Ensure that the work is the one expected for the corrected exercise
61 | and don't forget to verify that the command "git clone" is run in an empty folder.
62 |
63 | - Check carefully that no malicious aliases were used to make
64 | you evaluate files that are not from the official repository.
65 |
66 | - To avoid any surprises, carefully check that both the evaluating
67 | and the evaluated students have reviewed the possible scripts used to facilitate the grading.
68 |
69 | - If the evaluating student has not completed that particular project yet,
70 | it is mandatory for them to read the entire subject prior to starting the defense.
71 |
72 | - Use the flags available on this scale to signal an empty repository,
73 | non-functioning program, a Norm error (specified next in general rules), cheating, and so forth.
74 | In these cases, the grading is over and the final grade is 0,
75 | or -42 in case of cheating. However, except the exception of cheating, you
76 | are encouraged to continue to discuss your work even if the later is in
77 | progress in order to identify any issues that may have caused the project
78 | failure and avoid repeating the same mistake in the future.
79 |
80 | - Use the appropriate flag.
81 |
82 | - Remember that for the duration of the defense, no other unexpected,
83 | premature, or uncontrolled termination of the program, else the final grade is 0.
84 |
85 | - You should never have to edit any file except the configuration file if
86 | the latter exists. If you want to edit a file, take the time to explain why
87 | with the evaluated student and make sure both of you agree on this.
88 |
89 | - The Norm: You will follow the PEP 8 standards.
90 |
91 | - The function eval is never allowed.
92 |
93 | - Your exercises are going to be evaluated by other students,
94 | make sure that your variable names and function names are appropriate and civil.
95 |
96 | # Exercise 0 NumPyCreator
97 | ### Guidelines:
98 | To test this exercise, you can launch the follwing command on your terminal:
99 | ```bash
100 | python3
101 | ```
102 | then
103 | ```python
104 | from NumPyCreator import NumPyCreator
105 | npc = NumPyCreator()
106 | ```
107 |
108 | ## Basic tests
109 | In this python interpretor, check if all the following cases have a correct behaviour:
110 |
111 | - This command:
112 | ```python
113 | npc.from_list([[],[]])
114 | ```
115 | Shoud Output:
116 | ```
117 | array([], shape=(2, 0), dtype=float64)
118 | ```
119 |
120 |
121 | - This command:
122 | ```python
123 | npc.from_list([[1,2,3],[6,3,4],[8,5,6]])
124 | ```
125 | Shoud Output:
126 | ```
127 | array([[1, 2, 3],
128 | [6, 3, 4],
129 | [8, 5, 6]])
130 | ```
131 |
132 |
133 | - This command:
134 |
135 | ```python
136 | npc.from_tuple(("a","b","c"))
137 | ```
138 | Shoud Output:
139 | ```
140 | array(['a', 'b', 'c'], dtype='
144 |
145 | - This command:
146 | ```python
147 | npc.from_iterable(range(5))
148 | ```
149 | Shoud Output:
150 | ```
151 | array([0, 1, 2, 3, 4])
152 | ```
153 |
154 |
155 |
156 | - This command:
157 | ```python
158 | npc.from_shape((0, 0))
159 | ```
160 | Shoud Output:
161 | ```
162 | array([], shape=(0, 0), dtype=float64)
163 | ```
164 |
165 |
166 |
167 | - This command:
168 | ```python
169 | npc.from_shape((3, 5))
170 | ```
171 | Should output:
172 | ```
173 | array([[0., 0., 0., 0., 0.],
174 | [0., 0., 0., 0., 0.],
175 | [0., 0., 0., 0., 0.]])
176 | ```
177 |
178 |
179 | - This command:
180 | ```python
181 | npc.random((3, 5))
182 | ```
183 | Should output (*the values are random but th shape must be the same)*:
184 | ```
185 | array([[0.74819604, 0.32295616, 0.27371925, 0.57171326, 0.92582071],
186 | [0.70307642, 0.94846695, 0.12465384, 0.25146454, 0.11179953],
187 | [0.38326719, 0.26179493, 0.88157011, 0.29978869, 0.72677049]])`
188 | ```
189 |
190 |
191 |
192 | - This command:
193 | ```python
194 | npc.identity(4)
195 | ```
196 | Should output:
197 | ```
198 | array([[1., 0., 0., 0.],
199 | [0., 1., 0., 0.],
200 | [0., 0., 1., 0.],
201 | [0., 0., 0., 1.]])
202 | ```
203 |
204 |
205 | For values contained in identity and from_shape function, both integer and float values are acceptable.
206 |
207 |
208 | ## Error management
209 | Run this:
210 | ```python
211 | print(npc.from_list("toto"))
212 | print(npc.from_list([[1,2,3],[6,3,4],[8,5,6,7]]))
213 | print(npc.from_tuple(3.2))
214 | print(npc.from_tuple(((1,5,8),(7,5))))
215 | print(npc.from_shape((-1, -1)))
216 | print(npc.identity(-1))
217 | ```
218 | Should print:
219 | ```python
220 | None
221 | None
222 | None
223 | None
224 | None
225 | None
226 | ```
227 |
228 | # Exercise 1 ImageProcessor
229 | ## Implementation
230 | ### Guidelines:
231 | To test this exercise, you can launch the follwing command on your terminal:
232 | ```bash
233 | python3
234 | ```
235 |
236 | then
237 | ```bash
238 | from ImageProcessor import ImageProcessor
239 | imp = ImageProcessor()
240 | ```
241 |
242 | Verify the class ImageProcessor and that the methods '**load**' and '**display**'
243 | are implemented in \"ImageProcessor.py\".
244 |
245 | As a class, special method '**\_\_init\_\_**' has to be present.
246 | - The method '**load** :
247 | ```python
248 | arr = imp.load("../ressources/42AI.png")
249 | # Loading image of dimensions 200 x 200
250 | print(arr)
251 | ```
252 | The print should display a nested list of RGB pixel numbers contained by the image (cf subject)
253 |
254 |
255 |
256 | - The method '**display**' :.
257 | ```python
258 | imp.display(arr)
259 | ```
260 | The image should be displayed in a separate window when running in the console.
261 |
262 |
263 |
264 |
265 | # Exercise 2 ScrapBooker
266 | ## Basic tests
267 | Perform basic tests to verify the proper behaviour of the different methods.
268 | First, launch the python interpreter by taping the following command on your terminal:
269 | ```
270 | python3
271 | ```
272 | - then copy paste the commands and check if they have the same output aviour as here:
273 | ```python
274 | import numpy as np
275 | from ScrapBooker import ScrapBooker
276 | spb = ScrapBooker()
277 | arr1 = np.arange(0,25).reshape(5,5)
278 | spb.crop(arr1, (3,1),(1,0))
279 | ```
280 |
281 | Output:
282 | ```python
283 | array([[ 5],
284 | [10],
285 | [15]])
286 | ```
287 |
288 |
289 |
290 | -
291 | ```python
292 | arr2 = np.array("A B C D E F G H I".split() * 6).reshape(-1,9)
293 | spb.thin(arr2,3,0)
294 | ```
295 |
296 | Output :
297 | ```python
298 | array([['A', 'B', 'D', 'E', 'G', 'H'],
299 | ['A', 'B', 'D', 'E', 'G', 'H'],
300 | ['A', 'B', 'D', 'E', 'G', 'H'],
301 | ['A', 'B', 'D', 'E', 'G', 'H'],
302 | ['A', 'B', 'D', 'E', 'G', 'H'],
303 | ['A', 'B', 'D', 'E', 'G', 'H']], dtype='
307 |
308 | -
309 | ```python
310 | arr3 = np.array([[var] * 10 for var in "ABCDEFG"])
311 | spb.thin(arr3,3,1)
312 | ```
313 |
314 | Output :
315 | ```python
316 | array([['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A'],
317 | ['B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B'],
318 | ['D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D'],
319 | ['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
320 | ['G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G', 'G']], dtype='
324 |
325 | -
326 | ```python
327 | arr4 = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
328 | spb.juxtapose(arr4, 2, 0)
329 | ```
330 |
331 | Output :
332 | ```python
333 | array([[1, 2, 3],
334 | [4, 5, 6],
335 | [7, 8, 9],
336 | [1, 2, 3],
337 | [4, 5, 6],
338 | [7, 8, 9]])
339 | ```
340 |
341 | ## Error managment
342 | First, verify the class is correctly implemented and has the 4 methods and the
343 | constructor ('\_\_init\_\_').
344 | try:
345 | ```python
346 | not_numpy_arr = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
347 | spb.crop(not_numpy_arr, (1,2))
348 | spb.juxtapose(arr4, -2, 0)
349 | spb.mosaic(arr4, (1, 2, 3))
350 | ```
351 | These functions should all return None because of incorect parameters (*Nothing will show on screen when you run the above code*)
352 |
353 |
354 |
355 |
356 |
357 | # Exercise 3 ColorFilter
358 |
359 | ## Basic tests
360 | Test the different methods, by taking a .png image of your choice and applying the filters.
361 | **The defendee may run ANY code he wishes to show the image effects to validate this excercise. This code is only meant to facilitate correction.**
362 | Celluloid is poorly documented so it is considered optional.
363 |
364 |
365 |
366 | Copy this code into a file, replace `""` by the actual path to the image and run the file with python (if the image is not a true .png this will crash, run it with the elonGAN image).
367 | ```python
368 | import numpy as np
369 | import matplotlib
370 | from matplotlib import pyplot as plt
371 |
372 | from ColorFilter import ColorFilter
373 | cf = ColorFilter()
374 |
375 | for f in [cf.to_red, cf.to_green, cf.to_blue, cf.invert]:
376 | array = plt.imread("")
377 | plt.imshow(f(array))
378 | plt.show()
379 |
380 | im = cf.to_grayscale(array, "m")
381 | plt.imshow(im, cmap="gray")
382 | plt.show()
383 |
384 | im = cf.to_grayscale(array, "w", weights = [0.2126, 0.7152, 0.0722])
385 | plt.imshow(im, cmap="gray")
386 | plt.show()
387 | ```
388 |
389 | You should see a Red, Blue, Green, Inverted and Gray version of the image
390 | **YOU HAVE TO CLOSE THE IMAGES THAT SHOW ON SCREEN FOR THE NEXT IMAGE TO SHOW**
391 |
392 |
393 |
394 |
395 | # Exercise 4 K-means Clustering
396 | ## Implementaion & Basic tests
397 | ### Guidelines:
398 | - First verify the correct implementation of the class (constructor and methods).
399 | Try launching the following command with the corresponding path on your terminal:
400 | ```bash
401 | python Kmeans.py filepath='' ncentroid=4 max_iter=30
402 | ```
403 | - The centroids are randomly initialized.
404 | - Program can handles different set of values (reasonnable ones) for 'ncentroid' and 'max_iter' arguments.
405 | - For a fix value of 'ncentroid', centroids coordinates slightly differ when running the algorithm multiple times.
406 | - Results are coherent and consistent trough multiple program execution.
407 | Most of the time, centroids converged to similar coordinates and number people associated to each centroids varies little.
408 |
--------------------------------------------------------------------------------
/correction_04.md:
--------------------------------------------------------------------------------
1 | # Module 04 - Pandas
2 |
3 | ## Comment:
4 | This fifth module is the evolution of two original projects created by the
5 | Paris-based student organization 42 AI.
6 | They are named Bootcamp Python and Bootcamp Machine Learning.
7 | active members of 42 AI re-designed both of them for the school curriculum.
8 |
9 | Bootcamps has been developped between August 2019 and March/April 2020.
10 | Active 42AI members organized severals sessions of 2 weeks to 42Paris students
11 | to offer them the possibility to get famliar with Python and basics concepts
12 | of machine learning.
13 |
14 | The success of those sections brings the pedagogy to accept the idea to integrate
15 | the 2 bootcamps to the curriculum (initial discussion (01-05/2019) with 42 Paris
16 | pedago team highlighted a categorical opposition/refusal to this idea)
17 |
18 | The transcription had been realized over the direction of Matthieu David.
19 | Several 42AI members contributed to the redaction on the correction scales.
20 | For futur corrections on the scale, please contact the 42AI association via
21 | contact@42ai.fr or the current 42AI pedagogical supervisor.
22 |
23 | ## Introduction:
24 | The Bootcamp Python and Bootcamp Machine Learning were originally created by
25 | [42AI](https://github.com/42-AI) active members and were adapted to 'piscine'
26 | format for the school 42 curriculum.
27 | For any issue or suggestion: [42paris_staff_pedagogy](https://42born2code.slack.com/archives/C7NF60E0Z) and
28 | [42AI](https://github.com/42-AI/bootcamp_python/issues).
29 |
30 | As usual, you have to observe the following courtesy rules:
31 |
32 | - Remain polite, courteous, respectful, and constructive throughout the evaluation process.
33 | The well-being of the community depends on it.
34 |
35 | - Identify with the evaluated person or group the eventual dysfunctions of the assignment.
36 | Take the time to discuss and debate the problems you may have identified.
37 |
38 | - You must consider that there might be some differences in the understanding
39 | of and approach to project instructions, and the scope of its functionalities,
40 | between you and your peers. Always remain open-minded and grade them as fairly as possible.
41 | The pedagogy is valid only and only if peer-evaluation is conducted seriously.
42 |
43 | The goal of this module is to get started with the library Pandas and the
44 | manipulation of dataframes.
45 |
46 | ## Disclaimer:
47 | The serie of modules started to be produce at the time of the release of
48 | Python 3.7. Students are free to use later version of Python as long as they
49 | verified the producted code complies with all the aspects precised in the
50 | subjects.
51 | As a consequence we recommend to students to perform the modules with the
52 | the Python version 3.7 (but this is just an advice).
53 | Version can be checked with the command ```python -V```.
54 |
55 | ## Guidelines:
56 | General rules
57 | - Only grade the work that is in the student or group's GiT repository.
58 |
59 | - Double-check that the GiT repository does belong to the student.
60 | Ensure that the work is the one expected for the corrected exercise
61 | and don't forget to verify that the command "git clone" is run in an empty folder.
62 |
63 | - Check carefully that no malicious aliases were used to make
64 | you evaluate files that are not from the official repository.
65 |
66 | - To avoid any surprises, carefully check that both the evaluating
67 | and the evaluated students have reviewed the possible scripts used to facilitate the grading.
68 |
69 | - If the evaluating student has not completed that particular project yet,
70 | it is mandatory for them to read the entire subject prior to starting the defense.
71 |
72 | - Use the flags available on this scale to signal an empty repository, non-functioning program,
73 | a Norm error (specified next in general rules), cheating, and so forth.
74 | In these cases, the grading is over and the final grade is 0,
75 | or -42 in case of cheating. However, except the exception of cheating, you
76 | are encouraged to continue to discuss your work even if the later is in
77 | progress in order to identify any issues that may have caused the project
78 | failure and avoid repeating the same mistake in the future.
79 |
80 | - Use the appropriate flag.
81 |
82 | - Remember that for the duration of the defense, no other unexpected,
83 | premature, or uncontrolled termination of the program, else the final
84 | grade is 0.
85 |
86 | - You should never have to edit any file except the configuration file if
87 | the latter exists. If you want to edit a file, take the time to explain why
88 | with the evaluated student and make sure both of you agree on this.
89 |
90 | - The Norm: You will follow the PEP 8 standards.
91 |
92 | - The function eval is never allowed.
93 |
94 | - Your exercises are going to be evaluated by other students,
95 | make sure that your variable names and function names are appropriate and civil.
96 |
97 | # Exercise 0 - FileLoader
98 | The goal of this exercise is to create a Fileloader class containing a load and a display method.
99 |
100 | put the path to the csv file in an environment variable
101 |
102 | ```bash
103 | export CSV_PATH="path_to_athletes_events.csv"
104 | python 3
105 | ```
106 |
107 |
108 |
109 | -
110 | ```python
111 | from FileLoader import FileLoader
112 | import os
113 |
114 | f = FileLoader()
115 |
116 | df = f.load(os.environ["CSV_PATH"])
117 | ```
118 | Should output (approximately) :
119 | ```python
120 | # (271116, 15)
121 | ```
122 |
123 |
124 |
125 |
126 |
127 | -
128 | ```python
129 | f.display(df, 3)
130 | ```
131 | Should Output
132 | ```python
133 | # ID Name Sex Age Height Weight Team NOC Games Year Season City Sport Event Medal
134 | # 0 1 A Dijiang M 24.0 180.0 80.0 China CHN 1992 Summer 1992 Summer Barcelona Basketball Basketball Men's Basketball NaN
135 | # 1 2 A Lamusi M 23.0 170.0 60.0 China CHN 2012 Summer 2012 Summer London Judo Judo Men's Extra-Lightweight NaN
136 | # 2 3 Gunnar Nielsen Aaby M 24.0 NaN NaN Denmark DEN 1920 Summer 1920 Summer Antwerpen Football Football Men's Football NaN
137 | ```
138 |
139 |
140 |
141 | -
142 | ```python
143 | f.display(df, -3)
144 | ```
145 |
146 | Should output:
147 | ```python
148 | # ID Name Sex Age Height Weight Team NOC Games Year Season City Sport Event Medal
149 | # 271113 135570 Piotr ya M 27.0 176.0 59.0 Poland POL 2014 Winter 2014 Winter Sochi Ski Jumping Ski Jumping Men's Large Hill, Team NaN
150 | # 271114 135571 Tomasz Ireneusz ya M 30.0 185.0 96.0 Poland POL 1998 Winter 1998 Winter Nagano Bobsleigh Bobsleigh Men's Four NaN
151 | # 271115 135571 Tomasz Ireneusz ya M 34.0 185.0 96.0 Poland POL 2002 Winter 2002 Winter Salt Lake City Bobsleigh Bobsleigh Men's Four NaN
152 | ```
153 |
154 |
155 |
156 | -
157 | ```python
158 | f.display(df, 0)
159 | # should display Nothing or the Header (column names of the dataframe)
160 | ```
161 |
162 |
163 |
164 | -
165 | ```python
166 | f.display(df, "lol")
167 | #shouldnt crash
168 |
169 | ```
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 | # Exercise 1 - YoungestFellah
178 | The goal of this exercise is to create a function that will return a
179 | dictionary containing the age of the youngest woman and the youngest
180 | man who took part in the Olympics a given year.
181 |
182 | ## Basic tests'
183 | Check the results of the following cases:
184 | *The name of the function YoungestFellah may be changed to make this code run*
185 |
186 | ```python
187 | from FileLoader import FileLoader
188 | from YoungestFellah import youngestfellah
189 | import os
190 |
191 | loader = FileLoader()
192 | data = loader.load(os.environ["CSV_PATH"])
193 |
194 |
195 | print(youngestfellah(data, 1992))
196 | # output is: "{'f': 12.0, 'm': 11.0}"
197 |
198 | print(youngestfellah(data, 2004))
199 | # output is: "{'f': 13.0, 'm': 14.0}"
200 |
201 | print(youngestfellah(data, 2010))
202 | # output is: "{'f': 15.0, 'm': 15.0}"
203 |
204 | print(youngestfellah(data, 2003))
205 | # output is: "{'f': nan, 'm': nan}"
206 | ```
207 | If something does not match, the exercise is failed.
208 |
209 |
210 |
211 |
212 | # Exercise 2 - ProportionBySport
213 | The goal of this exercise is to create a function displaying the proportion
214 | of participants who played a given sport, among the participants of a given
215 | genders.
216 |
217 | ## Basic tests'
218 | Verify the results of the following cases: (please adapt the path to csv file)
219 | ```python
220 | from FileLoader import FileLoader
221 | from ProportionBySport import proportionBySport
222 | import os
223 |
224 | loader = FileLoader()
225 | data = loader.load(os.environ["CSV_PATH"])
226 |
227 | print("")
228 |
229 | print(proportionBySport(data, 2004, 'Tennis', 'F'), end = "\n\n")
230 | # output is "0.02307"
231 |
232 | print(proportionBySport(data, 2008, 'Hockey', 'F'), end = "\n\n")
233 | # output is "0.03284"
234 |
235 | print(proportionBySport(data, 1964, 'Biathlon', 'M'), end = "\n\n")
236 | # output is "0.00659"
237 | ```
238 | **The rounding of the result does no matter (0.023 or 0.02307969707897584 or 2.3 % are all acceptable**
239 | If something does not match, the exercise is failed.
240 |
241 |
242 |
243 |
244 | # Exercise 3 - HowManyMedals
245 | The goal of this exercise is to code a function that will return
246 | a dictionary of dictionaries giving the number and type of medals
247 | for each year during which the participant won medals.
248 |
249 | ## Basic tests
250 | Verify the results of the following cases: (Please adapt the path to csv file)
251 | ```python
252 | import pandas as pd
253 | from HowManyMedals import howManyMedals
254 | import os
255 |
256 | data = pd.read_csv(os.environ["CSV_PATH"])
257 |
258 | print(howManyMedals(data, 'Gary Abraham'))
259 | # the output is: "{1976: {'G': 0, 'S': 0, 'B': 0}, 1980: {'G': 0, 'S': 0, 'B': 1}}"
260 |
261 | print(howManyMedals(data, 'Yekaterina Konstantinovna Abramova'))
262 | # the output is "{2006: {'G': 0, 'S': 0, 'B': 1}, 2010: {'G': 0, 'S': 0, 'B': 0}}"
263 |
264 | print(howManyMedals(data, 'Kristin Otto'))
265 | # the output is: "{1988: {'G': 6, 'S': 0, 'B': 0}}"
266 | ```
267 | If something does not match, the exercise is failed.
268 |
269 |
270 |
271 |
272 |
273 | # Exercise 4 - SpatioTemporalData
274 | The goal of this exercise is to write a class called SpatioTemporalData
275 | that takes a dataset (pandas.DataFrame) as argument in its constructor
276 | and implements two methods.
277 |
278 |
279 | ## Basic tests
280 | Check the result of the following cases:
281 | ```python
282 | import pandas as pd
283 | from SpationTemporalData import SpatioTemporalData
284 | import os
285 |
286 | df = pd.read_csv(os.environ["CSV_PATH"])
287 | sp = SpatioTemporalData(df)
288 |
289 | print(sp.where(2000))
290 | # output is: ['Sydney']
291 |
292 | print(sp.where(1980))
293 | # output is: ['Lake Placid', 'Moskva'] If a single of these locations is returned it's ok.
294 |
295 | print(sp.when('London'))
296 | # output is: [2012, 1948, 1908]
297 | ```
298 |
299 | You should try other locations and years.
300 | If something does not match, the exercise is failed.
301 |
302 |
303 | # Exercise 5 - HowManyMedalsByCountry
304 | The goal of this exercise is to write a function that returns a
305 | dictionary of dictionaries giving the number and type of medal for
306 | each competition where the country delegation earned medals.
307 |
308 |
309 | ## Basic tests'
310 | Print the result of howManyMedalsByCountry functions calls with various countries
311 | and check that the format respects the following:
312 | ```python
313 | import pandas as pd
314 | from HowManyMedalsByCountry import howManyMedalsByCountry
315 | import os
316 |
317 | df = pd.read_csv(os.environ["CSV_PATH"])
318 |
319 | print(howManyMedalsByCountry(df, "United States") == {1896: {'G': 11, 'S': 7, 'B': 2}, 1900: {'G': 18, 'S': 14, 'B': 13}, 1904: {'G': 65, 'S': 68, 'B': 66}, 1906: {'G': 12, 'S': 6, 'B': 6}, 1908: {'G': 34, 'S': 16, 'B': 15}, 1912: {'G': 46, 'S': 25, 'B': 36}, 1920: {'G': 87, 'S': 41, 'B': 35}, 1924: {'G': 65, 'S': 41, 'B': 36}, 1928: {'G': 39, 'S': 22, 'B': 18}, 1932: {'G': 60, 'S': 57, 'B': 43}, 1936: {'G': 30, 'S': 29, 'B': 28}, 1948: {'G': 57, 'S': 34, 'B': 30}, 1952: {'G': 55, 'S': 38, 'B': 25}, 1956: {'G': 39, 'S': 57, 'B': 21}, 1960: {'G': 83, 'S': 27, 'B': 19}, 1964: {'G': 75, 'S': 36, 'B': 28}, 1968: {'G': 86, 'S': 36, 'B': 35}, 1972: {'G': 70, 'S': 58, 'B': 33}, 1976: {'G': 62, 'S': 46, 'B': 30}, 1980: {'G': 24, 'S': 4, 'B': 2}, 1984: {'G': 143, 'S': 75, 'B': 33}, 1988: {'G': 66, 'S': 48, 'B': 36}, 1992: {'G': 79, 'S': 46, 'B': 52}, 1994: {'G': 6, 'S': 8, 'B': 5}, 1996: {'G': 98, 'S': 41, 'B': 28}, 1998: {'G': 25, 'S': 2, 'B': 3}, 2000: {'G': 69, 'S': 34, 'B': 48}, 2002: {'G': 9, 'S': 52, 'B': 9}, 2004: {'G': 65, 'S': 66, 'B': 38}, 2006: {'G': 9, 'S': 7, 'B': 32}, 2008: {'G': 64, 'S': 61, 'B': 47}, 2010: {'G': 8, 'S': 61, 'B': 20}, 2012: {'G': 82, 'S': 44, 'B': 38}, 2014: {'G': 8, 'S': 28, 'B': 16}, 2016: {'G': 95, 'S': 52, 'B': 45}})
320 | ```
321 | Should output `True`
322 | **If the previous test fails the defendee should use the following list for team sports**, If he does not filter for team sports, he failed the exercise.
323 | ```python
324 | team_sports = ['Basketball', 'Football', 'Tug-Of-War', 'Badminton', 'Sailing', 'Handball', 'Water Polo', 'Hockey', 'Rowing', 'Bobsleigh', 'Softball', 'Volleyball', 'Synchronized Swimming', 'Baseball', 'Rugby Sevens', 'Rugby', 'Lacrosse', 'Polo']
325 | ```
326 |
327 | # Exercise 6 - MyPlotLib
328 | The goal the exercise is to introduce plotting methods among the different
329 | libraries Pandas, Matplotlib, Seaborn or Scipy
330 |
331 |
332 | ## Basic tests'
333 | Performs the following basic tests with the given dataset
334 | with at least 3 numerical features:
335 | - run the method histogram with one, two and three valid features
336 | - run the method density with one, two and three valid features
337 | - run the method pair_plot with one, two and three valid features
338 | - run the method box_plot with one, two and three valid features
339 |
340 | # Exercise 7 - Komparator
341 | The goal the exercise is to introduce plotting methods among the different
342 | libraries Pandas, Matplotlib, Seaborn or Scipy.
343 |
344 |
345 | ## Basic tests'
346 | Verify you get the expected plots for each methods:
347 | -
348 | - giving 'Medal' and 'Age' for the method compare_box_plots, you
349 | should observe 3 boxes: Bronze. Silver and Gold
350 | - giving 'Medal' and 'Height' for the method compare_histograms, you
351 | should observe 3 histograms
352 | - giving 'Medal' and 'Weight' for the method density, you should
353 | observe 3 curves of density plot
354 |
--------------------------------------------------------------------------------