Question 6 - note the order of tests is important.
def fizzbang(n):
if n % 3 == 0:
print("fizz")
elif n % 5 == 0:
print("bang")
elif n % 3 == 0 and n % 5 == 0:
print("fizz bang")
fizzbang(15)
Question 2 - note that (5/9) is a float, so the result is also a float.
temp = 41
print((temp - 32)*(5/9))
These have the form:
[expression for item in sequence]
[i**2 for i in range(1, 11)]
A condition can also be added to select which items become part of the list. The syntax is:
[expression for item in sequence if condition]
[i**2 for i in range(1, 11) if i % 2 == 0]
Loops can also be nested inside list comprehensions.
[(x, y) for x in range(3) for y in range(2)]
A more complicated example to generate primitive Pythagorean triples.
import math
ppts = [(a, b) for a in range(1, 50) for b in range(1, 50) if math.gcd(a, b) == 1 and math.sqrt(a**2 + b**2).is_integer()]
[item[0] for item in ppts]
mylist = list("abcdefg")
mylist
Items in a list can be selected (indexed) using square brackets and an integer for the index.
Note that the first item has index 0.
mylist[1]
mylist[0]
It is an error to index past the end of a list.
mylist[7]
Lists can also be indexed backwards from the end, using a negative index.
mylist[-1]
mylist[-2]
The "=" assignment operator can be used to change the value of an element at a given index.
mylist[0] = 'z'
mylist
mylist = list("abcdefg")
mylist
mylist[0] = 'z'
mylist
mylist[0] = 'a'
mylist
$<$list$>$[start:stop] selects the elements from start up to (but not including) stop.
mylist[1:4]
Slicing from the start up to (not inclusing) some element.
mylist[:3]
Slicing from some element up to the end of the list.
mylist[3:]
Slicing can also be given a step size.
mylist[0:7:2]
Slicing every second element.
mylist[::2]
mylist[1::2]
Slicing creates a copy of a list, so modifying the slice doesn't modify the original list.
newlist = mylist[::2]
newlist
newlist[0] = 'z'
newlist
mylist
The usual alias to use for NumPy is 'np'.
import numpy as np
Create a NumPy array from a list.
a = np.array([1, 2, 3])
print(a)
a
Adding a scalar to an array adds it to every element of the array.
a + 3
Multiplying an array by a scalar multiplies every element by that scalar.
a *= 3
print(a)
Raising an array to a power will raise every element to that power.
a**2
a = np.array([1, 2, 3])
a
Imported NumPy functions will operate on every element of an array
np.exp(a)
Functions called on multiple arrays be will be called on the corresponding elements of each array.
b = np.array([4, 5, 6])
c = a + b
print(c)
The "magic" %%timeit times how long the code takes to run in a cell.
n = 10000000
Summing the integers up to ten million the slow way with a Python loop.
%%timeit
total = 0
for i in range(n):
total += i
print(total)
Doing it the fast way with NumPy functions - nearly 20 times faster.
%%timeit
print(np.sum(np.arange(n)))
ones generates an array of all 1's.
np.ones(10)
linspace(start, end) generates a uniform array of points in the interval [start, end] (including the endpoints).
x = np.linspace(0, 1)
x
linspace(start, end, n) generates a uniform array of n points.
x = np.linspace(0, 1, 11)
x
linspace makes plotting functions very easy.
%matplotlib inline
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 201)
y = np.sin(x)
plt.plot(x, y)
legend lets us label multiple plots on the same graph.
plt.figure(figsize=(10,4))
plt.plot(x, np.sin(x), label='Sin x')
plt.plot(x, np.cos(x), label='Cos x')
plt.legend()
xlim(xmin, xmax) and ylim(ymin, ymax) provide manual control over the range of values displayed.
plt.figure(figsize=(10,4))
plt.plot(x, np.sin(x), label='Sin x')
plt.plot(x, np.cos(x), label='Cos x')
plt.xlim(0, 20)
plt.legend()
$\frac{13}{22}$
$\frac{13}{22}$
- Item 1
- Item 2
$\displaystyle\sum_1^{100}$
$\displaystyle\sum_1^{100}$
$\sum_1^{100}$
<\code>
$\sum_1^{100}$
$\begin{bmatrix}
1 & 2 \\
3 & 4
\end{bmatrix}$
$\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}$
$\begin{pmatrix}
1 & 2 \\
3 & 4
\end{pmatrix}$
$\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}$
Consider the function $g(x) = \frac{\log(1 + x)}{x}$
end = 1
x = np.linspace(-end, end)
y = np.where(x==0, 1.0, np.log(1+x)/x)
plt.plot(x, y)
end = 1e-4
x = np.linspace(-end, end)
y = np.where(x==0, 1.0, np.log(1+x)/x)
plt.plot(x, y)
As x gets close to zero, g(x) shows unexpected oscillations.
end = 1e-7
x = np.linspace(-end, end)
y = np.where(x==0, 1.0, np.log(1+x)/x)
plt.plot(x, y)
end = 1e-7
x = np.linspace(-end, end, 1001)
y = np.where(x==0, 1.0, np.log(1+x)/x)
plt.plot(x, y)
For x close to machine epsilon, the oscillations can be seen clearly.
plt.figure(figsize=(10, 6))
end = 1e-15
x = np.linspace(-end, end, 1001)
y = np.where(x==0, 1.0, np.log(1+x)/x)
plt.plot(x, y)