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 [21]:
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]]
[1 2 3]
[[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 [3]:
a = "The quick brown fox jumps over the lazy dog"
b = 1234567890.0

## Print the variable `a` in all uppercase
print(a.upper())

## Print the variable `a` with every other letter in uppercase
def capEveryOtherLetter(str):
    ans = "" 
    i = True  # capitalize
    for char in str:
        if i == True:
            ans += char.upper() 
        else:
            ans += char.lower()
        if char != ' ':  # if character is not a space
            i = not i  # toggle i between False/True
    return ans

print(capEveryOtherLetter(a))

## Print the variable `a` in reverse, i.e. god yzal ...
def reverse(str):
    rev = ""
    for char in str:
        rev = char + rev
    return rev
    
print(reverse(a))

## Print the variable `a` with the words reversed, i.e. ehT kciuq ...
def reverseWords(str):
    words = str.split()
    for i in range(len(words)):
        words[i] = reverse(words[i])
    rev = " ".join(words)
    return rev

print(reverseWords(a))

## Print the variable `b` in scientific notation with 4 decimal places
## In python, you have floats and decimals that can be rounded. 
## If you care about the accuracy of rounding, use decimal type. 
## If you use floats, you will have issues with accuracy.
## Why does ans output E+09 and ans2 E+9? 
from decimal import Decimal
ans = '%.4E' % Decimal(b)
ans2 = "{:.4E}".format(Decimal(b))
print(ans, ans2)


THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
ThE qUiCk BrOwN fOx JuMpS oVeR tHe LaZy DoG
god yzal eht revo spmuj xof nworb kciuq ehT
ehT kciuq nworb xof spmuj revo eht yzal god
1.2346E+09 1.2346E+9
  • 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 [1]:
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-separated values.
## uses map with str conversion function, as join() expects str, not dict
peopleCommaSeparated = ",".join(map(str, people))
print(peopleCommaSeparated)

## Sort people so that they are ordered by age, and print.
## sort() only works with lists, whereas sorted() accepts any iterable
peopleSortedByAge = sorted(people, key = lambda person: person['age'])
print(peopleSortedByAge)

## 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.
peopleSortedByAgeAndName = sorted(people, key = lambda person: (person['age'], person['name']))
print(peopleSortedByAgeAndName)


{'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}
[{'name': 'Eve', 'age': 20}, {'name': 'Dennis', 'age': 25}, {'name': 'Fred', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Gail', 'age': 30}, {'name': 'Bob', 'age': 35}, {'name': 'Charlie', 'age': 35}]
[{'name': 'Eve', 'age': 20}, {'name': 'Dennis', 'age': 25}, {'name': 'Fred', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Gail', 'age': 30}, {'name': 'Bob', 'age': 35}, {'name': 'Charlie', 'age': 35}]
  • 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 [27]:
import numpy as np
np.random.seed(0)
a = np.random.randint(0, 100, size=(10,20))
print(a, "\n")

## Print the standard deviation (σ) of each row in a numpy array
## in a 2D array, columns are axis = 0, and rows are axis = 1
row_std = np.std(a, axis=1)
print(row_std, "\n")

## Print only the values greater than 90 in a numpy array
truncated = a[a > 90]
print(truncated, "\n")

## From a numpy array, display the values in each row in a separate plot 
## (the subplots method) may be useful
import matplotlib.pyplot as plt

plt.plot(a[0])
plt.subplot(211)
plt.show()


[[44 47 64 67 67  9 83 21 36 87 70 88 88 12 58 65 39 87 46 88]
 [81 37 25 77 72  9 20 80 69 79 47 64 82 99 88 49 29 19 19 14]
 [39 32 65  9 57 32 31 74 23 35 75 55 28 34  0  0 36 53  5 38]
 [17 79  4 42 58 31  1 65 41 57 35 11 46 82 91  0 14 99 53 12]
 [42 84 75 68  6 68 47  3 76 52 78 15 20 99 58 23 79 13 85 48]
 [49 69 41 35 64 95 69 94  0 50 36 34 48 93  3 98 42 77 21 73]
 [ 0 10 43 58 23 59  2 98 62 35 94 67 82 46 99 20 81 50 27 14]
 [41 58 65 36 10 86 43 11  2 51 80 32 54  0 38 19 46 42 56 60]
 [77 30 24  2  3 94 98 13 40 72 19 95 72 26 66 52 67 61 14 96]
 [ 4 67 11 86 77 75 56 16 24 29 21 25 80 60 61 83 33 32 70 85]] 

[ 25.08804496  28.47011591  21.7795202   30.07972739  28.97667165
  28.50697283  31.07008207  23.401923    32.10681392  27.20087315] 

[99 91 99 99 95 94 93 98 98 94 99 94 98 95 96] 


In [ ]: