import mermaid from 'https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.2.3/mermaid.esm.min.mjs'; mermaid.initialize({ startOnLoad: true });
La programmation est devenue un outil essentiel du datascientist mais pas seulement. Beaucoup d'outils pointus sont open source mais uniquement accessibles à ceux qui savent programmer. Après la mise au point d'un modèle statistique, économique, il se pose souvent la question de la mise à jour fréquente des résultats, c'est à dire leur automatisation via la programmation.
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Programmation, ENSAE, automatisation, emplois
def position_max(tableau):
for i in range(0, len(tableau)):
if tableau[i] == max(tableau):
return i
mx = position_max([6, 7, 4, 11, -5, 4])
mx
3
a = 3
a = 3
p = 4.56
b = 'r'
c = (4, 6)
g = [5, 4]
d = {'a': 0, 'b': 1}
h = 7
if h % 2 == 0:
msg = 'pair'
else:
msg = 'impair'
print(msg)
impair
for element in [4, 5, 8]:
print(element)
4 5 8
it = 0
while it < 24:
print(it)
it += 5
0 5 10 15 20
def area(l, w):
return l * w
print(area(4, 5))
20
def area(l, w):
print(l * w)
print(area(4, 5))
20 None
import math
from math import cos
cos(5) + math.sin(5)
-0.6752620891999122
class Vase:
def __init__(self, hauteur, diametre):
self.hauteur = hauteur
self.diametre = diametre
def area(self):
return self.hauteur * self.diametre * math.pi
v = Vase(5, 3)
print(v.area())
47.12388980384689
import numpy
mat1 = numpy.array([[1, 2, 3], [4, 5, 6]])
mat2 = numpy.array([[1, -1], [-1, 1], [0, 0]])
mat1 @ mat2
array([[-1, 1], [-1, 1]])
mat2 @ mat1
array([[-3, -3, -3], [ 3, 3, 3], [ 0, 0, 0]])
import pandas
df = pandas.DataFrame([{'col1': 4.5, 'col2': "legend"},
{'col1': 4.5, 'col3': -8},
{'col1': 14.5, 'col3': -80, 'col2': 'note'}])
df
col1 | col2 | col3 | |
---|---|---|---|
0 | 4.5 | legend | NaN |
1 | 4.5 | NaN | -8.0 |
2 | 14.5 | note | -80.0 |
df.isna()
col1 | col2 | col3 | |
---|---|---|---|
0 | False | False | True |
1 | False | True | False |
2 | False | False | False |
df.isna().astype(numpy.int64)
col1 | col2 | col3 | |
---|---|---|---|
0 | 0 | 0 | 1 |
1 | 0 | 1 | 0 |
2 | 0 | 0 | 0 |
df[df['col1'] >= 10]
col1 | col2 | col3 | |
---|---|---|---|
2 | 14.5 | note | -80.0 |
rnd = numpy.random.randn(50, 3) @ numpy.array([[1, 0, 1], [0, 1, 0], [0, -3, 1]])
rnd[:5]
array([[ 0.06607333, 4.74896639, -1.11535865], [-1.28671779, 1.2653011 , -2.10633038], [-0.40579191, -0.85452334, -0.34367823], [-1.10590692, 1.92898689, -1.25570647], [ 0.43969349, 4.22563223, -1.25008265]])
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 3, figsize=(12, 4), sharex=True, sharey=True)
ax[0].plot(rnd[:, 0], rnd[:, 1], '.')
ax[0].set_title("Axes 1 et 2")
ax[1].plot(rnd[:, 1], rnd[:, 2], '.')
ax[1].set_title("Axes 2 et 3")
ax[2].plot(rnd[:, 0], rnd[:, 1], '.', label="Axes 1 et 2")
ax[2].plot(rnd[:, 1], rnd[:, 2], '.', label="Axes 2 et 3")
ax[2].set_title("Axes 1 et 2 et 3")
ax[2].legend();
from IPython.display import SVG, Image
Image("https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png")
Image("https://upload.wikimedia.org/wikipedia/commons/6/60/Mergesort_algorithm_diagram.png")
SVG("https://upload.wikimedia.org/wikipedia/commons/3/38/Max-Heap.svg")
SVG("https://upload.wikimedia.org/wikipedia/commons/2/29/DijkstraBis01.svg")
Image("tsp.png", width=400)
Image("https://upload.wikimedia.org/wikipedia/commons/d/d1/Levenshtein_distance_animation.gif")
<IPython.core.display.Image object>
SVG("https://upload.wikimedia.org/wikipedia/commons/f/fd/Knapsack.svg")
Image('https://upload.wikimedia.org/wikipedia/commons/2/25/Tetrahedron.png', width=400)
Image("postier.png")
Image("dectree.png")
Les programmes qui plantent mais en fait c'est pas grave.
try:
y = 1 / 0
except Exception as e:
print(type(e), e)
<class 'ZeroDivisionError'> division by zero
Ou des fois-ci
try:
x = -1
if x < 0:
raise ValueError("La racine carrée d'un nombre positif est inconnue de ce programme.")
except Exception as e:
print(type(e), e)
<class 'ValueError'> La racine carrée d'un nombre positif est inconnue de ce programme.
import re
reg = re.compile("[A-Z]{2,}")
texte = "Etrange ces acronymes comme ENSAE ou CPU qui ressortent comme par magie."
reg.findall(texte)
['ENSAE', 'CPU']
Ou comment protéger son code contre l'intrusion d'un codeur distrait.
def return_sept(n):
return int('7' * n)
def test_unitaire():
# Si ça plante, c'est de votre faute.
assert return_sept(4) == 7777
test_unitaire()
Il y a plusieurs façons de passer à la postérité. C'est l'une d'elle.
Image("suggestion.png")
Le trie
SVG('https://upload.wikimedia.org/wikipedia/commons/b/be/Trie_example.svg')
...
...
par reconnaissance faciale mais qui échoue pour cause de masques qui passe alors par la voix en demandant de chanter du Johnny.