In this exercise, you will convert badly written code, provided here, into better-written code.
You will do this not through simply writing better code, but by taking a refactoring approach, as discussed in the lectures.
As such, your use of git
version control, to make a commit after each step of the refactoring, with a commit message which indicates the refactoring you took, will be critical to success.
You will also be asked to look at the performance of your code, and to make changes which improve the speed of the code.
The script as supplied has its parameters hand-coded within the code. You will be expected, in your refactoring, to make these available as command line parameters to be supplied when the code is invoked.
Here's our terrible code:
%matplotlib inline
from math import sin, cos
from matplotlib import pyplot as plt
s = 1
d = [[0, 1, 0]]
plt.plot([0, 0], [0, 1])
for i in range(5):
n = []
for j in range(len(d)):
n.append(
[
d[j][0] + s * sin(d[j][2] - 0.2),
d[j][1] + s * cos(d[j][2] - 0.2),
d[j][2] - 0.2,
]
)
n.append(
[
d[j][0] + s * sin(d[j][2] + 0.2),
d[j][1] + s * cos(d[j][2] + 0.2),
d[j][2] + 0.2,
]
)
plt.plot([d[j][0], n[-2][0]], [d[j][1], n[-2][1]])
plt.plot([d[j][0], n[-1][0]], [d[j][1], n[-1][1]])
d = n
s *= 0.6
plt.savefig("tree.png")
If you want to self-assess your solution you can consider using the marking scheme below.
perf_plot.py
, invoking a function imported from tree.py
. The script should produce a figure called perf_plot.png
. Comment on your findings in a text file, called comments.md
. For your performance measurements you should turn off the actual plotting, and run only the mathematical calculation using an appropriate flag. 5 marks:append()
which is not appropriate for NumPy
. Create a new solution (in a file called tree_np.py
) which makes use of NumPy
. Compare the performance (again, excluding the plotting from your measurements), and discuss in comments.md. 5 marks:hstack
or similar to create new arrays with twice the length, by composing the left-turned array with the right-turned array. (1 mark)