Python

(Notes to myself about Python 3)

Read/write to files: docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

List/dict/set comprehensions

list_comp = [expr for val in collection if condition]
dict_comp = {key-expr : value-expr for value in collection if condition}
set_comp = {expr for value in collection if condition}

Plotting

# Draw an ellipse using parametric equations
# Source: https://stackoverflow.com/a/48409811/752784
import numpy
from matplotlib import pyplot
from math import pi
x_0 = 1.0
y_0 = 0.5
a = 2.0    # semimajor axis
b = 1.5    # semiminor axis
t = numpy.linspace(0, 2 * pi, 100)
pyplot.plot(x_0 + a * numpy.cos(t), y_0 + b * numpy.sin(t))
pyplot.show()

# Draw a random path

import numpy
import matplotlib.pyplot as pyplot

# Add random number of points
import random
n = random.randint(5,10)
points = numpy.zeros((n,2))

for i in range(n):
    # Add random points
    a = random.randint(1,10)
    b = random.randint(1,10)
    points[i,:] = [a, b]

# Complete the loop: repeat first point as last point
# Appending to numpy arrays: https://stackoverflow.com/a/42545300/752784
points = numpy.append(points, [points[0,:]], axis=0)

pyplot.plot(points[:,0], points[:,1])
pyplot.show()