Cheatsheet - Python

Updated: 2018-12-04

Time complexity

https://wiki.python.org/moin/TimeComplexity

Unit Test: Assert

Use assert for unit testing.

>>> a = 1
>>> assert a == 1
>>> assert a != 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

Swap

a, b = b, a

Repeated Values In List/Tuple

List

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Tuple.

>>> (0,) * 10
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

Notice the comma in (0,), otherwise it is scalar calculation

>>> (1) * 10
10

Unpack

>>> a, *b, c = [1, 2, 3, 4, 5, 6]
>>> a
1
>>> b
[2, 3, 4, 5]
>>> c
6

Zip and Unzip

Zip

>>> x = (1, 2, 3)
>>> y = ('a', 'b', 'c')
>>> z = list(zip(x, y))
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]

Unzip. Use * to unpack z

>>> x, y = list(zip(*z))
>>> x
(1, 2, 3)
>>> y
('a', 'b', 'c')

Infinity

>>> import math
>>> math.inf
inf

Init 2D array

>>> a = [[0] * 3 for _ in range(4)]
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

2D 8-Directions

>>> [(x, y) for x in d for y in d if x != 0 or y != 0]
[(1, 1), (1, 0), (1, -1), (0, 1), (0, -1), (-1, 1), (-1, 0), (-1, -1)]

TreeNode Definition

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

If You Forget Function Name

Use dir() to check the function names:

>>> dir([])
[... 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Or pretty print:

>>> import pprint; pprint.pprint(dir([]))
[ ...
  'append',
  'clear',
  'copy',
  'count',
  'extend',
  'index',
  'insert',
  'pop',
  'remove',
  'reverse',
  'sort']

All and ANY

ALL: if every one is truthy

>>> all([1, "abc", [False]])
True
>>> all([1, 0, 1])
False

ANY: if any one is truthy

>>> any([1, 0, 0])
True
>>> any(["", 0, 0])
False

Conversions

string to char array

>>> s = "asdf"
>>> [c for c in s]
['a', 's', 'd', 'f']

int to char

>>> chr(97)
'a'

char to int

>>> ord('a')
97

int to binary

>>> format(14, 'b')
'1110'

int to hex

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')

Bytes

Not very likely used in interviews.

  • bytearray: mutable
  • bytes: immutable

string must comes with encoding

bytearray:

>>> a = bytearray("123", 'utf-8')
>>> a[0]
49
>>> a[1]
50

bytes:

>>> a = bytes('abc', 'utf-8')
>>> a
b'abc'