Solutions

Exercise 2

  1. What range(20) returns
In [4]:
print(range(20))
range(0, 20)
  1. what n returns in a for n in range(20) loop
In [5]:
for n in range(20):
    print(n)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Exercise 3

In [6]:
fibonacci = np.zeros(20)
for n in range(20):
    if n < 2:
        fibonacci[n] = 1
    else:
        fibonacci[n] = fibonacci[n-2] + fibonacci[n-1]
print(fibonacci)
[1.000e+00 1.000e+00 2.000e+00 3.000e+00 5.000e+00 8.000e+00 1.300e+01
 2.100e+01 3.400e+01 5.500e+01 8.900e+01 1.440e+02 2.330e+02 3.770e+02
 6.100e+02 9.870e+02 1.597e+03 2.584e+03 4.181e+03 6.765e+03]

Exercise 4

The first step is to print the output to a file. We've already got our fibonacci array, but we also want to print the n values. We need to create another array for that to send to np.savetxt with the output. We also need with some extra arguements for the delimeter and the heading.

To get the n values we use np.arange(1,21,1) This gives us a numpy array with the values 1 to 20 in steps of 1.

In [9]:
n = np.arange(1,21,1)
np.savetxt('fibonacci_20.txt', list(zip(n, fibonacci)), fmt="%10d", header='{:>10}, {:>10}'.format('n', 'Fibonacci'), delimiter=',')

Now we should read the file back in to check that it's printed as we expect. Remember to tell loadtxt to unpack the data into the variables. This time we're also specifying dtype='int' so that it reads our variables in as integers.

In [10]:
n2, fib = np.loadtxt('fibonacci_20.txt', unpack=True, dtype='int', delimiter=',')

Finally print the variables n2 and fib along with their shapes to check that everything worked as expected

In [11]:
print(n2, n2.shape)
print(fib, fib.shape)
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20] (20,)
[   1    1    2    3    5    8   13   21   34   55   89  144  233  377
  610  987 1597 2584 4181 6765] (20,)