2017-12-05 13:54:44 +00:00
|
|
|
import matplotlib.pyplot as plt
|
|
|
|
import numpy as np
|
|
|
|
import random as rd
|
|
|
|
|
|
|
|
## Question 1
|
|
|
|
def genere(regles, L0, n):
|
|
|
|
L = L0
|
|
|
|
for i in range(n):
|
|
|
|
new_res = ""
|
|
|
|
for j in L:
|
|
|
|
new_res += regles.get(j, j)
|
|
|
|
L = new_res
|
|
|
|
return L
|
|
|
|
|
|
|
|
## Question 2
|
|
|
|
class Tortue:
|
|
|
|
def __init__(self, angle, i=1):
|
|
|
|
""" Initialise la tortue en (0,0) avec un angle de `angle`."""
|
|
|
|
plt.figure(i)
|
|
|
|
plt.axis('equal')
|
|
|
|
self.angle = angle
|
|
|
|
self.pos = (0,0)
|
|
|
|
|
|
|
|
self.stack = []
|
|
|
|
|
|
|
|
def avance(self, r):
|
|
|
|
""" Avance la torue de `r` unités. """
|
|
|
|
x,y = self.pos
|
|
|
|
self.pos = (
|
|
|
|
x + r*np.cos(self.angle),
|
|
|
|
y + r*np.sin(self.angle)
|
|
|
|
)
|
|
|
|
plt.plot([x, self.pos[0]], [y, self.pos[1]], 'r')
|
|
|
|
|
|
|
|
def tourne(self, a):
|
|
|
|
""" Tourne la tortue d'un angle a. """
|
|
|
|
self.angle += a
|
|
|
|
|
|
|
|
def push(self):
|
|
|
|
""" Mémorise l'état courrant. """
|
|
|
|
self.stack.append((self.pos, self.angle))
|
|
|
|
|
|
|
|
def pop(self):
|
|
|
|
""" Retourne au précédent état mémorisé. """
|
|
|
|
self.pos, self.angle = self.stack.pop(-1)
|
|
|
|
|
2017-12-05 22:23:31 +00:00
|
|
|
def saut(self, r):
|
|
|
|
x,y = self.pos
|
|
|
|
self.pos = (
|
|
|
|
x + r*np.cos(self.angle),
|
|
|
|
y + r*np.sin(self.angle)
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2017-12-05 13:54:44 +00:00
|
|
|
def trace(self, s, alpha):
|
|
|
|
""" Trace la chaîne de caractères s. """
|
|
|
|
plt.autoscale()
|
|
|
|
for c in s:
|
|
|
|
if c == '+':
|
|
|
|
self.tourne(alpha)
|
|
|
|
elif c == '-':
|
|
|
|
self.tourne(-alpha)
|
|
|
|
elif c == '[':
|
|
|
|
self.push()
|
|
|
|
elif c == ']':
|
|
|
|
self.pop()
|
2017-12-05 22:23:31 +00:00
|
|
|
elif c.islower():
|
|
|
|
self.saut(1)
|
2017-12-05 13:54:44 +00:00
|
|
|
else:
|
|
|
|
self.avance(1)
|
|
|
|
|
|
|
|
|
|
|
|
## Question 5
|
|
|
|
def genere2(regles, L0, n):
|
|
|
|
L = L0
|
|
|
|
for i in range(n):
|
|
|
|
new_res = ""
|
|
|
|
for j in L:
|
|
|
|
regle = regles.get(j, [j])
|
|
|
|
new_res += regle[rd.randint(0,len(regle)-1)]
|
|
|
|
L = new_res
|
|
|
|
return L
|
|
|
|
|
|
|
|
## Question 5
|
|
|
|
def genere3(regles, L0, n):
|
|
|
|
L = L0
|
|
|
|
for i in range(n):
|
|
|
|
new_res = ""
|
|
|
|
for j in L:
|
|
|
|
regle = regles.get(j, [(1,j)])
|
|
|
|
poids_total = sum(map(lambda x:x[0], regle))
|
2017-12-05 22:04:42 +00:00
|
|
|
tirage = rd.uniform(0,poids_total)
|
2017-12-05 13:54:44 +00:00
|
|
|
k = 0
|
|
|
|
while tirage > 0:
|
|
|
|
tirage -= regle[k][0]
|
|
|
|
k += 1
|
|
|
|
new_res += regle[k-1][1]
|
|
|
|
L = new_res
|
|
|
|
return L
|