Python Basics

In [1]:
1 + 2 * 3 
Out[1]:
7
In [2]:
2**3
Out[2]:
8
In [3]:
x = "Machine" + "Learning"
print(x)
MachineLearning
In [4]:
x.upper()
Out[4]:
'MACHINELEARNING'
In [5]:
x.lower()
Out[5]:
'machinelearning'
In [6]:
len(x)
Out[6]:
15
In [7]:
a = 2 + 3
b = a * 4
c = b - 7
L = [a,b,c]
print(L)
[5, 20, 13]
In [8]:
M = [10, 2, "a", 3.5]
N = L + M
print(N)
[5, 20, 13, 10, 2, 'a', 3.5]
In [34]:
len(N)
Out[34]:
7
In [9]:
N[2]
Out[9]:
13
In [10]:
N[:3]
Out[10]:
[5, 20, 13]
In [11]:
N[3:]
Out[11]:
[10, 2, 'a', 3.5]
In [12]:
N[3:6]
Out[12]:
[10, 2, 'a']

Python Dictionaries

In [20]:
# This is what a comment looks like 
# Dictionaries contain name-value pairs

studentIds = {'knuth': 42.0, 'turing': 56.0, 'nash': 92.0 }
studentIds['turing']
Out[20]:
56.0
In [21]:
studentIds['ada'] = 97.0
studentIds
Out[21]:
{'ada': 97.0, 'knuth': 42.0, 'nash': 92.0, 'turing': 56.0}
In [22]:
del studentIds['knuth']
studentIds
Out[22]:
{'ada': 97.0, 'nash': 92.0, 'turing': 56.0}
In [23]:
studentIds['knuth'] = [42.0,'forty-two']
studentIds
Out[23]:
{'ada': 97.0, 'knuth': [42.0, 'forty-two'], 'nash': 92.0, 'turing': 56.0}
In [32]:
studentIds.keys()
Out[32]:
dict_keys(['turing', 'nash', 'ada', 'knuth'])
In [35]:
list(studentIds)
Out[35]:
['turing', 'nash', 'ada', 'knuth']
In [36]:
list(studentIds.values())
Out[36]:
[56.0, 92.0, 97.0, [42.0, 'forty-two']]
In [38]:
list(studentIds.items())
Out[38]:
[('turing', 56.0),
 ('nash', 92.0),
 ('ada', 97.0),
 ('knuth', [42.0, 'forty-two'])]
In [ ]:
list(studentIds)
In [30]:
len(studentIds) 
Out[30]:
4
In [13]:
fruits = ['apples','oranges','pears','bananas']
for fruit in fruits:
    print (fruit + ' for sale')
apples for sale
oranges for sale
pears for sale
bananas for sale
In [18]:
# Accessing dict element
fruitPrices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75}

for fruit, price in fruitPrices.items():
    if price < 2.00:
        print ('%s cost %f a pound' % (fruit, price))
    else:
        print (fruit + ' are too expensive!')
pears cost 1.750000 a pound
oranges cost 1.500000 a pound
apples are too expensive!
In [15]:
# Example of python's list comprehension construction:

nums = [1,2,3,4,5,6]
plusOneNums = [x+1 for x in nums]
print("plusOneNums =", plusOneNums)

oddNums = [x for x in nums if x % 2 == 1]
print("oddNums = ", oddNums) 

oddNumsPlusOne = [x+1 for x in nums if x % 2 ==1]
print("oddNumsPlusOn = ", oddNumsPlusOne)
plusOneNums = [2, 3, 4, 5, 6, 7]
oddNums =  [1, 3, 5]
oddNumsPlusOn =  [2, 4, 6]

Numpy

In [39]:
import numpy as np
In [40]:
# Creating a 1-d array

A = np.array([1,2,3,4,5])
A
Out[40]:
array([1, 2, 3, 4, 5])
In [41]:
# Creating a 1-d array from an existing Python list

L = [1, 2, 3, 4, 5, 6]

A = np.array(L)
A
Out[41]:
array([1, 2, 3, 4, 5, 6])
In [42]:
A / 5
Out[42]:
array([0.2, 0.4, 0.6, 0.8, 1. , 1.2])
In [43]:
np.array([1.0,2,3,4,5]) / 5
Out[43]:
array([0.2, 0.4, 0.6, 0.8, 1. ])
In [44]:
M = np.array([2, 3, 4, 5, 6, 7])

P = L * M
P
Out[44]:
array([ 2,  6, 12, 20, 30, 42])
In [45]:
P.sum()
Out[45]:
112
In [46]:
P.mean()
Out[46]:
18.666666666666668
In [47]:
# Dot product of two vectors

np.dot(L, M)
Out[47]:
112
In [80]:
# Creating a 2-d array

A = np.array([[1,2,3],[4,5,6],[7,8,9],[8,7,6]])
A
Out[80]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9],
       [8, 7, 6]])
In [49]:
A.shape
Out[49]:
(4, 3)
In [53]:
A[0,1]
Out[53]:
2
In [54]:
A[2,1]
Out[54]:
8
In [55]:
A[:,1]
Out[55]:
array([2, 5, 8, 7])
In [56]:
A[0,:]
Out[56]:
array([1, 2, 3])
In [57]:
A[1:,1:]
Out[57]:
array([[5, 6],
       [8, 9],
       [7, 6]])
In [68]:
A[1:3,1:]
Out[68]:
array([[5, 6],
       [8, 9]])
In [66]:
A[1:,0:2]
Out[66]:
array([[4, 5],
       [7, 8],
       [8, 7]])
In [81]:
A[-1,:]
Out[81]:
array([8, 7, 6])
In [70]:
# Transpose a 2-d array
print(A)
print()
print(A.T)
[[1 2 3]
 [4 5 6]
 [7 8 9]
 [8 7 6]]

[[1 4 7 8]
 [2 5 8 7]
 [3 6 9 6]]
In [82]:
C = np.array([1,10,20])

print("A: \n", A)
print()
print("C: \n", C)
print()

print("A * C: \n", A * C)
print()
print("A dot C: \n", np.dot(A,C))
A: 
 [[1 2 3]
 [4 5 6]
 [7 8 9]
 [8 7 6]]

C: 
 [ 1 10 20]

A * C: 
 [[  1  20  60]
 [  4  50 120]
 [  7  80 180]
 [  8  70 120]]

A dot C: 
 [ 81 174 267 198]
In [83]:
A = np.mat(A)
C = np.mat(C)

print(A * C)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-83-bc847f7489f1> in <module>()
      2 C = np.mat(C)
      3 
----> 4 print(A * C)

C:\Anaconda\envs\py35\lib\site-packages\numpy\matrixlib\defmatrix.py in __mul__(self, other)
    307         if isinstance(other, (N.ndarray, list, tuple)) :
    308             # This promotes 1-D vectors to row vectors
--> 309             return N.dot(self, asmatrix(other))
    310         if isscalar(other) or not hasattr(other, '__rmul__') :
    311             return N.dot(self, other)

ValueError: shapes (4,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
In [85]:
print("C Transpose: \n", C.T)
print()
print("A * C: \n",A * C.T)
C Transpose: 
 [[ 1]
 [10]
 [20]]

A * C: 
 [[ 81]
 [174]
 [267]
 [198]]
In [71]:
# Using arrays to index into other arrays (e.g., Boolean masks)

A = np.array([1, 2, 3, 4, 5, 6])

A > 3
Out[71]:
array([False, False, False,  True,  True,  True])
In [72]:
A[A > 3]
Out[72]:
array([4, 5, 6])
In [73]:
sum(A[A > 3])
Out[73]:
15
In [75]:
Ind = (A > 1) & (A < 6)
print(Ind)
A[Ind]
[False  True  True  True  True False]
Out[75]:
array([2, 3, 4, 5])
In [ ]: