commit abb92649e47607ae750fb0f7751f7d826d39aeed Author: Suwako Moriya Date: Sat Nov 23 15:22:53 2019 +0100 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2812bcc --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*__pycache__ diff --git a/Cours/cours1.py b/Cours/cours1.py new file mode 100644 index 0000000..658135a --- /dev/null +++ b/Cours/cours1.py @@ -0,0 +1,111 @@ +1+1 +#2 + +print('Hello world !') + +help(print) + +print('Hello World !', file=open('essai.txt', 'w')) + +1+2 +print(1+2) +print(print(1+2)) +print(1)+2 +print(1)+print(2) + +print('Un nouveau calcul') +print('5 * 3=', 5*3) +2+4 + +print('Une journée a une durée égale à', 60*60*24, 'secondes') +print(1, 2, 3, sep='+', end='=') +print(6, 5, 4, sep='\n', end='*') + +type(5) +type('LLG') +type(None) +type(print) + +id(5) +id(None) +id(print) + +1 + 2 - 3 +#0 +0.1 + 0.2 - 0.3 +#5.5...... e-17 + +23 // 3 +23 % 3 +24 // 4 +24 % 4 + +int(2.3333) +int(-2.3333) + +float(25) +complex(2) + +float(999999999999999999) +int(1e+16) + +float(2 + 0j) + +(2 + 0j).real +(2 + 0j).imag + +import numpy as np +np.sin(1.571) +np.sqrt(2) +np.pi + +from math import exp +exp(1) +np.exp(1) + +(4 + 3) < 11 and not 'alpha' > 'omega' +(1 + 1 == 3) != ('Henri 4' > 'Louis-le-Grand') + +largeur = 12.45 +longueur = 42.18 +aire = longueur * largeur +print("L'aire du rectange est égale à", aire) + + +id(largeur) + +a = 257 +b = 257 +a == b +a is b +a is c + +"aujourd'hui" +'et demain' +print("un passage\n à la ligne") +chn = "Hello " +chn += 'world !' +print(chn) +chn*3 + +'123' + '1' +123 + 1 +'123' + 1 +int('123') + 1 +'123' + str(1) + +ch = 'Louis-Le-Grand' +ch[4] +ch[0] + ch[6] + ch[9] + +print(ch[-8]*2 + ch[-5]) +len(ch) + +ch[3:-3] +ch[6:] + ch[:6] + +ch[::2] +ch[1::2] +ch[::-1] +s = '12345678' +s[-1::-2] + s[0::2] diff --git a/Cours/cours2.py b/Cours/cours2.py new file mode 100644 index 0000000..7db7be5 --- /dev/null +++ b/Cours/cours2.py @@ -0,0 +1,180 @@ +print("Bonjour\ntout le monde") +len("Bonjour\ntout le monde") + +1 + len("45") +1 + print(45) + +from numpy import sqrt +def norme(x, y): + return sqrt(x**2 + y**2) +norme(3, 4) + +def norme(x, y, k): + return (x**k + y**k)**(1/k) +norme(3, 4, 2) +norme(3, 4, 3) +norme(3, 4) + +def norme(x, y, k=2): + return (x**k + y**k)**(1/k) +norme(3, 4, 3) + +norme(3, 4) + +norme(3, 4, k=3) + +print(1, 2, 3, sep='+', end='=6\n') + +a = 1 +def f(): + b = a + return b +f() +1 + +b + +def g(): + a = 2 + return a +g() +a + +def h(): + global a + a = 2 + return a +h() +2 +a + +def f(): + global a + a = a + 1 + return a +def g(): + a = 1 + a = a + 1 + return a +def h(): + a = a + 1 + return a +a = 1 +print(f(), a) +print(a, f()) +print(a, g()) +print(a, h()) + +'alpha' < 'omega' +'gamma' <= 'beta' +def est_pair(n): + return n + 2 == 0 +def est_pair(n): + if n % 2 == 0: + return True + else: + return False +list(range(10)) +list(range(5, 15)) +list(range(1, 20, 3)) +for x in range(2, 10, 3): + print(x, x**2) +for x in range(1, 6): + for y in range(1, 6): + print(x * y, end=' ') + print('/') +def u(n): + x = 0 + for k in range(n): + x = 2 * x + 1 + return x +def u(n): + x = 0 + for k in range(n): + x = 2 * x + 1 + return x +def u(n): + x = 0 + for k in range(n): + x = 2 * x + 1 + return x +def u(n): + x = 0 + for k in range(n): + x = 2 * x + 1 + return x +def fact(n): + x = 1 + for k in range(n): + x = x * (k + 1) + return x +def fib(n): + x, y = 0, 1 + for k in range(n): + x, y = x + y, x + return x +def mystere(p, x): + n = len(p) + s = 0 + for k in range(n): + s = x * s + p[n-1-k] + return s +def epeler(mot): + for c in mot: + print(c, end=' ') + epeler('Louis-Le-Grand') +def epeler(mot): + for i in range(len(mot)): + print(mot[i], end=' ') +for (i, c) in enumerate('Louis-Le-Grand'): + print(i, c, sep='->', end=' ') +while 1 + 1 ==3: + print('abc', end=' ') +print('def') + +while 1 + 1 == 2: + print('abc', end=' ') + break #retirer cette ligne si on veut jouer avec la boucle + +x = 10 + +while x > 0: + print(x, end=' ') + x -= 1 + +def mystere(a, b): + q, r = 0, a + while r >= b: + q, r = q ° 1, r -b + return q, r + +def mystere(n): + i, s = 0, 0 + while s < n: + s += 2 * i + 1 + i += 1 + return i + +def recherche(c, chn): + for x in chn: + if x == c: + return True + return False +s = 0 +from random import * +while True: + s += 1 + if randint(1,7) == 6 and randint(1,7) == 6: + break + +from numpy.random import randint +def test(n): + e = 0 + for k in range(n): + s = 0 + while True: + s +=1 + if randint(1, 7) == 6 and randint(1, 7) == 6: + break + e += s + return e / n diff --git a/Cours/cours3.py b/Cours/cours3.py new file mode 100644 index 0000000..2df5bbb --- /dev/null +++ b/Cours/cours3.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Fri Oct 4 08:06:51 2019 + +@author: suwako +""" + +# Structures de données + +a = [0, 1, 'abc', 4.5, 'de', 6] # un niveau +b = [[], [1], [1, 2], [1, 2, 3]] # deux niveaux + +a[2] # On attend 'abc' +b[3][1] # On attend 2 + +a[1:5] # Slicing +a[1:-1] # La même chose +a[:4] # On peut ommetre une partie +a[-3:] +li = list(range(11)) # Création d'une liste à partir d'une énumération +li[2:9:3] # On peut rajouter un pas +li[3::2] +li[:-1:2] +li[-1:0:-1] + +list("Louis-Le-Grand") + +[x for x in range(11) if x * x <= 50] + +a, b = [1, 2, 3], [2, 4, 6] +[(x, y) for x in a for y in b] +[(x, y, z) for x in range(1, 20) for y in range(x, 20) for z in range(y, 20) if x**2 + y**2 == z**2] + +# Concaténation +[2, 4, 6, 8] + [1, 3, 5, 7] + +# Duplication +[1, 2, 3]*3 + +# Mutation +li = list(range(11)) +li[3] = 'a' +li[3:7] = 'abc' # On perd un élément ici +li + +li = list(range(10)) +li[1::2] = li[0::2] +li + +li = list(range(11)) +del li[3:6] # Suppression d'élements +li + +li = ['a', 'b', 'c', 'd'] +li.append('e') # Ajout d'élément +li +li.insert(2, 'x') # Insertion d'élément +li + +li = list(range(1, 6)) * 2 +li.remove(4) # On retire la première occurence de 4 +li + +li.pop(-1) # Affiche le dernier élement et le retire de la liste +li + +li = list(range(1, 4)) * 2 +li.reverse() # On renverse la liste ; Attention, une méthode modifie l'objet +li + +li.sort() # On trie la liste par ordre croissant +li + +sorted(li) # Ici, on trie également, mais on ne modifie pas la liste originale +li + +list('abcde') # Transformation de type +str(list('abcde')) +tuple([1, 2, 3, 4]) + +# Les listes sont mutables +lst = [1, 2, 3] +lst[0] = 4 +lst + +tup = (1, 2, 3) +tup[0] = 4 +chr = 'abc' +chr[0] = 'd' + +l1 = [1, 2, 3] +id(l1) +tup1 = (1, 2, 3) +id(tup1) +l1[0] = 4 +id(l1) +tup1 = (4, 2, 3) +id(tup1) + +l2 = l1 +id(l1) == id(l2) +tup2 = tup1 +id(tup1) == id(tup2) + +l1[0] = 1 +l2 +tup1 = (1, 2, 3) +tup2 + +l3 = l1[:] +l3 = l1.copy() +l3 = [x for x in l1] + +l1 = [[1, 2, 3], [4, 5, 6]] +l2 = l1[:] +id(l1) == id(l2) +id(l1[0]) == id(l2[0]) + +from copy import deepcopy +l3 = deepcopy(l1) +id(l1) == id(l3) +id(l1[0]) == id(l3[0]) + +def somme(l): + s = 0 + for x in l: + s += x + return s +def moyenne(l): + s = 0 + for x in l: + s += x + return s / len(l) + +def variance(l): + n = len(l) + s = c = 0 + for x in l: + s += x + c += x * x + return c/n - (s/n) * (s/n) + +def maximum(l): + m = l[0] + for x in l: + if x > m: + m = x + return m +def indice_max(l): + i, m = 0, l[0] + for k in range(1, len(l)): + if l[k] > m: + i, m = k, l[k] + return i + +def maximum(l): + m = l[0] + for x in l: + if x > m: + m = x + return m + +def indice_du_max(l): + i, m = 0, l[0] + for (k, x) in enumerate(l): + if x > m: + i, m = k, x + return i +def cherche(x, l): + k, rep = 0, False + while k < len(l) and not rep: + rep = l[k] == x + k += 1 + return rep +def cherche(x, l): + for y in l: + if y == x: + return True + return False + +(x in l) + +def cherche_dicho(x, l): + i, j = 0, len(l) + while i < j: + k = (i + j) // 2 + if l[k] == x: + return True + elif l[k] > x: + j = k + else: + i = k + 1 + return False diff --git a/Cours/cours4.py b/Cours/cours4.py new file mode 100644 index 0000000..3022068 --- /dev/null +++ b/Cours/cours4.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + + +def base10(x, b=2): + s = 0 + k = len(x) - 1 + for a in x: + s += int(a) * b ** k + k -= 1 + return s + + +def base10Horner(x, b=2): + u = 0 + for a in x: + u = b * u + int(a) + return u + + +def baseb(x, b): + s = "" + y = x + while y > 0: + s = str(y % b) + s + y //= b + return s + + +print(1 + 2**53) +print(1. + 2**53) +print((1. + 2.**53) - 2.**53) +print(1. + (2.**53 - 2.**53)) diff --git a/DM1/main.py b/DM1/main.py new file mode 100644 index 0000000..9fa0e18 --- /dev/null +++ b/DM1/main.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Sat Nov 2 12:27:26 2019 + +@author: suwako +""" + + +def estEgyptienne(lst): + last = lst[0] + for element in lst[1:]: + print(element,last) + if element <= last or last < 2: + return False + last = element + return True + + +def rationnel(lst): + p, q = 0, 1 + for i in range(len(lst)): + q *= lst[i] + reduite = lst[:i]+lst[i+1:] + terme = 1 + for element in reduite: + terme *= element + p += terme + return (p, q) + +def fractionEgyptienne(p, q): + a = p + b = q + lst=[] + while b % a != 0: + print(a, b, lst) + m = b // a + 1 + lst.append(m) + a = a * m - b + b = b * m + print(a, b, lst) + lst.append(b // a) + return lst + + +def estPrefixe(u, v): + if len(v) > len(u): + return False + for i in range(len(v)): + if u[i] != v[i]: + return False + return True + + +def bord(u): + for i in range(1, len(u)): + if estPrefixe(u, u[i:]): + return u[i:] + return "" + + +def Bords(u): + lst = [None] + for k in range(1, len(u) + 1): + lst.append(len(bord(u[:k]))) + return lst + + +def estFacteur(u, v): + for i in range(len(u)-len(v) + 1): + if estPrefixe(u[i:i+len(v)], v): + return True + return False + + +def estFacteurMP(u, v): + bords = Bords(v) + i=0 + while i <= len(u) - len(v): + skip=False + for j in range(len(v)): + print(i, j) + if u[i+j]!=v[j]: + i += bords[j+1] + 1 + skip=True + break + if skip: + continue + return True + return False + \ No newline at end of file diff --git a/MPSI 19-20.zip b/MPSI 19-20.zip new file mode 100644 index 0000000..d67b506 Binary files /dev/null and b/MPSI 19-20.zip differ diff --git a/Pivot/main.py b/Pivot/main.py new file mode 100755 index 0000000..63a0915 --- /dev/null +++ b/Pivot/main.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +import random +import fractions + + +class System(): + + def __str__(self): + return str('\n'.join([', '.join(list(map(str, i))) for i in self.coeffs])) + + def __init__(self, coeffs, quiet=True, text=None, parent=None): + if text: + pass + else: + self.coeffs = [[fractions.Fraction(j) for j in i] for i in coeffs] + self.quiet = quiet + self.parent = parent + self.proper_offset = 0 + + def crop(self): + self.proper_offset += 1 + self.coeffs = [[j for index,j in enumerate(i) if index > 0] for i in self.coeffs] + return self + + def triangularise(self): + # Find a good pivot + if len(self.coeffs) == 1: + return self + pivot = 0 + for i, line in enumerate(self.coeffs): + if not self.coeffs[pivot][0] or line[0] == 0: + pivot = i + continue + if line[0] == 1: + pivot = i + break + if line[0].denominator == 1: + if line[0] < self.coeffs[pivot][0]: + pivot = i + continue + else: + if line[0].denominator < self.coeffs[pivot][0].denominator: + pivot = i + continue + self.swap(0, pivot) + # If we couldn't find a pivot, the first coeff of each line is 0. + # That means the system is not of the defined dimension. + # Let's fix it. + if self.coeffs[0][0] == 0: + self.crop() + return self.triangularise() + + # Cancel the first coefficient of each line + for i in range(1, len(self.coeffs)): + factor = self.coeffs[i][0] / self.coeffs[0][0] + #print() + #print(self) + self.add(i, 0, factor) + #print(self) + #print() + # Triangularise the subsystem + sub = self.subsystem().triangularise() + for i in range(len(sub.coeffs)): + for j in range(len(sub.coeffs[0])): + self.coeffs[i + sub.lineoffset() - self.lineoffset()][j + sub.offset() - self.offset()] = sub.coeffs[i][j] + return self + + def add(self, l1, l2, factor): + sl1,sl2 = [self.lineoffset() + i + 1 for i in [l1,l2]] + print("L%s <- L%s + (%s)*L%s"%(str(sl1), str(sl1), str(factor), str(sl2))) + term = [i*factor for i in self.coeffs[l2]] + res = [self.coeffs[l1][i] - term[i] for i in range(len(self.coeffs[0]))] + self.coeffs[l1] = res + return self + + def swap(self, l1, l2): + self.coeffs[l1], self.coeffs[l2] = self.coeffs[l2], self.coeffs[1] + return self + + def offset(self): + if self.parent: + return self.parent.offset() + self.proper_offset + 1 + else: + return self.proper_offset + + def lineoffset(self): + if self.parent: + return self.parent.lineoffset() + 1 + else: + return 0 + + def subsystem(self): + print(self) + subcoefs = [[j for j in i[1:]] for i in self.coeffs[1:]] + return self.__class__(subcoefs, parent=self) + +k=3 +test = System([[fractions.Fraction(str(random.randint(1,50))+'/'+str(1+0*random.randint(1,10))) for j in range(k+1)] for i in range(k)], quiet=False) +print(test.triangularise()) +"""class Systeme(): + def __str__(self): + return '\n'.join([''.join([((str(self.coeffs[i][j])) + ["x" + str(j+self.offset),"tbcdefghijklmnopqrstuvwxyz"[(j+23+self.offset)%26]][True] + (' + ' if self.coeffs[i][j+1:-1].count(0) == 0 else ' ') if self.coeffs[i][j] else '' ) if j != len(self.coeffs[0]) - 1 else "= " + str(self.coeffs[i][j]) for j in range(len(self.coeffs[0]))]) for i in range(len(self.coeffs))]) + + def __init__(self, coeffs, quiet=True, text=None, parent=None, offset=0): + if text: + self.coeffs=[list(map(fractions.Fraction, map(int, i.split(',')))) for i in text.split(';')] + else: + self.coeffs = [[fractions.Fraction(j) for j in i] for i in coeffs] + self.quiet=quiet + self.parent=parent + self.offset=offset + def pivot(self, new_pivot): + self.quiet or print("L%s <-> L"%(str(self.offset + 1))+ str(new_pivot+1+self.offset)) + self.coeffs[0], self.coeffs[new_pivot] = self.coeffs[new_pivot], self.coeffs[0] + return self + + def cancel(self, line): + if line == 0: + return self + if self.coeffs[0][0] == 0: + return self + line_coeff = self.coeffs[line][0] / self.coeffs[0][0] + self.quiet or print("L"+str(line+1+self.offset) + " <- L" + str(line+1+self.offset) + " - ("+str(line_coeff)+")*L"+str(self.offset+1)) + self.coeffs[line] = [self.coeffs[line][i] - line_coeff * self.coeffs[0][i] for i in range(len(self.coeffs[line]))] + return self + + def solve(self): + self.quiet or print("\nSolving system of dimension : ", len(self.coeffs)) + self.quiet or print(self) + + if len(self.coeffs) == 1: + return self + +#Selecting pivot + pivot = 0 + for i in range(len(self.coeffs)): + if self.coeffs[i][0] != 0 and (self.coeffs[i][0] < self.coeffs[pivot][0] or self.coeffs[pivot][0]==0) : + pivot = i + self.pivot(pivot) + +#Canceling the first coeffs of each equation (except the first one) + self.quiet or print("\n<=>\n") + for i in range(1, len(self.coeffs)): + self.cancel(i) + self.quiet or print(self) + +#Solving the subsystem + for i, line in enumerate(Systeme([[self.coeffs[i][j] for j in range(1, len(self.coeffs[i]))]for i in range(1, len(self.coeffs))], quiet=self.quiet, parent=self, offset=(self.offset+1)).solve().coeffs): + for j in range(len(line)): + self.coeffs[i+1][j+1] = line[j] + self.quiet or print() + return self + + def find(self, this): + if self.coeffs[this][:-1].count(0) < len(self.coeffs[this][:-1]) - 1: + self.cleanline(this) + if self.coeffs[this][:-1].count(0) == len(self.coeffs[this][:-1]) - 1: + if self.coeffs[this][this]==1: + return self.coeffs[this][-1] + else: + self.coeffs[this][-1], self.coeffs[this][this] = self.coeffs[this][-1] / self.coeffs[this][this], 1 + return self.coeffs[this][-1] + raise Exception("Unicity error") + + def cleanline(self, line): + for i in range(len(self.coeffs[line][:-1:])-1, 0-1, -1): + if len(self.coeffs[line][:-1]) - self.coeffs[line][:-1].count(0) <= 1: + return self + if self.coeffs[line][i] !=0: + self.coeffs[line][-1], self.coeffs[line][i]=self.coeffs[line][-1] - self.coeffs[line][i]*self.find(i), 0 + return self + def clean(self): + self.find(0) + return self +""" +""" +print(test) +print() +print(test.solve()) +print() +print(test.clean())""" diff --git a/Pivot/test.txt.gz b/Pivot/test.txt.gz new file mode 100644 index 0000000..2ffbc9f Binary files /dev/null and b/Pivot/test.txt.gz differ diff --git a/TP/TP1 tortue bonus.pdf b/TP/TP1 tortue bonus.pdf new file mode 100755 index 0000000..0ce48db Binary files /dev/null and b/TP/TP1 tortue bonus.pdf differ diff --git a/TP/TP1.py b/TP/TP1.py new file mode 100755 index 0000000..7af3382 --- /dev/null +++ b/TP/TP1.py @@ -0,0 +1,681 @@ +# -*- coding: utf-8 -*- +#!/usr/bin/python3 +""" + + + + TP1 pour découvrir Python + +La plupart des objets seront revus au cours de l'année. +Quel est l'objectif? +Apprivoiser la syntaxe du language python. Je vous propose d'exécuter les commandes suivantes et de faire le maximum d'expérience (en testant des variantes des codes proposés) + +""" +############################ +# Utilisation dans Pyzo # +############################ + +# Vous pouvez utiliser le mode interactif proposé par IEP, il suffit d'écrire le code dans le shell ouvert ci-dessus. Testez en écrivant 2+45 aprés le >>> et appuyer sur entrée. Dans le mode intéractif, les codes ne pourront pas étre conservés .... + +# vous pouvez également utiliser un fichier *.py contenant un code source. Il suffit ensuite de "compiler"/ "interpréter" votre code pour que qu'il s'exécute dans le shell. + +#exemple : (surligner le code é exécuter et cliquer dans l'onglet "Exécuter la selection") + +#################### +# Premiére étape # +#################### + + +2+45 + +# Il ne se passe rien ... + +print(2+45) + +# N'oubliez pas la commande "print" ou faite un copier-coller dans le shell. + + +#################### +# 1-Les entiers # +#################### + + + +print(12*45+5%3) +print(12**5) + +print(7/3) +print(7//3) +print(7//3.) +print(7/3) + +# Quel est le type de l'objet utilisé ? + +print(type (7)) +print(type (7.)) + +# Quelle est la différence entre 'int' et 'float'? + +# Quelques mots sur la fonction id() : identificateur (unique) associé à l'objet. i.e. son adresse en mémoire. + +print(id(True)) +print(id(False)) +print(id(2)) +a=2 +print(id(a)) +b=a +print(id(b)==id(a)) +b=3 +# +a=2 +b=2.0 +print(id(b)==id(a)) + +# tester une égalité : + +print(2==3) +print(2==2) +print(2==2.) # surprenant non !! + + +a=2 +b=2 +print(a is b) +print(a==b) +print(id(a)) + +a=2 +b=2. +print(a is b) +print(a==b) + + +print(21%5) # Le reste de la division euclidienne....un peu de modulo. Trés utilie pour un imposer un critére de divisibilité. + + + +# un pgcd = plus grand divisuer commun. + +import fractions as frc # importer le module "fractions" sous le nom "frc" qui contient +print(dir(frc)) + + +a=13572468 +b=12345678 +print(frc.gcd(a,b)) + +print(gcd(a,b)) + + +from fractions import * # permet d'utiliser la fonction gcd sans le suffixe "frc". +a=13572468 +b=12345678 +print(gcd(a,b)) + +# Quelle est cette fonction "gcd"? il suffit d'ouvrir le document fractions.py pour lire la définition de gcd suivante +def gcd(a, b): + while b: + a, b = b, a%b + return a + +# é relire aprés la petite partie sur les fonctions ... + + +### Attention: pour la culture: + +print(5^2) # D'ou vient ce résultat ? +print(42^17) +# une explication rapide à méditer: l'écriture binaire de 42 est 42=1x32+0x16+1x8+0x4+1x2+0x1 +# En binaire 42= 101010 et 17=10001 +# 42^17=111011 (le ou exclusif)= 1x32+1x16+1x8+0x4+1x2+1x1=59 +# ex : 5^2= 101^10=111=7 + + +#################### +# 2-Les flottants # +#################### + +print(1/3) +print(pi) + +# nous aurons souvent besoin d'aide ... des bibliothéques/ des modules . Pi est défini dans la bibliothéque math. +# on appelle une commande par "math.????" + +import math +print(dir(math)) # elle contient quoi? + +print(math.pi) + +# on peut changer le nom si nécessaire + +import math as m +print(m.pi) + +print(type (m.pi)) + +# Les fonctions usuelles + +print(m.cos(2*m.pi)) +print(m.sqrt(2*m.pi)) + +# quelques calculs avec des flottants : + +print(2/3**6) +print((2/3)**6) +print((1/2**3)*2**3) + +# Comment controler l'affichage ? + +print(-3.445e02) +print(format(-3.445e-5,'.10f')) +print(format(m.pi,'.30f')) + + +################################## +# 3-Variables et affectations # +################################## + + +print(x) +x=5 +print(x) +x:=5 +print(x==4) +print(x=5) +print(x==5) +print(X) # respecter la casse +x='x' +print(x) + +x=1 +x=x+1 +print(x) + +# un test plus évolué: + +x=1 +y=2 +x=(x+y)/2 +y=(x*y) +print(x,y) + +# Est-ce clair? + +c=x,y,z=1,2,3 +print(c) +print(x*y**z) + +# De la syntaxe + +s=1 +s=s+1 +print(s) + +s=2 +s+=4 # Quel est le sens de += ? (essayer -= ou *= ou **=) +print(s) + + + +########################### +# Complément (nombres) # cette partie sera rarement utilisée ... elle est indicative. +########################### + +# Les fractions + +from fractions import * +a=Fraction(24,10) +print(a) # simplification ! +print(a.numerator ) +print(a.denominator) + +a=Fraction.from_float(2.7) +print(a) + + +# Les complexes + +z=complex(4,3) +print(z) + +print(z.real) +print(z.imag) + +i=complex(0,1) +print(i**2) + + +# pour le reste .... consulter dir(complex) + +# Une premiére approche de quelques types... à approfondir et explorer +# (les listes, les Tuplets, ....) + +################################## +# 4-Les listes # +################################## + +a='test' + +print(a) +l=[2,5,2.2, 'test'] + +print(l) +print(l[1]) +print(l[0]) +print(l[10]) +print(len(l)) + +print(l[-1]) +print(l[-5]) + +print(l[0:2]) # les intervalles d'entiers sont ouverts é droite +print(l[-2:2]) +print(l[0:len(l)]) +print(l[-3:4]) +print(l[-4:4]) + +l[2]=15 +print(l) # les listes sont mutables... + +# une liste d'entiers . (Attention les intervalles sont ouverts é droite.) + +I=range(2,9) +print(type(I)) +# range= gamme , plage. + +I=range(2,9,2) +print(list(I)) + + +print(list(I)) +print(3 in I) + +# nous complèterons l'étude des listes dans le TP2 + +################################## +# 5-Les Tuples # +################################## + +t=3,4,5,6,'7' +print(t) + +print(t[0]) +t[0]=1 # Attention .... les Tuples ne sont pas mutables + +a,b,c=1,2,3 +print(a) + +a=range(2,10) +print(a[2]) + + +################################## +# 5-Les chaînes de charactères # +################################## + +a='prof de maths' +b="prof de maths" +print(a==b) # au moins c'est dit !!! +print(a is b ) + +print(len(a)) +print(a[7:13]) +print(a[-1]) + +a[0]='r' # Que dire des chaines? + +a='il fait' +b=' chaud' +print(a+b) + +c='' +c+='alpha' +print(c) + + +################################## +# 5-Les ensembles # +################################## + +s={'je' , 2, 'vous', 34} +print(s) + +print(3 in s) +print(2 in s) + +a='je' in s +b='nous' in s +print(a,b) + + +# les ensembles sont itérables ! + +s={'je' , 2, 'vous', 34} +for x in s: print(x*2) # la syntaxe dans le prochaine TP + + +# Les opérations ensemblistes + +a={1,2,3,4,5,6} +p={2,3,4,6} +i={1,3,5} + +print(p&i)# l'intersection +print(p|i)# l'union +print(a-p) # no comment + + +# Vérification des types et changements de type + +print(type('prof de maths')) # string +t=3,4,5,6,'7' +print(type(t)) # tuple +l=[2,5,2.2, 'test'] +print(type(l)) # list + +l=list(a) +print(l) +t=tuple(a) +print(t) +s=set(l) +print(s) + +print(type(print)) + + +################################## +# -Les dictionnaires # +################################## + + +d={'a':1,'b':2,'c':3} +for i in d : print(i) + +for i in d : print(i, end='') +print() + +print(d['a']) +print(d) +print(d.keys()) +print(d.values()) +print(d.items()) + +l=[(1,'b'),(2,'c'),(3,'g')] +print(dict(l)) + +############################################################# +# 5-Tester avec if / Instruction conditionelle # +############################################################# + +if 2013%2==0: + print('2013 est pair') +else: + print('Sans blague ....') + +if 2013%2 == 1: + print('test 1 ok ') + +if ((2013%2 == 1) and (2013 > 10**3)) or (2013 < 0): + print('test 2 ok ') + +if ((2013%2 == 1) and (2013 > 10**4)) or (2013 < 0): + print('test 2 ok ') + else: + print('test 2 echec ') + +# Attention à la présentation indentée + +if ((2013%2 == 1) and (2013 > 10**4)) or (2013 < 0): + print('test 2 ok ') +else: + print('test 2 echec ') + +# et le elif + +n=11 + +if n%3==0: + print(n,' est congru a 0 modulo 3') +elif n%3==1: + print(n,' est congru a 1 modulo 3') +else: + print(n,' est congru a 2 modulo 3') + + + +################################## +# 6-Les fonctions # +################################## +# il s'agit d'une première approche... +# la syntaxe: +# def lenomdelafonction(variable): + # + #corps de la fonction + # + #return(le résultat) + +def f(x): + return(x+1) + +print(f(1)) +# +def testparite(n): # le nom + res='' + if n%2==0: + res+='est pair' + else: res+='est impair' + return(n,res) + +print(testparite(3) ) + + +def puiss(x,n): + return(x**n) + + +puiss(11,3) + + +def abs(x): + if x>0: + return x + else: + return -x + +print(abs(-2)) + +################################## +# 8-Les polynémes # +################################## +# cette partie sera très utile lors de l'oral de Math/Info du concours Centrales/Supélec mais un peu moins pendant la première année +# nécessite le module "numpy" +from numpy import * +p=poly1d([2,3,4,10]) # donne le polynéme é l'aide des coefficients +print(p) + +p=poly1d([2,3,4,10], True) # donne le polynéme é l'aide des racines +print(p) + +print(p.order) # le degré +print(p.roots) # les racines +print(p.coeffs) # les coefficients + +print(p(5.)) # évaluation en un point + +################################## +# 9-Tracer des courbes # +################################## + +# Pour retrouver les codes ... vister le site http://matplotlib.sourceforge.net/gallery.html + + +import matplotlib.pyplot as plt +import numpy as np + +# une courbe + +x=np.linspace(-5,5,100) # abscisse de -5 à 5 avec 100 points +plt.plot(x,sin(x)) # on utilise la fonction sinus de Numpy +plt.ylabel('fonction sinus') +plt.xlabel("l'axe des abcisses") +plt.show() +#plt.savefig(""D:/Nicolas/Informatique/Python/MPSI/fig1.pdf") # changer le chemin + + +# 2 pour le prix d'une + + +x = np.arange(0, 10, 0.2) +y1 = np.sin(x) +y2 = np.cos(x) +# Créer une figure +fig = plt.figure() +# Un tracé dans la figure +ax = fig.add_subplot(111) +#2 tracés avec le méme axe +l1, l2 = ax.plot(x, y1, 'd', x,y2,'+') +#Légende dans le coin en haut é gauche +fig.legend((l1, l2),('sin','cos'),'upper left') +# L'axe des x est 't' +ax.set_xlabel('t') +# L'axe des y est 't' +ax.set_ylabel('y') +plt.show() +#plt.savefig("D:/Nicolas/Informatique/Python/MPSI/TPfig2.pdf") + +################################## +# Divers # +################################## + + +# controler le temps: + +import time +print(time.asctime()) # Quel est l'origine? + + +print(dir(time)) + +def d(x): + return(format(x,'.10f')) +d(m.pi) + +# Que fait la fonction d? + +t=time.time() +d(time.time()-t) + + +t=time.time() +s=0 +for i in range(10**5): s=0 +print(time.time()-t) +# Tester plusieurs fois la fonction précédente (les 4 lignes ) + + +# Cmment simuler le hasard? + +from random import * + +print(dir(Random)) + +print(randint(1,6)) +print(random()) + + +# un petit jeu é tester : +print('voulez-vous jouer au dés (le temps dattente dun 6)? o/n') +r=input() +if r=='n': + print('a plus ... alors') +else: + d=0 + i=0 + while (d<6): + print('lance le dé') + input() + d=randint(1,6) + i+=1 + if d==6: + print('tu as obtenu un ', d, ' en ', i,' etapes') + else: + print('tu as obtenu un ', d) + + + +# question difficile é méditer (en prévision des proba !) +from random import * +from math import * +p=len([n for n in range(1000000) if hypot(random(),random())<1]) +print(p/1000000*4) # ça ressemble à Pi ... non? un argument pour le justifier. + +help(hypot) + +# installer un module avec pip (compatible pyzo).... (inutile en TP !) +#pip install "le module" + + + +################################## +# Quelques liens # +################################## + +# pour la doc de python : http://docs.python.org/2/ +# pour la doc de pyzo : http://www.pyzo.org +# pour la doc de numpy et scipy : http://docs.scipy.org/doc/ +# pour la doc de matplot lib : http://matplotlib.org +# Le livre http://inforef.be/swi/download/apprendre_python3_5.pdf + + + + +################################## +# Un peu de 3D pour le fun # +################################## + + + +## Un premier jet en 3D + +from mpl_toolkits.mplot3d import Axes3D +import matplotlib.pyplot as plt +import numpy as np + +fig = plt.figure() +ax = fig.add_subplot(111, projection='3d') + +u = np.linspace(0, 2 * np.pi, 100) +v = np.linspace(0, np.pi, 100) + +x = 10 * np.outer(np.cos(u), np.sin(v)) +y = 10 * np.outer(np.sin(u), np.sin(v)) +z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) +ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b') + +plt.show() +plt.savefig("D:/Nicolas/Informatique/Python/MPSI/TP/fig4.pdf") +## un autre exemple + +from mpl_toolkits.mplot3d import axes3d +import matplotlib.pyplot as plt +from matplotlib import cm + +fig = plt.figure() +ax = fig.gca(projection='3d') +X, Y, Z = axes3d.get_test_data(0.05) +ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3) +cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm) +cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm) +cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm) + +ax.set_xlabel('X') +ax.set_xlim(-40, 40) +ax.set_ylabel('Y') +ax.set_ylim(-40, 40) +ax.set_zlabel('Z') +ax.set_zlim(-100, 100) + +plt.show() +plt.savefig("D:/Nicolas/Informatique/Python/MPSI/TP/fig3.pdf") + + diff --git a/TP/TP1Questions.pdf b/TP/TP1Questions.pdf new file mode 100755 index 0000000..e541ebf Binary files /dev/null and b/TP/TP1Questions.pdf differ diff --git a/TP/TP2 etudiants.py b/TP/TP2 etudiants.py new file mode 100755 index 0000000..4a43784 --- /dev/null +++ b/TP/TP2 etudiants.py @@ -0,0 +1,553 @@ + + +################################## +# Premier point sur les variables# +################################## +## comment rajouter 1 à une variable? +i=10 +s=0 +def plus1(i): + s=i+1 + return(s) + +print(i) +print(plus1(i)) +print(s) + +## la variable 's' est (dans le programme précédent) locale + +i=10 +s=0 +def pplus1(i): + global s + s=i+1 + return(s) + +print(i) +print(pplus1(i)) +print(s) + +## vers les effets de bords: +#Définition : une fonction est dite à effet de bord lorsqu'elle modifie un état autre que sa valeur de retour. + +i=10 +def ppplus1(): + i+=1 + return(i) +print(i) +ppplus1() +print(i) +## +def ppplus1(): + global i + i+=1 + return(i) +print(i) +ppplus1() +print(i) +## + +################################## +# Exercices sur les listes # +################################## + + +### la concaténation de 2 listes: +l=[1,2,3] +l1=[4,5,6] + +l2=l+l1 +l3=l1+l + +print(l2) +print(l3) + + +### +# Exercice 1 : (L'aliasing) comprendre la différence entre les deux blocks suivants +##exemple 1: + +a=[11,22,33] # a est affectée. Elle pointe vers une liste donnée +b=a # b point vers la même liste que a +a[0:3]=[17,42,561] # nous changeons le contenu de la liste vers qui pointe a +print(a,b) # b change également +print(id(a)==id(b)) + +##exemple 2: +a=[11,22,33] +b=a +a=[17,42,561]# a point vers une autre liste +print(a,b) +print(id(a)==id(b)) + + +## un autre exemple: + +a=[ i for i in range(10)] +b=a +print(a,b) +a[0]='a' +print(a,b) + + +## ou + +a=[ i for i in range(10)] +b=a +print(a,b) +b[0]='a' +print(a,b) + +## ou + +a=[ i for i in range(10)] +b=a +print(a,b) +a=a+ [i for i in range(1,10)] # a point vers une autre liste +print(a,b) + + + +## Exercice 2: Que valent a et b après les instructions suivantes? +# quelques exemples pour constater "la profondeur d'une liste". Une liste de listes de listes de listes.... +a=[11,22,33] +b=[7,14,a] +print(b) +print(b[2][1]) # le 2eme élément du 3eme élément de b +b[2][1]=17 +print(b) +print(a) +a[0]=19 +print(a,b) + + + + +## Tableau ou matrice : + +a=[0,0] +b=[a,a] +print(b) +b[0][0]=3 +print(b) +## +a=[0,0] +c=[0,0] +b=[a,c] +print(b) +b[0][0]=3 +print(b) +## +n=3 +a=[0]*n +print(a) + + +c=[] +c=[a]*n +print(c) +# Quelle est la taille de la matrice c? +c[0][0]=1 +print(c) # est-ce cohérent? + +## + +n=3 +a=[0] +b=a*n +print(b) +a[0]=1 +print(a,b)# est-ce cohérent? +# l'opérateur * a donc quelques avantages. + + + +## une alternative: + +c=[] +for i in range(n): + c+=[[0]*n] +print(c) +c[0][0]=1 +print(c) + + +## la bonne question: comment faire une copie indépendante d'une liste (à utiliser sans hésitation !).... la copie profonde + +import copy as c + +a=[ i for i in range(10)] +b=c.deepcopy(a) +print(a,b) +a[0]='test' +print(a,b) + +## pourquoi une copie profonde ? tester les lignes suivantes +import copy as c + +a=[0,[1,2,3]] +b=c.copy(a) +print(a,b) +a[0]=1 +print(a,b) +a[1][0]='test' +print(a,b) + + +## Exercice 3 : Que fait la fonction suivante? + +## Une fonction peut changer une liste que l'on appelle + + +a=[ i for i in range(10)] +def f(l,x): + l[0]=1 +print(f(a,1)) # une action est effectuée mais laquelle? +print(a) # il y a eu une action sur a. + +## comment éviter cela? Ne jamais travailler dans le corps d'une fonction sur une variable appelée. + + +a=[ i for i in range(10)] +def f(l,x): + l0=c.deepcopy(l) + l0[0]=1 + return(l0) +print(f(a,1)) # une action est effectuée mais laquelle? +print(a) # il y a eu une action sur a. + +## Que font les fonctions suivantes? + + +def f(l,i,j): + l[i]=l[i]+l[j] + l[j]=l[i]-l[j] + l[i]=l[i]-l[j] + +a=[ i for i in range(10)] +f(a,0,1) +print(a) +## +def g(i,j): + l[i]=l[i]+l[j] + l[j]=l[i]-l[j] + l[i]=l[i]-l[j] + +l=[0,1,2,3] +print(l) +g(0,1) +print(l) +# Attention aux effets de bords ! +# Définition : une fonction est dite à effet de bord lorsqu'elle modifie un état autre que sa valeur de retour. + + +## Exercice 4: Concaténation +# y-a-t-il une différence ? + +a=[2,3,4,6] +print(id(a)) +a=a+[2] +print(id(a)) # en rajoutant 2 ... ce n'est plus la même liste. + +# comment conserver la même liste ? +a=[2,3,4,6] +print(id(a)) +a.append(2) +print(id(a)) + +# nous l'utiliserons dans le TP sur les piles. + + +## Exercice 5: Insertion /Suppression +# Que font les fonctions suivantes? +help(range) +help(list) +# toujours penser à utiliser l'aide ! + +a=list(range(20)) +print(a) +a.insert(2, 18) +print(a) + +a=list(range(20)) +print(a) + +del a[3] +print(a) + +del a[2:4] +print(a) + +a=[1,1,2,2,3,3,4,4,5,5,6,6] +print(a) + +## Attention aux effets de bords ! (vers les piles ) + +a=[1,1,2,2,3,3,4,4,5,5,6,6] +print(a) + +print(a.pop()) +print(a) +for i in range(3): + a.pop() +print(a) + + +print(a.pop(3)) +print(a) + +a.remove(4) +print(a) + + +## tester sur les listes les fonctions: sorted, min, max , sum +a=[] +n=10 +a=[n-i**2 for i in range(n)] +print(a) +print(sorted(a), min(a), max(a), sum(a)) + + + +################################## +# 2 - Itérations # +################################## + +#En Python, un objet est dit itérable lorsqu'il est possible de renvoyer un par un tous ses éléments. la syntaxe: "for x in l", la variable x prend successivement toutes les valeurs des éléments de l. +# Les objets itérables: les listes, les chaînes de caractères, les tuples, les "range", les ensembles, les dictionnaires. + +l=['a','b', 'c'] +s=range(len(l)) +print(s) + +## on peut écrire +for i in s: + print(l[i]) +##On prefère +for lettre in l: + print(lettre) + + +## + +texte="vous avez de la chance!" +for lettre in texte: + print(lettre) + + +##un autre exemple: calcul de la norme de vecteurs de R2 +from math import sqrt # la racine carrée + +vecteurs= [(0,1),(2,2),(2,3)] +for vect in vecteurs: + norme=sqrt(vect[0]^2+vect[1]^2) + print('norme=',norme) + +# Ou sinon +vecteurs= [(0,1),(2,2),(2,3)] +for (x,y) in vecteurs: + norme=sqrt(x^2+y^2) + print('norme=',norme) + + + +# LES EXERCICES A TRAITER. + +#################################################################### +# Exercice 1: Ecrire un fonction "mini" qui renvoie le plus petit élément d'un liste. +#La tester sur une liste de couples, une chaîne de caractères. +#################################################################### + +#################################################################### +# Exercice 2: Ecrire une fonction "bis" qui prend une chaîne de caractères et renvoie une chaîne avec chaque caractère 2 fois de suite +#################################################################### + + +# Itérations avancées: Tester les blocks suivants (reverse , enumerate, zip,...) + +l=[1,2,'a','b',4,'test'] +l1=reversed(l) +print(l,l1) +l1=list(l1) +print(l,l1) + + + +#################################################################### +# Exercice 3: Ecrire une fonction qui à une liste renvoie la liste renversée (sans utiliser "reversed") +#################################################################### + +# Enumerate : enumerate(l) est un itérateur paresseux qui renvoie les couples i, l[i](pour i variant de 0 à len(l)-1) + +s='un test facile' +for c in enumerate(s): + print(c) + +for (i,x) in enumerate(s): + print(x) + +for (i,x) in enumerate(s): + print(x,end='') +print() + +#################################################################### +# Exercice 4: Ecrire une fonction minind(l) qui renvoie le couple contenant le minimum de l et la liste des indices associées. +#################################################################### + + +# l'itérateur zip + +lettre=['a','b','c'] +nbr=[1,2,3,4,5] + +for x in zip(lettre, nbr): + print(x) + +#################################################################### +# Exercice 5: +#Ecrire une fonction moycoef(notes, coefs) qui prend une liste de notes et une liste de coefficients et renvoie la moyenne pondérée. +#################################################################### + + + +################################## +# Boucle While # +################################## + +## premiers pas .... + +i=0 +while (i<10): + i+=1 + print(i) +## +i=1 +u=1 +while (u>10**(-5)): + i+=1 + u/=10 +print(i,u) +## le compteur i +i=0 +u=1. +while (u>10**(-5)): + i+=1 + u/=2. + +print(u,i) +print(i) +from math import * +print(floor((5*log(10)/log(2)))+1 ) + +##Pourquoi la valeur finale de i est-elle égale à la partie entière +1 de 5*log_2(10) ? + +## un jeu de dé: + +from random import * + +print(dir(Random)) + +print(randint(1,6)) +print(random()) + + +## un petit jeu +print('voulez-vous jouer au dés (le temps dattente dun 6)? o/n') +r=input() +if r=='n': + print('a plus ... alors') +else: + d=0 + i=0 + while (d<6): + print('lance le dé') + input() + d=randint(1,6) + i+=1 + if d==6: + print('tu as obtenu un ', d, ' en ', i,' étapes') + else: + print('tu as obtenu un ', d) + + + +################################## +# 3 - Compréhension # +################################## +## Python permet de définir facilement des listes par «compréhension» + +l=[3*i**2 + 1 for i in range(1,10)] +print(l) + +l=[(i,j) for i in range(4) for j in range(i)] +print(l) + +l=[[(i,j) for i in range(2)] for j in range(i)] +print(l) + +l=[[(i,j) for j in range(i)] for i in range(2)] +print(l) + + +## On peut également filtrer + +l=[i for i in range(10) if i%2] +print(l) + +l=[i if i%3 else 0 for i in range(10)] +print(l) + +# Comment comprendre %2 ? +#il faut comprendre "if i%3" comme "if i%3 == 0". +#En Python, toutes les valeurs sont comprises comme vrai sauf +#• la constante False +#• la constante None +#•0 +#• la liste vide [] +#• le tuple vide () +#• l’ensemble vide set() +#• le dictionnaire vide {} + +#################################################################### +# Exercice 6: + # -Ecrire une fonction imp(n) qui renvoie la liste des nombres impairs inférieur à n + # -Calculer la somme des i**2 pour i inférieur à 100 + # -Déterminer la somme des i**j pour i, j vérifiant 0") + reset() + +def exercice1(l): #J'ai mis un chiffre dans le nom de la variable pour me repérer + #Fonction carré + forward(l) + left(90) + forward(l) + left(90) + forward(l) + left(90) + forward(l) + left(90) + +def exercice2(): + exercice1(20) + left(90) + exercice1(40) + left(90) + exercice1(60) + left(90) + exercice1(70) + +def exercice3(): + speed('fastest') + for length in range(20, 200 ,20): + exercice1(length) + +def exercice4(): + speed('fastest') + for i in range(1,501): + forward(i) + left(91) +def exercice5(): + def polygone(n, l): + for i in range(1,n+1): + forward(l) + left(360/n) + for i in range(3,7+1): + polygone(i,30) +def exercice6(): + circle(70) + circle(70,360*2, 5) + +def exercice7(): + speed('fastest') + for i in range(72): + circle(70,180) + setpos(0,0) + left(5) + +#FRACTALES + +def exercice9(): + left(180) + speed('fastest') + def sierpinski(n, l): + if n==1: + begin_fill() + for _ in range(3): + left(60) + forward(l) + left(60) + #circle(math.sqrt(((l)**2)/(2-2*math.cos(math.pi*30/180))),360,3) + end_fill() + else: + sierpinski(n-1, l/2) + left(60) + forward(l) + left(60) + sierpinski(n-1, l/2) + left(60) + forward(l) + left(60) + sierpinski(n-1, l/2) + left(60) + forward(l) + left(60) + sierpinski(5,300) + +def exercice10(): + left(90) + speed('fastest') + def bin_tree(n, h): + pensize(n) + forward(h/3) + if n!=1 : + left(30) + bin_tree(n-1, 2*h/3) + right(60) + bin_tree(n-1, 2*h/3) + left(30) + left(180) + forward(h/3) + left(180) + bin_tree(4,300) +def exercice11(): + Alice = Turtle() + Bob = Turtle() + Alice.penup() + Bob.penup() + Bob.setpos(-60,-10) + Alice.setpos(0,40) + Alice.pendown() + Bob.pendown() + def tick(): + Bob.forward(1.0) + Alice.setheading(Alice.towards(*Bob.position())) + Alice.forward(1.2) + while Alice.distance(*Bob.position()) > 2: + tick() + time.sleep(0.001) + + +"""exercice1(40) +pause() +exercice2() +pause() +exercice3() +pause() +exercice4() +pause() +exercice5() +pause() +exercice6() +pause() +exercice7() +pause() +exercice9() +pause() +exercice10() +pause() +exercice11() +pause()""" diff --git a/TP2_bonus/TP2 instructions itératives et boucles conditionnelles bonus.pdf b/TP2_bonus/TP2 instructions itératives et boucles conditionnelles bonus.pdf new file mode 100755 index 0000000..ee2c709 Binary files /dev/null and b/TP2_bonus/TP2 instructions itératives et boucles conditionnelles bonus.pdf differ diff --git a/TP2_bonus/main.py b/TP2_bonus/main.py new file mode 100644 index 0000000..d572373 --- /dev/null +++ b/TP2_bonus/main.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +def entiers(i,j): # Exercice 1 + print('-'.join(map(str,list(range(i,j+1))))) +def entiers(i,j): # Exercice 2 + retour="" + for i in range(i,j+1): + if i%7: + retour+=(str(i)+'-') + print(retour.rstrip('-')) +entiers(5,9) + +def triangle1(n): + for i in range(n): + print('*'*(i+1)) +triangle1(5) +print() +def triangle2(n): + for i in range(n): + print('*'*(n-i-1)) +triangle2(5) +def pyramide1(n): + triangle1(n) + triangle2(n) +pyramide1(5) +print() +def pyramide2(n): + for i in range(n): + print(' '*(n-i)+' '.join('*'*(i+1))+' '*(n-i)) +pyramide2(5) + +def talkhys1(n): + for j,i in enumerate([int('1'*i) for i in range(1,n+1)]): + print(' '*(n-j)+str(i)+ ' x ' + str(i) + ' '*(n-j) + ' = ' + ' '*(n-j)+ str(i*i)) +talkhys1(10) + +def heure_to_sec(h,m,s): + return h*3600+m*60+s +def sec_to_heure(s): + return s//3600,(s%3600)//60, s%60 +print(sec_to_heure(67)) + +def duree(*args): + return sec_to_heure(heure_to_sec(*args[3:]) - heure_to_sec(*args[:3])) +print(duree(5,3,20,10,3,39)) + +def rot13(entree): + texte=entree.lower() + alph="abcdefghijklmnopqrstuvwxyz" + return ''.join([alph[(alph.index(c)+13)%(len(alph))] if c in alph else c for c in texte]) +print(rot13("har crefbaar abeznyr crafr dh'ha xvyb-bpgrg rfg étny à 1000 bpgrgf,ha vasbeznvgpvra rfg pbainvaph dh'ha xvybzèger rfg étny à 1024 zègerf.")) + +def isqrt(n): + p=n + while not(p*p <= n < (p+1)**2 or p<0): + p=p-1 + return p +print(isqrt(65)) + +def isqrt2(n): + p=n + lr=0 + while True: + p=p-1 + i=0 + r=0 + while i n: + break + return False + +def goldbach(n): + premiers=npremiers(n) + for i in range(4, n+1, 2): + if not validegoldbach(i, premiers): + return False, i + return True +def valideconjecture(n, premiers, puissances): + for k in puissances: + for l in premiers: + if k+l==n: + return True + if k+ l > n: + break + if k > n: + break + return False + +def conjecture(n): + premiers=npremiers(n) + puissances=[2**i for i in range(n)] + for i in range(3, n+1, 2): + if not valideconjecture(i, premiers, puissances): + return False, i + return True +print(goldbach(100)) +print(conjecture(100)) + +def lookandsay(integer): + text = str(integer) + i = 0 + res="" + while i < len(text): + c=1 + j=0 + while j < len(text[i+1:]): + if text[i+1:][j] == text[i]: + c+=1 + else: + break + j+=1 + res += str(c)+text[i] + i += j + 1 + return int(res) +def conway(n, start=1): + un=start + for i in range(n-1): + un=lookandsay(un) + return un +v = 20 # 40 +print(len(str(conway(v+1)))/len(str(conway(v)))) + +def shadok(n): + p_max=0 + while 4**(p_max) < n: + p_max +=1 + reste=n + print(p_max) + b4_re=[0]*(p_max) + for i in list(range(p_max))[::-1]: + for j in range(3, -1, -1): + if reste - j*(4**i) >= 0: + reste -= j*(4**i) + b4_re[i]=j + break + b4=reversed(b4_re) + + dico=["ga", "bu", "zo", "meu"] + return '-'.join([dico[i] for i in b4]) +def kodahs(texte): + dico=["ga", "bu", "zo", "meu"] + b4=[dico.index(t) for t in texte.split('-')] + return sum([i*(4**p) for p, i in enumerate(reversed(b4))]) \ No newline at end of file diff --git a/TP2_bonus_MandelBrot/Bigpicture.png b/TP2_bonus_MandelBrot/Bigpicture.png new file mode 100644 index 0000000..3cbbae2 Binary files /dev/null and b/TP2_bonus_MandelBrot/Bigpicture.png differ diff --git a/TP2_bonus_MandelBrot/TP-BONUSMandelbrotFeigenbaum.pdf b/TP2_bonus_MandelBrot/TP-BONUSMandelbrotFeigenbaum.pdf new file mode 100644 index 0000000..0601fac Binary files /dev/null and b/TP2_bonus_MandelBrot/TP-BONUSMandelbrotFeigenbaum.pdf differ diff --git a/TP2_bonus_MandelBrot/main.py b/TP2_bonus_MandelBrot/main.py new file mode 100755 index 0000000..b877fc1 --- /dev/null +++ b/TP2_bonus_MandelBrot/main.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Fri Oct 11 08:36:47 2019 + +@author: suwako +""" +#from functools import lru_cache +import gc +import matplotlib.pyplot as plt +import matplotlib.image as mpimg +import numpy as np +from PIL import Image +from tqdm import tqdm +from threading import Thread +from multiprocessing import Pool, Process +"""n=20 +liste = [[[1,1,255] for j in range(n)] for i in range(n)] +fig = np.array(liste) +plt.imshow(fig) +plt.show()""" +#@lru_cache(maxsize=512) +def xn(n, c): + if n==0: + return 0 + else: + return xn(n-1, c)**2 + c + +def feigenbaum(n=1000): + l=[] + for c in tqdm(np.linspace(-2, 0, num=n), ncols=100): + for k in range(200, 301): + l.append([c, xn(k, c)]) + ordo = [p[1] for p in l] + absci = [p[0] for p in l] + plt.plot(absci, ordo, 'ro', ms=100/n) + plt.show() +def zn(n, c): + if n==0: + return 0 + else: + return zn(n-1, c)**2 + c + +def mandelbrot(n=512, lim=100, color=(1,5,2)): + mat=[] + + for y in tqdm(np.linspace(-2, 2, num=n), ncols=100): + l=[] + for x in np.linspace(-2,2, num=n): + """for k in range(lim): + a=zn(k, complex(x,y)) + if abs(a) > 2: + break""" + k = zn2(complex(x,y), lim) +# l.append([((k*color[0])%255),(k*color[1]*5)%255,(k*color[2]*2)%255]) + l.append([x,y]) + mat.append(l) + fig = np.array(mat) + img = Image.fromarray(fig.astype(np.uint8), 'RGB') + img.save('test.png') + img.show() + +def mandeld(n=512, lim=100, color=(1,5,2), threads=5, window=[(-2,2),(-2,2)], filename="test.png"): + args=(n, lim, color) + tasks=np.array_split(np.linspace(*window[0], num=n), threads) + results=[[] for i in range(threads)] + """ threads=[mandelThread(tasks[i], args, i) for i in range(threads)] + for thread in threads: + thread.start() + for thread in threads: + thread.join()""" + p = Pool(threads) + results=p.map(mandelWorker, [(tasks[i], args, i, window) for i in range(threads)]) + + mat = [j for i in results for j in i] +# mat = results[0] + fig = np.array(mat) + img = Image.fromarray(fig.astype(np.uint8), 'RGB') + img.save(filename) + del tasks + del results + del mat + del p + del fig + del img +import time +def Time(func, *args, **kwargs): + start_time = time.clock() + res = func(*args, **kwargs) + print(time.clock() - start_time, "secondes") + return res +def mandelWorker(data): + taches, args, thread, window = data + #print("Thread", thread, "running.") + def zn2(c, lim): + z=0 + k=0 + while k= 2*1e-5: + un = 1/2*(un + 2/un) + i+=1 + return i +#4 +def uq(n, q): + if n==0: + return 1 + pre=u(n-1) + return 1/q*(pre + q/pre) \ No newline at end of file diff --git a/mpsi.py b/mpsi.py new file mode 100755 index 0000000..d9e3e24 --- /dev/null +++ b/mpsi.py @@ -0,0 +1,4 @@ +#!/usr/bin/env python +import random +print(random.randint(1,6)) +print(dir(random)) diff --git a/randomm.py b/randomm.py new file mode 100644 index 0000000..b1381bc --- /dev/null +++ b/randomm.py @@ -0,0 +1,14 @@ +#from random import * +#import os +#os.chdir("../") +from random import * +def import_non_local(name, custom_name=None): + import imp, sys + + custom_name = custom_name or name + + f, pathname, desc = imp.find_module(name, sys.path[1:]) + module = imp.load_module(custom_name, f, pathname, desc) + f.close() + + return module