Week 1 - Getting Started


In [3]:
import numpy as np

print("Numpy:", np.__version__)


Numpy: 1.10.4

Python Summary

Further information

More information is usually available with the help function. Using ? brings up the same information in ipython.

Using the dir function lists all the options available from a variable.

help(np)

np?

dir(np)

Variables

A variable is simply a name for something. One of the simplest tasks is printing the value of a variable.

Printing can be customized using the format method on strings.


In [13]:
location = 'Bethesda'
zip_code = 20892
elevation = 71.9

print("We're in", location, "zip code", zip_code, ", ", elevation, "m above sea level")
print("We're in " + location + " zip code " + str(zip_code) + ", " + str(elevation) + "m above sea level")
print("We're in {0} zip code {1}, {2}m above sea level".format(location, zip_code, elevation))
print("We're in {0} zip code {1}, {2:.2e}m above sea level".format(location, zip_code, elevation))


We're in Bethesda zip code 20892 ,  71.9 m above sea level
We're in Bethesda zip code 20892, 71.9m above sea level
We're in Bethesda zip code 20892, 71.9m above sea level
We're in Bethesda zip code 20892, 7.19e+01m above sea level

Types

A number of different types are available as part of the standard library. The following links to the documentation provide a summary.

Other types are available from other packages and can be created to support special situations.

A variety of different methods are available depending on the type.


In [1]:
# Sequences

# Lists
l = [1,2,3,4,4]
print("List:", l, len(l), 1 in l)

# Tuples
t = (1,2,3,4,4)
print("Tuple:", t, len(t), 1 in t)

# Sets
s = set([1,2,3,4,4])
print("Set:", s, len(s), 1 in s)

# Dictionaries
# Dictionaries map hashable values to arbitrary objects
d = {'a': 1, 'b': 2, 3: 's', 2.5: 't'}
print("Dictionary:", d, len(d), 'a' in d)


List: [1, 2, 3, 4, 4] 5 True
Tuple: (1, 2, 3, 4, 4) 5 True
Set: {1, 2, 3, 4} 4 True
Dictionary: {'a': 1, 3: 's', 2.5: 't', 'b': 2} 4 True

In [2]:
import random

if random.random() < 0.5:
    print("Should be printed 50% of the time")
elif random.random() < 0.5:
    print("Should be primted 25% of the time")
else:
    print("Should be printed 25% of the time")


Should be printed 50% of the time

In [3]:
for i in ['a', 'b', 'c', 'd']:
    print(i)
else:
    print('Else')
    
for i in ['a', 'b', 'c', 'd']:
    if i == 'b':
        continue
    elif i == 'd':
        break
    print(i)
else:
    print('Else')


a
b
c
d
Else
a
c

In [4]:
def is_even(n):
    return not n % 2

print(is_even(1), is_even(2))


False True

In [5]:
def first_n_squared_numbers(n=5):
    return [i**2 for i in range(1,n+1)]

print(first_n_squared_numbers())


[1, 4, 9, 16, 25]

In [6]:
def next_fibonacci(status=[]):
    if len(status) < 2:
        status.append(1)
        return 1
    status.append(status[-2] + status[-1])
    return status[-1]

print(next_fibonacci(), next_fibonacci(), next_fibonacci(), next_fibonacci(), next_fibonacci(), next_fibonacci())


1 1 2 3 5 8

In [7]:
def accepts_anything(*args, **kwargs):
    for a in args:
        print(a)
    for k in kwargs:
        print(k, kwargs[k])
        
accepts_anything(1,2,3,4, a=1, b=2, c=3)


1
2
3
4
c 3
a 1
b 2

In [8]:
# For quick and simple functions a lambda expression can be a useful approach. 
# Standard functions are always a valid alternative and often make code clearer.
f = lambda x: x**2
print(f(5))

people = [{'name': 'Alice', 'age': 30}, 
          {'name': 'Bob', 'age': 35}, 
          {'name': 'Charlie', 'age': 35}, 
          {'name': 'Dennis', 'age': 25}]
print(people)
people.sort(key=lambda x: x['age'])
print(people)


25
[{'age': 30, 'name': 'Alice'}, {'age': 35, 'name': 'Bob'}, {'age': 35, 'name': 'Charlie'}, {'age': 25, 'name': 'Dennis'}]
[{'age': 25, 'name': 'Dennis'}, {'age': 30, 'name': 'Alice'}, {'age': 35, 'name': 'Bob'}, {'age': 35, 'name': 'Charlie'}]

In [56]:
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
print(a)
print(a[1:,1:])
a = a + 2
print(a)
a = a + np.array([1,2,3])
print(a)
a = a + np.array([[10],[20],[30]])
print(a)


[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[5 6]
 [8 9]]
[[ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
[[ 4  6  8]
 [ 7  9 11]
 [10 12 14]]
[[14 16 18]
 [27 29 31]
 [40 42 44]]

In [59]:
print(a.mean(), a.mean(axis=0), a.mean(axis=1))


29.0 [ 27.  29.  31.] [ 16.  29.  42.]

In [65]:
import matplotlib.pyplot as plt

%matplotlib inline

In [68]:
x = np.linspace(0, 3*2*np.pi, 500)

plt.plot(x, np.sin(x))
plt.show()


Exercises


In [63]:
a = "The quick brown fox jumps over the lazy dog"
b = 1234567890.0
  • Print the variable a in all uppercase
  • Print the variable a with every other letter in uppercase
  • Print the variable a in reverse, i.e. god yzal ...
  • Print the variable a with the words reversed, i.e. ehT kciuq ...
  • Print the variable b in scientific notation with 4 decimal places

In [ ]:


In [64]:
people = [{'name': 'Bob', 'age': 35}, 
          {'name': 'Alice', 'age': 30}, 
          {'name': 'Eve', 'age': 20},
          {'name': 'Gail', 'age': 30},
          {'name': 'Dennis', 'age': 25},
          {'name': 'Charlie', 'age': 35}, 
          {'name': 'Fred', 'age': 25},]
  • Print the items in people as comma seperated values
  • Sort people so that they are ordered by age, and print
  • Sort people so that they are ordered by age first, and then their names, i.e. Bob and Charlie should be next to each other due to their ages with Bob first due to his name.

In [ ]:

  • Write a function that returns the first n prime numbers
  • Given a list of coordinates calculate the distance using the (Euclidean distance)[https://en.wikipedia.org/wiki/Euclidean_distance]
  • Given a list of coordinates arrange them in such a way that the distance traveled is minimized (the itertools module may be useful).

In [ ]:
coords = [(0,0), (10,5), (10,10), (5,10), (3,3), (3,7), (12,3), (10,11)]
  • Print the standard deviation of each row in a numpy array
  • Print only the values greater than 90 in a numpy array
  • From a numpy array display the values in each row in a seperate plot (the subplots method may be useful)

In [75]:
np.random.seed(0)
a = np.random.randint(0, 100, size=(10,20))

In [ ]: