Skip to content
📖 Advanced Python Syntax In A4
Python
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
code
.gitignore
README.org
cheatsheet-python-A4.pdf

README.org

1 Python CheatSheet

linkedin
github
slack


PRs Welcome

File me Issues or star this repo.

See more CheatSheets from Denny: #denny-cheatsheets

1.1 Python Compact Coding

NameComment
if … returnif k == 0: return False
if… continueif index == icol: continue
return if.. elsereturn val if i>0 else 0
multiple assignmentl, r = 2, 3
assign with check of nonea = b if b else 1
assignmentsl[1]=l[0]=0
swap valuesleft, right = right, left
list Comprehensions[x*x for x in range(1, 1001)]
list Comprehensionsl = [2, 3, 5]; [2*x for x in l if x>2]
use zipfor a, b in zip(nums, nums[3:])
build a listdp = [1] + [0]*3
sum a subarraysum(nums[0:k])
sort list in descending ordersorted(nums, reverse=True)
dictionary with defaultsm = collections.defaultdict(lambda: 1)
loop with single statementwhile p.left: p = p.left
print multiple valuesprint(x, y)
get both index and itemfor i, ch in enumerate(["a", "b", "c"]): print(i, ch)
mod negative(-2)%5

1.2 Python Common Algorithms

NameComment
bfscode/tree-bfs.py
trie treecode/tree-trie.py
python SemaphoreLeetcode: Print Zero Even Odd

1.3 List

NameComment
return all but lastlist[:-1]
The second last itemlist[-2] or list[~1]
mapmap(lambda x: str(x), [1, 2, 3])
create fixed size arrayl = [None] * 5
append an elementarray.append(var)
insert elements to headarray.insert(0,var)
delete element by indexdel a[1]
list as stackitem = l.pop()
sort in descendingl=sorted([8, 2, 5], reverse=True)
sort by attributel=sorted([(‘ebb’,12),(‘abc’,14)], key=lambda x: x[1])
in-place sortl.sort()
generate a-zmap(chr, range(ord('a'), ord('z')+1))
map/reducefunctools.reduce((lambda x, y: "%s %s" % (x, y)), l)
replace ith to jthlist[i:j] = otherlist
combine two listlist1 + list2
get sumsum(list)
unique listset(["Blah", "foo", "foo", 1, 1, 2, 3])
Insert to sorted listbisect.insort(l, 3)
Reverse a listl[::-1]

1.4 String

NameComment
reverse string‘hello world’[::-1]
array to string’ ‘.join([‘a’, ‘b’])
split string to array“hello, python”.split(“,”)
string to arraylist('abc')
format to 2 digitsprint "%02d" % (13)
capitalize string‘hello world’.capitalize()
upper/lower string‘aBc’.upper(), ‘aBc’.lower()
count substring‘2-5g-3-J’.count(‘-‘)
pad leading zero‘101’.zfill(10)
string remove tailing ‘0’‘0023’.rstrip(‘0’)
string remove leading ‘0’‘0023’.lstrip(‘0’)
check if string represent integer‘123’.isdigit()
check if string alphabetic‘aBc’.isalpha()
Check if string alphanumeric‘a1b’.isalnum()
find location of substring‘abc’.find(‘d’)= (returns -1)
find location of substring‘abc’.index(‘d’)= (raise exception)
replace string‘ab cd’.replace(‘=’,=”)
padd whitespace to the left‘a’.ljust(10,=’=’)
padd whitespace to the right‘a’.rjust(10,=’=’)

1.5 Integer

NameComment
max, minsys.maxsize, -sys.maxsize-1
min, maxmin(2, 3), max(5, 6, 2)
generate rangefor num in range(10,20)
get asciiord('a'), chr(97)
print integer in binary“{0:b}”.format(10)

1.6 Dict & Set

NameComment
dict get first elementm[m.keys()[0]]
intersectionlist(set(l1).intersection(set(l2)))
list to setset(list1)
remove from sets.remove(2)
remove the first from sets.pop()
sort dict by valuessorted(dict1, key=dict1.get)
deep copy dictimport copy; m2=copy.deepcopy(m1)

1.7 Bit Operator

NameComment
modx % 2
shift leftx << 1; a << 2
shift righx >> 2
andx & y
complement~x
xorx ^ y
power2 ** 3
bool complementnot x
binary formatbin(5) (get 101)
count 1 inside binarybin(5).count('1')

1.8 File

NameComment
Append fileopen("/tmp/test.txt", "ab").write("\ntest:")
Write fileopen("/tmp/test.txt", "wab").write("\ntest:")
Read filesf.readlines()
Check fileos.path.exists("/tmp/test.txt")

1.9 Math

NameComment
sqrtimport math; math.sqrt(5)
powerimport math; math.pow(2, 3)
randomrandom.randint(1, 10) 1 and 10 included
eval stringeval("2-11*2")

1.10 Networking

NameComment
Start a simple HTTP serverpython -m SimpleHTTPServer <port_number>

1.11 Queue/heapq

NameComment
Initialize min heapheapq.heapify(q)
heappush a tupleq=[]; heapq.heappush(q, (5, 'ab'))
popprint (heapq.heappop(q))
first itemq[0]
print heapqprint list(q)
create a queuefrom collections import deque; queue = deque([1,5,8,9])
append queuequeue.append(7)
pop queue from headelement = queue.popleft()

Review: Heap Problems

Link: BINARY HEAP AND HEAPQ IN PYTHON

1.11.1 minheap & maxheap

import heapq

# initializing list
li = [5, 7, 9, 1, 3]

# using heapify to convert list into heap
heapq.heapify(li) # a minheap
heapq._heapify_max(li) # for a maxheap!

# printing created heap
print (list(li))

# using heappush() to push elements into heap
# pushes 4
heapq.heappush(li,4)

# printing modified heap
print (list(li))

# using heappop() to pop smallest element
print (heapq.heappop(li))

print (list(li))

1.12 Code snippets

  • Initialize Linkedlist from array
def initListNodeFromArray(self, nums):
    head = ListNode(None)
    prev, p = head, head
    for num in nums:
        pre = p
        p.val = num
        q = ListNode(None)
        p.next = q
        p = p.next
    pre.next = None
    return head
  • Print linkedlist
def printListNode(self, head):
    print("printListnode")
    while head:
        print("%d" % (head.val))
        head = head.next
  • Print Trie Tree in level order
def printTrieTreeLevelOrder(self, node):
    print("printTrieTreeLevelOrder")
    if node.is_word:
        print("Node is a word")
    queue = []
    queue.append(node)
    while len(queue) != 0:
        s = ''
        for i in range(len(queue)):
            node = queue[0]
            del queue[0]
            for child_key in node.children:
                s = '%s %s' % (s, child_key)
                queue.append(node.children[child_key])
        if s != '':
            print 'print level children: %s' % (s)
  • python sort with customized cmp function: -1 first
nums = [3, 2, 6]
def myCompare(v1, v2):
    return -1
sorted_nums = sorted(nums, cmp=myCompare)
print nums # [3, 2, 6]
print sorted_nums # [6, 3, 2]
  • Initialize m*n matrix
col_count, row_count = 3, 2
matrix = [[None for j in range(col_count)] for i in range(row_count)]
print matrix

1.13 More Resources

License: Code is licensed under MIT License.

linkedin github slack
You can’t perform that action at this time.