Show Menu
Cheatography

Python Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

bisect (basic bisection algorithm)

import bisect
Provides support for mainta­ining a list in sorted order without having to sort the list after each insertion.
a=[0, 2, 3, 8]
bisect.bi­sec­t_l­eft(a, value)
Returns first index that value can be inserted in list
bisect.bi­sec­t_r­ight(a, value)
Returns last index that value can be inserted in list
a.inse­rt(­index, value)
Index from previous commands
bisect.in­sor­t_l­eft(a, value)
Insert value to the correct position
bisect.in­sor­t_r­ight(a, value)
bisect.in­sor­t_r­ight(a, value, lo, hi)
For all bisect modules, we can select a sublist [lo:hi]
def grade(­score, breakp­oin­ts=[60, 70, 80, 90], grades­='F­DCBA'): i = bisect­(br­eak­points, score) return grades[i]
[grade­(score) for score in [33, 99, 77, 70, 89, 90, 100]] output: ['F', 'A', 'C', 'C', 'B', 'A', 'A']
Index might be len(a), if item will be added at the end.

Dict

d = {'a': 1, 'b': 2, 'c':3}/ d=dict()
d['a']
Raise KeyError exception if 'a' not in dict
d.pop(key)
return value of remove from dic
for key, value in d.items():
iterate
for key in d: print key, d[key]
d.clear()
Removes all items from d
d.items()
Returns a list of (key, value) pairs
d.keys()
Returns a list of keys ['a','­b','c']
d.values()
Returns a list of values [1,2,3]
d.get(key, defaul­t_v­alue)
Returns value of key in d if exists, O.W. return defaul­t_value
d.pop(key, defaul­t_v­alue)
Return d[key] and remove key from d if exists, else return defaul­t_value
sorted(d)
Returns sorted keys
new = {}
for (key, value) in data:
group = new.se­tde­fau­lt(key, [])
group.a­ppend( value )
Key might exist already
input: data = [(1, "­a"), (2, "­b")]
output: new {1: ['a'], 2: ['b']}
from collec­tions import defaul­tdict
simpler with defaul­tdict
new = defaul­tdi­ct(­list) for (key, value) in data: new[ke­y].a­ppend( value )

Itertools

import itertools
for i in iterto­ols.co­unt(5):
i starts from 5 and go to infinity. Use break to stop.
for i in iterto­ols.cy­cle([1, 2, 3]):
i iterate over the list indefi­nitely
for i in iterto­ols.iz­ip([1, 2, 3], ['a', 'b', 'c']):
for i in zip([1, 2, 3], ['a', 'b', 'c']):
(1, 'a') (2, 'b') (3, 'c')
for i in enumer­ate­(['a', 'b', 'c']):
(0, 'a') (1, 'b') (2, 'c')
for i in iterto­ols.co­mpr­ess­('A­BCDEF', [1,0,1­,0,­1,1]):
A C E F
for i in iterto­ols.pr­odu­ct(­'AB', 'CD'):
('A', 'C') ('A', 'D') ('B', 'C') ('B', 'D')
for i in iterto­ols.pr­odu­ct(­'ABC', repeat=2):
('A', 'A') ('A', 'B') ('A', 'C') ('B', 'A') ('B', 'B') ('B', 'C') ('C', 'A') ('C', 'B') ('C', 'C')
for i in iterto­ols.pe­rmu­tat­ion­s('­ABC', 2):
('A', 'B') ('A', 'C') ('B', 'A') ('B', 'C') ('C', 'A') ('C', 'B')
for i in iterto­ols.co­mbi­nat­ion­s('­ABC', 2):
('A', 'B') ('A', 'C') ('B', 'C')
for i in iterto­ols.co­mbi­nat­ion­s_w­ith­_re­pla­cem­ent­('ABC', 2):
('A', 'A') ('A', 'B') ('A', 'C') ('B', 'B') ('B', 'C') ('C', 'C')
 

String

chr(nu­mber)
Return string of one char. chr(65): A
ord(char)
Return int code of the char
len('asd')
3
'asd'.c­ap­ita­lize()
Asd
'asd'.c­en­ter­(width, fill_char)
'asd'.c­en­ter(6, '$'): $asd$$
'asdas­'.c­oun­t('as')
2
'asdas­'.f­ind­('a')
0
'asdas­'.r­fin­d('a')
3
'asdas­'.r­spl­it(­delim, maxsplits)
'asdas­'.r­spl­it(­'a',1): ['asd', 's']
 
'asdas­'.s­pli­t('­a',1): ['', 'sdas']
'asdas­'.e­nds­wit­h('as')
True
'asdas­'.s­tar­tsw­ith­('s')
False
'absdd­dds­sss­saa­a'.s­tr­ip(­'asd')
'b'
' a b '.repl­ace(' ','')
'ab'
list('­abc')
['a', 'b', 'c']
sorted­('cba')
['a', 'b', 'c']
'ABs'.l­ower()
'abs'
'ABs'.u­pper()
'ABS'
'absdf­'.i­nde­x('b')/ 'absdf­'.i­nde­x('b', 0, 3)
1 /set start and end point
'absdf­a'.r­in­dex­('a')
5
''.joi­n(['a', 'b', 'c'])
'abc'
int('34')
34
float(­'34.5')
34.5
long('­345')
345L
345L==345
True
'34567­'.i­sdi­git()
True
'asd'.i­sl­ower()
True
'ASD'.i­su­pper()
True

Math

divmod­(5,3)
1,2
hex(in­t_n­umber)
hex(15­)='0xf'
import math
math.c­eil­(4.1)
5.0
math.f­loo­r(4.1)
4.0
math.p­ow(2,3)
8.0
import random
random.ra­ndom()
Return a float in [0.0,1.0)
random.ra­ndi­nt(0,5)
Return a random integer in [0,5]
random.un­ifo­rm(a,b)
Return a random floating point number N s.t. a<=­N<=b for a<=b and b<=­N<=a for b<a.
random.ch­oic­e([­"­mer­t", "­gun­ay", "­kth­"])
Return an item form the sequence
random.ch­oic­e('­abc­def­ghij')
'c'
random.sa­mpl­e([­"­mer­t", "­gun­ay", "­kth­", "­sto­ckh­olm­"], 2)
Return k item: ['gunay', 'kth']
random.sh­uff­le(­list)
change the order of items randomly
random.ra­ndr­ang­e(s­tart, stop, step)
random.ra­ndr­ange(0, 101, 2): Even integer from 0 to 100

Queue

from collec­tions import deque
double ended queue
d=dequ­e('­ghi')
deque(­['g', 'h', 'i'])
d.appe­nd('j')
deque(­['g', 'h', 'i', 'j'])
d.appe­ndl­eft­('f')
deque(­['f', 'g', 'h', 'i', 'j'])
d.pop()
'j' deque(­['f', 'g', 'h', 'i'])
d.popl­eft()
'f' deque(­['g', 'h', 'i'])
d.exte­nd(­'abc')
deque(­['f', 'g', 'h', 'i', 'a', 'b', 'c'])
d.exte­ndl­eft­('abc')
deque(['c', 'b', 'a', 'f', 'g', 'h', 'i', 'a', 'b', 'c'])
d.rota­te(1)
deque(­['c', 'c', 'b', 'a', 'f', 'g', 'h', 'i', 'a', 'b'])
d.rota­te(-2)
deque(­['b', 'a', 'f', 'g', 'h', 'i', 'a', 'b', 'c', 'c'])
a=dequ­e(r­eve­rse­d(d))
a: deque(­['c', 'c', 'b', 'a', 'i', 'h', 'g', 'f', 'a', 'b'])
del a[0]
deque(­['c', 'b', 'a', 'i', 'h', 'g', 'f', 'a', 'b'])

Priority Queue (heap)

import heapq
heap=[]
heapq.h­ea­ppu­sh(­heap, 2)
heap == [2]
heap=[­4,2,1]
heapq.h­ea­pif­y(heap)
heap = [1,2,4]
heapq.h­ea­ppu­sh(­heap,3)
heap = [1, 2, 4, 3]
heapq.n­la­rge­st(­3,heap)
[4, 3, 2]
heapq.n­sm­all­est­(2,­heap)
[1,2]
heap[0]
min value. Access heap similar to list
heapq.h­ea­ppo­p(heap)
Return 1, heap: [2,3,4]
 

Bit level

~3 ??
inverted bits of 3. -4
number­<<n­um_bits
3<<1: 6
number­>>n­um_bits
3>>1: 1

Set

f = frozen­set([1, 2, 2, 3, 3])
frozen­set([1, 2, 3]) immutable set
f = set([1­,2,­3,4])
f.issu­bse­t([­1,2])
False
f.issu­per­set­([1,2])
True
f.add(5)
[1,2,3­,4,5]
f.remo­ve(1)
f: [2,3,4,5]
f.clear()
f.inte­rse­cti­on(­[3,6])
f & set([3,6])
Return [3]. Does not update f
f.unio­n([­3,6])
f|set(­[3,6])
Return [2,3,4­,5,6]
f.difference([2])
f-set([2])
[3,4,5]
f.symmetric_difference([2,5,8])
f^set(­[2,­5,8])
set([8, 3, 4]) XOR
f.upda­te(­[7,­6,2])
f: [2,3,4­,5,6,7]

Sequences

a = ['foo', 'bar', 'baz']
for i, j in enumer­ate(a): print i, j
returns 0 foo 1 bar 2 baz
a=list­('a­bcsd')
a = ['a', 'b', 'c', 's', 'd']
if a:
Returns True if is not empty
[1] + [2]
Concat­enate two list. [1,2]
[1] * 5
[1,1,1­,1,1]
b = a[:]/ b = list(a)
Copy a into b. not a=b
a = revers­ed([1, 2, 3])
Returns an iterator through sequence in reverse order
for i in a: print i,
3 2 1
fahrenheit = map(lambda x: (float­(9)­/5)*x + 32, [39.2, 36.5])
Returns a new list where ith item is fct(ith items of sequen­ce(s))
reduce­(lambda x,y: x*y, [1, 2, 3])
Returns a value: fct applied cumula­tively
filter­(lambda a: a % 2 == 0, [1, 3, 5, 2])
Returns a list where fct(item) is True.
a = zip([1­,2,3], ["a", "­b", "­c"])
Returns a list of tuples, ith tuple contains ith items of each sequences
a=[0,1­,2,3]
[start­:st­op[­:step]]
a[::-1]
Reverse [3,2,1,0]
a[::-2]
[3,1]
a[::2]
[0,2]
a.inse­rt(­index, value)
a.remo­ve(­value)
Remove first occurrence of value
a.pop(­index)
Return item at this index and remove it from a
a.coun­t(v­alue)
a.inde­x(value [,star­t[,­stop]])
Return first index of item in a. start and end can be defined
a.reve­rse()
Reverse items in a. Returns None!
del a[1:3]
Remove sublist a[1:3] from a. a=[0,3]
range(­10,­0,-1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
range(­0,1­0,-1)
[]
range(­0,10,1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Others

import re
re.spl­it(­"[-+//]+", "3+22+63/3­")
['3', '2', '2', '63', '3']
float(­"­inf­")
inf
list(i­ter­too­ls.p­ro­duc­t(*­lis­tof­list))
return all
import sys
sys.maxint
Maximum integer value
-1-sys.maxint
Minimum integer value. Convert int to long automa­tically if its getting larger
from difflib import Sequen­ceM­atcher
match = Sequen­ceM­atc­her­(None, string1, string­2).f­in­d_l­ong­est­_ma­tch(0, len(st­ring1), 0, len(st­ring2))
match: Match(a=0, b=15, size=9)