Skip to content

Instantly share code, notes, and snippets.

@bobbyali
Last active August 29, 2015 14:15
Show Gist options
  • Save bobbyali/79fed4df303bfcfd9eac to your computer and use it in GitHub Desktop.
Save bobbyali/79fed4df303bfcfd9eac to your computer and use it in GitHub Desktop.
Python Summary
Python quickstart tutorial
http://www.swaroopch.com/notes/python/#first_steps
Triple Quotes for multiple line strings
Split lines - use \
Strings:
* print '{0} was {1} years old when he wrote this book'.format(name, age)
{0:.3f}'.format(1.0/3) --> 0.333
'{0:_^11}'.format('hello') ---> ___hello___
print name + ' is ' + str(age) + ' yrs old'
Prevent newline, use a comma
print "a",
Raw string (no escape chars), prefix with r
r"string"
USE WITH REGEX
Operators
** is power of
// is integer division
<< is left shift
2 << 2 returns 8 because 010 --> 100
^ is bitwise XOR
5 ^ 3 yields 6 because 0101 ^ 0011 --> 0111 = 6
Control Flow
if:
elif:
else:
while statement:
else:
for i in range(1,5):
else:
break / continue
Functions
def say_hello(a=1,b):
Can call function with keyword args (diff orders, can ignore params w default vals)
say_hello(b=1)
VarArgs
def total(init=5, *numbers, **keywords)
for number in numbers:
count += number
for key in keywords:
count += keywords[key]
return count
*param --> tuple called param
**param --> dictionary called param
DocStrings
Enables quick documentation of functions, modules, classes
def print_max(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
print print_max.__doc__
Modules
"module_using_sys.py"
import sys
print('The command line arguments are:')
for i in sys.argv:
print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'
python module_using_sys.py we are arguments
When first called, it gets byte-compiled into .pyc
if __name__ == '__main__':
print 'This program is being run by itself'
else:
print 'I am being imported from another module'
__version__ = '0.1'
Every python script is a potential module.
dir() - shows available attributes in current module
del a - deletes variable a
Packages
Organise modules
Folder contains init.py __init__.py
Ensure folder appears in the sys.path directory
Data Structures
http://interactivepython.org/runestone/static/pythonds/Introduction/GettingStartedwithData.html
- list of methods for each data type
List
['a','big','poo']
Can use as a stack: LAST IN FIRST OUT
stack = [3, 4, 5]
stack.append(6)
stack.pop()
Can use as a queue: FIRST IN FIRST OUT
from collections import deque
queue = deque(["Eric", "Terry"])
queue.append("John")
queue.popleft()
Not efficient...
Tuple
('python','elephant','penguin')
Holds together multiple objects
Immutable
Return multiple variables from function:
def get_error_details():
return (2, 'details')
errnum, errstr = get_error_details()
Dictionary
d = {key1 : value1, key2 : value2 }
Sequence
Lists, tuples, strings are egs of sequences
Properties
Membership tests (e.g. can test for item with 'in' / 'not in')
Indexing operations
[-1]
[:]
[::2] - step 2 items at a time
Slicing functions
Set
bri = set(['brazil', 'russia', 'india'])
Unordered collections of objects
Can test for membership with 'in'
e.g. 'india' in bri
References
shoplist = ['apple','mango']
mylist = shoplist (mylist points to shoplist)
mylist = shoplist[:] (mylist makes copy via full slice)
USE SLICING TO MAKE COPIES OF SEQUENCES / COMPLEX OBJS
OOP
Class methods MUST HAVE SELF as first parameter!!
class Person:
pass # empty block
p = Person()
----
class Person:
def say_hi(self):
print('Hi!')
p = Person()
p.say_hi()
----
class Person:
def __init__(self, name):
self.name = name
p = Person('Ali')
----
class Robot:
population = 0
def __init(self, name):
self.name = name
Robot.population += 1
A self.variable is an object variable.
A Class.variable is a class variable.
A __variable is a private variable.
----
Inheritance:
class SchoolMember:
class Teacher(SchoolMember):
class Student(SchoolMember):
I/O
raw_input()
open()
readline()
write()
close()
Pickle
Store any object in file, for persistence
import pickle
fh = open(file, 'wb')
pickle.dump(object, fh)
f.close
del object
fh = open(file, 'rb')
list = pickle.load(f)
Unicode
http://www.joelonsoftware.com/articles/Unicode.html
Prefix string with 'u'
Use this when opening / saving files with unicode:
encoding="utf-8"
Exceptions
try:
except <ERROR_TYPE>:
else:
finally: - handle if try works ??????
with open("poem.txt") as f:
for line in f:
print line, ??????
raise <ERROR_TYPE>
Single statement blocks
if flag: print 'Yes'
Lambda Forms
the lambda takes a parameter followed by a single expression only which becomes the body of the function and the value of this expression is returned by the new function.
points = [ { 'x' : 2, 'y' : 3},
{ 'x' : 4, 'y' : 1} ]
points.sort(key=lambda pair : pair['y'])
print points
We write a lambda to avoid writing a custom function to provide sort with a key.
https://docs.python.org/2/tutorial/controlflow.html#lambda-expressions
Can also make your own function generators:
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(1) # returns 43
List Comprehension
Let you build quick lists/arrays from existing lists.
https://d396qusza40orc.cloudfront.net/matrix/from-loop-to-comprehension.pdf
[(i,j) for i in range(10) for j in {2, 5, 9}]
Functional Programming
filter
def f(x): return x % 3 == 0 or x % 5 == 0
filter(f, range(2,9))
# [3, 5, 6, 9]
Returns items for which f(x) is true.
map
def cube(x): return x ** 3
map(cube, range(1,4))
# [1, 8, 27, 64]
Calls f(x) for each item and returns list of return values.
reduce
def add(x,y): return x+y
reduce(add, range(1,11))
# 55
Returns single value constructed by calling f(x) on first two items
of sequence, then on result and next item, and so on.
(e.g. ((1+2) + 3) + 4)... )
http://docs.python-guide.org/en/latest/writing/tests/
Unit Tests
import unittest
def fun(x):
return x + 1
class MyTest(unittest.Test)
def test(self):
self.assertEqual(fun(3),4)
def setUp():
def tearDown():
NumPy
ndarray is the main array type
Create ndarray:
from numpy import *
a = array( [2,3,4] ) SINGLE LIST OF NUMBERS AS FIRST ARGUMENT
b = array( [ (1.5,2,3), (4,5,6) ] ) 2D ARRAY
c = array( [ [1,2], [3,4] ], dtype=complex ) EXPLICITLY SPECIFY ARRAY TYPE
zeros( (3,4) )
ones( (3,4) )
empty( (3,4) )
arange( 10, 30, 5 )
linspace( 0, 2, 9 )
1D arrays are printed as ROWS
2D arrays are printed as MATRICES
3+D arrays are printed as lists of matrices
Last axis printed LEFT-TO-RIGHT
Second-to-last axis is printed TOP-TO-BOTTOM
Rest are also top to bottom
A*B element-wise multiplication
dot(A,B) matrix product
Copies vs Views
NO COPY - simple assignments
b = a
function calls with arrays
VIEW/SHALLOW COPY - diff array objects share same data
c = a.view()
slicing
DEEP COPY
d = a.copy()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment