In [3]:
import numpy as np
print("Numpy:", np.__version__)
help(np)
np?
dir(np)
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))
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 [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)
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 [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)
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 [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)
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 [ ]:
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)
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 [ ]:
In [ ]:
coords = [(0,0), (10,5), (10,10), (5,10), (3,3), (3,7), (12,3), (10,11)]
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()
In [ ]: