In [33]:
import numpy as np
print("Numpy:", np.__version__)
help(np)
np?
dir(np)
In [4]:
dir(np)
Out[4]:
In [5]:
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))
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)
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")
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')
In [4]:
def is_even(n):
return not n % 2
print(is_even(1), is_even(2))
In [5]:
def first_n_squared_numbers(n=5):
return [i**2 for i in range(1,n+1)]
print(first_n_squared_numbers())
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())
In [6]:
def accepts_anything(*args, **kwargs):
for a in args:
print(a)
print(type(args))
for k in kwargs:
print(k, kwargs[k])
accepts_anything(1,2,3,4, a=1, b=2, c=3)
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)
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)
In [59]:
print(a.mean(), a.mean(axis=0), a.mean(axis=1))
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()
In [35]:
a = "The quick brown fox jumps over the lazy dog"
b = 1234567890.0
a
in all uppercasea
with every other letter in uppercasea
in reverse, i.e. god yzal ...a
with the words reversed, i.e. ehT kciuq ...b
in scientific notation with 4 decimal places
In [42]:
print(a.upper())
upper = True
soln = ''
for i in a:
if upper == True:
soln += i.upper()
else:
soln += i
if i != ' ':
upper = not upper
print(soln)
def reverse_string(s):
al = list(s)
al.reverse()
return ''.join(al)
print(reverse_string(a))
words = a.split(' ')
print(' '.join([reverse_string(i) for i in words]))
print('{0:.4e}'.format(b))
In [53]:
people = [{'name': 'Charlie', 'age': 35},
{'name': 'Alice', 'age': 30},
{'name': 'Eve', 'age': 20},
{'name': 'Gail', 'age': 30},
{'name': 'Dennis', 'age': 25},
{'name': 'Bob', 'age': 35},
{'name': 'Fred', 'age': 25},]
people
as comma seperated valuespeople
so that they are ordered by age, and printpeople
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 [55]:
for i in people:
print('{0},{1}'.format(i['name'], i['age']))
for i in people:
print('{0:<10},{1}'.format(i['name'], i['age']))
In [57]:
def key_age(x):
return x['age']
people.sort(key=key_age)
print(people)
people.sort(key=lambda x: x['name'])
people.sort(key=key_age)
print(people)
In [59]:
coords = [(0,0), (10,5), (10,10), (5,10), (3,3), (3,7), (12,3), (10,11)]
In [58]:
def first_n_primes(n):
primes = []
i = 2
while len(primes) < n:
for p in primes:
if i % p == 0:
break
else:
primes.append(i)
i += 1
return primes
print(first_n_primes(5))
In [66]:
def distance(coords):
distance = 0
for p1, p2 in zip(coords[:-1], coords[1:]):
distance += ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5
return distance
print(distance(coords))
assert distance([(0,0), (10,0)]) == 10
assert distance([(0,0), (-10, 0)]) == 10
assert distance([(0,0), (3,4)]) == 5
In [67]:
import itertools
all_options = []
for option in itertools.permutations(coords, len(coords)):
all_options.append((option, distance(option)))
all_options.sort(key=lambda x: x[1])
print(all_options[0])
In [68]:
np.random.seed(0)
a = np.random.randint(0, 100, size=(10,20))
In [72]:
print(a.std())
print(a)
print(a.std(axis=1))
print(a[a>90])
In [73]:
import matplotlib.pyplot as plt
%matplotlib inline
fig, axes = plt.subplots(5, 2, figsize=(16,12))
for i, ax in zip(range(a.shape[0]), axes.flatten()):
ax.plot(a[i])
plt.show()
In [ ]: