Answer the following questions in Python. Do all calculations in Python. Answer each problem twice: once using a for loop with lists and once using numpy arrays (no for loops). There are two answer prompts. The first is for Python and the second is numpy. It may be useful to know that you can turn a python list into a numpy array like so:

x = [1,4,6]
x_array = np.array(x)

Add up the numbers from 1 to 100


In [1]:
sum = 0
for i in range(1,101):
    sum += i
print(sum)


5050

In [2]:
import numpy as np
a = np.arange(1,101)
print(np.sum(a))


5050

Print the first 5 powers of 3. Start at $3^1$


In [3]:
for i in range(1,6):
    print(3**i)


3
9
27
81
243

In [4]:
import numpy as np
a = np.arange(1,6)
print(3**a)


[  3   9  27  81 243]

Find the largest value of the function $(x - 3)^2$, where x is only the values: [0,1,2,5,6,7]


In [5]:
x = [0,1,2,5,6,7]
fx = []
for xi in x:
    fx.append( (xi - 3)**2)
print(max(fx))


16

In [6]:
x = [0,1,2,5,6,7]
fx = np.array(x)
np.max( (fx - 3)**2)


Out[6]:
16

x and Px are two arrays which correspond to the sample space and the probability of an element in the sample space, respectively. Write code that finds the most likely element in the sample space. Demonstrate your code using the following lists, but your code should work on any size lists:

x = [1, 2, 3, 4, 5, 6]
Px = [1/21, 2/21, 3/21, 4/21, 5/21, 6/21]

In [8]:
x = [1, 2, 3, 4, 5, 6]
Px = [1/21, 2/21, 3/21, 4/21, 5/21, 6/21]
max_v = 0
max_x = None

for i in range(len(x)):
    if(Px[i] > max_v):
        max_v = Px[i]
        max_x = x[i]
print(max_x)


6

In [9]:
x = np.array([1, 2, 3, 4, 5, 6])
Px = np.array([1/21, 2/21, 3/21, 4/21, 5/21, 6/21])

i = np.argmax(Px)
print(x[i])


6

Continuing the question above, calculate the expected value of x and Px.


In [10]:
x = [1, 2, 3, 4, 5, 6]
Px = [1/21, 2/21, 3/21, 4/21, 5/21, 6/21]
ex = 0

for i in range(len(x)):
    ex += Px[i] * x[i]
print(ex)


4.333333333333333

In [12]:
x = np.array([1, 2, 3, 4, 5, 6])
Px = np.array([1/21, 2/21, 3/21, 4/21, 5/21, 6/21])

xPx = x * Px
print(np.sum(xPx))


4.33333333333