Python Review
Python Review
Python Review
CS224N - 1/19/18
def someGreatFunction(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return someGreatFunction(left) + middle + someGreatFunction(right)
print(someGreatFunction([3,6,8,10,1,2,1]))
def QuickSort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return QuickSort(left) + middle + QuickSort(right)
print(someGreatFunction([3,6,8,10,1,2,1]))
x + y
x - y
x ** y
x / y
x / float(y)
str(x) + “ + “ + str(y)
Common Operations
x = 10 # Declaring two integer variables
y = 3 # Comments start with the hash symbol
x + y >> 13 # Addition
x - y >> 7 # Subtraction
x ** y >> 1000 # Exponentiation
x / y >> 3 # Dividing two integers
x / float(y) >> 3.333.. # Type casting for float division
str(x)+ “ + “ + str(y)
>> “10 + 3” # Casting and string concatenation
Built-in Values
True, False # Usual true/false values
None # Represents the absence of something
# A valid object -- can be used like one
def func():
return None # Functions can return None
def fib(n):
# Indent level 1: function body
if n <= 1:
# Indent level 2: if statement body
return 1
else:
# Indent level 2: else statement body
return fib(n-1)+fib(n-2)
Language Basics
Python is a strongly-typed and dynamically-typed language.
Execution: Python is first interpreted into bytecode (.pyc) and then compiled by a
VM implementation into machine instructions. (Most commonly using C.)
[1] https://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language
Language Basics
Python is a strongly-typed and dynamically-typed language.
Execution: Python is first interpreted into bytecode (.pyc) and then compiled by a
VM implementation into machine instructions. (Most commonly using C.)
[1] https://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language
Language Basics
Python is a strongly-typed and dynamically-typed language.
Execution: Python is “slower”, but it can run highly optimized C/C++ subroutines
which make scientific computing (e.g. matrix multiplication) really fast.
[1] https://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language
Language Basics
Python is a strongly-typed and dynamically-typed language.
[1] https://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language
Collections: List
Lists are mutable arrays (think std::vector)
numbers = [0, 1, 2, 3, 4, 5, 6]
numbers[0:3] == numbers[:3] == [0, 1, 2]
numbers[5:] == numbers[5:7] == [5, 6]
numbers[:] == numbers = [0, 1, 2, 3, 4, 5, 6]
while True:
print ‘We’re stuck in a loop...’
break # Break out of the while loop
>> We’re stuck in a loop...
Loops (cont’d)
What about for (i=0; i<10; i++)? Use range():
def ageOneYear(self):
self.age += 1
y = np.array([[3,4,5]])
z = np.array([[6,7],[8,9]])
print x,y,z
print x.shape
print y.shape
print z.shape
np.ndarray
x = np.array([1,2,3]) >> [1 2 3]
Always reduces along an axis! (Or will reduce along all axes if not specified.)
(You can think of this as “collapsing” this axis into the function’s output.)
x = np.array([[1,2],[3,4]])
Always reduces along an axis! (Or will reduce along all axes if not specified.)
(You can think of this as “collapsing” this axis into the function’s output.)
x = np.array([[1,2],[3,4]])
print(np.array([1,2,3]).T) >> [1 2 3]
print(np.array([1,2,3]).T) >> [1 2 3]
Note: Scipy and np.linalg have many, many other advanced functions that are very useful!
Indexing
x = np.random.random((3, 4)) # Random (3,4) matrix
Note: Selecting with an ndarray or range will preserve the dimensions of the selection.
Broadcasting
x = np.random.random((3, 4)) # Random (3, 4) matrix
Note: If you’re getting an error, print the shapes of the matrices and investigate from there.
Efficient Numpy Code
Avoid explicit for-loops over indices/axes at all costs.