%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('bmh')
from math import pi, sin, cos
DEGREES_TO_RADIANS = pi / 180
def turtle_to_coords(turtle_program, turn_amount=45):
# 거북이가 (0,0)으로 시작하고 위쪽을 향해있다.
state = (0.0, 0.0, 90.0)
# 거북이가 가는 경로
yield (0.0, 0.0)
for command in turtle_program:
x, y, angle = state
if command in 'Ff': # 거북이를 앞으로 움직인다
state = (x - cos(angle * DEGREES_TO_RADIANS),
y + sin(angle * DEGREES_TO_RADIANS),
angle)
if command == 'f':
yield (float('nan'), float('nan'))
yield (state[0], state[1])
elif command == '+': # 움직이지 않고 거북이를 시계방향으로 돌린다
state = (x, y, angle + turn_amount)
elif command == '-': # 움직이지 않고, 거북이를 반시계 방향으로 돌린다
state = (x, y, angle - turn_amount)
def plot_coords(coords, bare_plot=False):
if bare_plot:
# Turns off the axis markers.
plt.axis('off')
# Ensures equal aspect ratio.
plt.axes().set_aspect('equal', 'datalim')
# Converts a list of coordinates into
# lists of X and Y values, respectively.
X, Y = zip(*coords)
# Draws the plot.
plt.plot(X, Y);
def transform_sequence(sequence, transformations):
return ''.join(transformations.get(c, c) for c in sequence)
transform_sequence('acab', {'a': 'aba', 'c': 'bb'})