In [1]:
# packages, modules, imports, namespaces
import numpy as np
from scipy.misc import factorial
# function definition with default arguments
def poisson_pmf(k, mu=1):
"""Poisson PMF for value k with rate mu."""
return mu**k*np.exp(-mu)/factorial(k)
In [2]:
# Jupyter notebook "magic" function
# Sets up "inline" plotting
%matplotlib inline
# Importing the seaborn plotting library and setting defaults
import seaborn as sns
sns.set_context("notebook", font_scale=1.5)
# Variable assignment
n = np.arange(10) # [0, 1, 2, ..., 0]
# Note that poisson_pmf is vectorized
sns.barplot(n, poisson_pmf(n, 2))
# pass is a do-nothing statement -
# Used here to suppress printing of return value for sns.barplot()
pass
In [3]:
print("Hello, world!")
In [4]:
# Boolean
True, False
Out[4]:
In [5]:
# Integer
0, 1, 23, int(3.8)
Out[5]:
In [6]:
# Float
1.2, 3.14, float(2)
Out[6]:
In [7]:
# Complex
1 + 2j, complex(23)
Out[7]:
In [8]:
# String
('abc', "abc",
"""abc
def
ghi""",
r'\t')
Out[8]:
In [9]:
# None
None
In [10]:
type(3)
Out[10]:
In [11]:
type(poisson_pmf)
Out[11]:
In [12]:
2 * 3
Out[12]:
In [13]:
2 ** 3
Out[13]:
In [14]:
2 ^ 3 # danger, Will Robinson! ^ is bitwise exclusive-or, not exponentiation
Out[14]:
In [15]:
7 /3
Out[15]:
In [16]:
7 // 3
Out[16]:
In [17]:
2 < 3
Out[17]:
In [18]:
7 % 3
Out[18]:
In [19]:
1 == 1
Out[19]:
In [20]:
1 != 2
Out[20]:
In [21]:
a = [1,2,3]
b = a
c = [1,2,3]
In [22]:
b == a
Out[22]:
In [23]:
b is a
Out[23]:
In [24]:
c == a
Out[24]:
In [25]:
c is a
Out[25]:
In [26]:
np.array([1,2,3]) @ np.array([1,2,3])
Out[26]:
In [27]:
True or False, True | False
Out[27]:
In [28]:
True and False, False & True
Out[28]:
In [29]:
2 << 4
Out[29]:
In [30]:
fruits = ['apple', 'banana', 'cherry', 'durian', 'eggplant', 'fig']
'durian' in fruits
Out[30]:
In [31]:
import operator as op
op.mul(3, 4)
Out[31]:
In [32]:
from functools import reduce
reduce(op.mul, [2,3,4,5], 1)
Out[32]:
In [33]:
# Create some object (the list [1,2,3]) on the RHS and assign it to the name on the LHS
In [34]:
a = [1,2,3]
In [35]:
a
Out[35]:
In [36]:
# Find the identity (address in memory in CPython) of the object named a
In [37]:
id(a)
Out[37]:
In [38]:
# Give the object named as a another name b
In [39]:
b = a
In [40]:
b
Out[40]:
In [41]:
# b is just another name for the object also named a
# So the identity is the same
id(b)
Out[41]:
In [42]:
# Create a new object (the list [1,23]) and give it a name c
In [43]:
c = [1,2,3]
In [44]:
c
Out[44]:
In [45]:
# The object named c has a different identity from the object with names a, b
id(c)
Out[45]:
In [46]:
a
Out[46]:
In [47]:
b[0] = 99
In [48]:
a
Out[48]:
In [49]:
c
Out[49]:
In [50]:
x = 1
In [51]:
x += 2
x
Out[51]:
In [52]:
x **= 3
x
Out[52]:
In [53]:
course = ('STA-663', 2017, 'Spring', 50)
In [54]:
course[0]
Out[54]:
In [55]:
course[1]
Out[55]:
In [56]:
course[-1]
Out[56]:
In [57]:
name, year, semester, size = course
In [58]:
semester
Out[58]:
In [59]:
name, *when, size = course
In [60]:
name
Out[60]:
In [61]:
size
Out[61]:
In [62]:
when
Out[62]:
In [63]:
import collections
In [64]:
course = collections.namedtuple('course', ['name', 'year','semester', 'size'])
In [65]:
sta_663 = course(name = 'STA-663', year=2017, size=50, semester='Spring')
In [66]:
sta_663
Out[66]:
In [67]:
name, *when, size = sta_663
In [68]:
when
Out[68]:
In [69]:
sta_663[-1]
Out[69]:
In [70]:
sta_663.size
Out[70]:
In [71]:
x = [1,2,3,4,5]
In [72]:
x[1:4]
Out[72]:
In [73]:
x[-1] = 10
x
Out[73]:
In [74]:
x[::2]
Out[74]:
In [75]:
x[::-1]
Out[75]:
In [76]:
x + x
Out[76]:
In [77]:
x * 3
Out[77]:
In [78]:
x.append(20)
x
Out[78]:
In [79]:
x.extend([3,4,5])
x
Out[79]:
In [80]:
x.index(10)
Out[80]:
In [81]:
x.count(3)
Out[81]:
In [82]:
s = {1,1,2,3,4}
s
Out[82]:
In [83]:
s.add(2)
s
Out[83]:
In [84]:
s.add(5)
s
Out[84]:
In [85]:
s & {5,6,7}, s.intersection({5,6,7})
Out[85]:
In [86]:
s | {5,6,7}, s.union({5,6,7})
Out[86]:
In [87]:
s - {5,6,7}, s.difference({5,6,7})
Out[87]:
In [88]:
s ^ {5,6,7}, s.symmetric_difference({5,6,7})
Out[88]:
In [89]:
d = {'a': 1, 'b':2, 'c':3}
d
Out[89]:
In [90]:
d['b']
Out[90]:
In [91]:
d1 = dict(d=4, e=5, f=6)
d1
Out[91]:
In [92]:
d.update(d1)
d
Out[92]:
In [93]:
list(d.keys())
Out[93]:
In [94]:
list(d.values())
Out[94]:
In [95]:
d['g'] = 7
d
Out[95]:
In [96]:
for k in d:
print(k, d[k])
In [97]:
# From Python 3.6 regular dictionaries will maintain order
d = {}
d['z'] = 1
d['x'] = 2
d['y'] = 3
for k in d:
print(k, d[k])
In [98]:
d = collections.OrderedDict()
d['z'] = 1
d['x'] = 2
d['y'] = 3
for k in d:
print(k, d[k])
In [99]:
d = collections.defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].extend([3,4,5])
d
Out[99]:
In [100]:
jabberwocky = '''
’Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
“Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!”
He took his vorpal sword in hand;
Long time the manxome foe he sought—
So rested he by the Tumtum tree
And stood awhile in thought.
And, as in uffish thought he stood,
The Jabberwock, with eyes of flame,
Came whiffling through the tulgey wood,
And burbled as it came!
One, two! One, two! And through and through
The vorpal blade went snicker-snack!
He left it dead, and with its head
He went galumphing back.
“And hast thou slain the Jabberwock?
Come to my arms, my beamish boy!
O frabjous day! Callooh! Callay!”
He chortled in his joy.
’Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
'''
In [101]:
c1 = {}
for word in jabberwocky.split():
c1[word] = c1.get(word, 0) + 1
c1['vorpal']
Out[101]:
In [102]:
int() # Note int is a factory fucntion that produces 0
Out[102]:
In [103]:
c2 = collections.defaultdict(int)
for word in jabberwocky.split():
c2[word] += 1
c2['vorpal']
Out[103]:
In [104]:
c3 = collections.Counter(jabberwocky.split())
c3['vorpal']
Out[104]:
In [105]:
x, y = 3,4
if (x > y):
print(x, '>', y)
elif (x == y):
print(x, 'equals', y)
else:
print('Either', x, '<', y, 'or x and y are not orderable')
In [106]:
for fruit in fruits:
print(fruit)
In [107]:
i = 0
while (i < 5):
print(i)
i += 1
In [108]:
for i in range(3):
for j in range(5):
if i==j:
continue
print(i, j)
In [109]:
i = 0
while True:
print(i)
if i > 5:
break
i += 1
In [110]:
([x for x in dir(__builtin__) if x.islower() and not x.startswith('__')])
Out[110]:
In [111]:
len('hello')
Out[111]:
In [112]:
range(5, 10, 2)
Out[112]:
In [113]:
ord('c') - ord('a')
Out[113]:
In [114]:
chr(ord('a') + 2)
Out[114]:
In [115]:
list(zip('abcd', range(1,10)))
Out[115]:
In [116]:
sum([4,5,6])
Out[116]:
In [117]:
sorted(fruits)
Out[117]:
In [118]:
sorted(fruits, reverse=True)
Out[118]:
In [119]:
sorted(fruits, key=len)
Out[119]:
In [120]:
def f(a, b, c):
return a + b * c
In [121]:
f(1,2,3)
Out[121]:
In [122]:
f(c=3, a=1, b=2)
Out[122]:
In [123]:
f(1,2,c=3)
Out[123]:
In [124]:
args = [1,2,3]
f(*args)
Out[124]:
In [125]:
kwargs = dict(a=1, b=2, c=3)
f(**kwargs)
Out[125]: