Python Default Values
Python executes some very interesting behaviour with regards to default values:
def a(v=): v.append(1) print(v) a() a() a() a()
Why does this happen? Default parameter values are always evaluated when, and only when, the “def” statement they belong to is executed. Also note that “def” is an executable statement in Python, and that default arguments are evaluated in the “def” statement’s environment. If you execute “def” multiple times, it’ll create a new function object (with freshly calculated default values) each time.
Python Data Structure Libraries
Heaps are provided by the
heapq library in python.
import heapq a = [1,2,3,4,5,6] # Heapq defaults to min heap heapq.heapify(a) # makes a into a min heap object heapq.heappop(a) heapq._heapify_max(a) # Makes a into max heap heapq._heappop_max(a)
queue module provides FIFO, LIFO and Priority Queues. Among them,
queue.PriorityQueue is perhaps the most commonly used in interview
import queue pq = queue.PriorityQueue() pq.put((10, 'ten')) pq.put((1, 'one')) pq.put((5, 'five')) x =  while not pq.empty(): print(pq.get())
Some important string operators and functions are:
- s + t
- s in t
- 3 * ‘01’
Strings are immutable, so operations create new array of characters that are then assigned back to s.
Python Nifty Tricks
The tilde operator
~ is the bit-wise complement operator, and it
essentially calculates the
-x-1. This comes in useful in arrays, where
\(s[~x] = s[-x-1]\). An example usage would be the \(O(n)\) time
def is_palindrome(s): return all(s[i] == s[~i] for i in range(len(s) // 2))
For loop else clause
for loop has
else clause, that runs when the for loop successfully
String translation tables
str.maketrans creates a translation table that makes string
Checking if character unique in string
s.index(x) == s.rindex(x) to check if character is only one in the string
rougier/from-python-to-numpy is a great reference to see how to speed up programs through vectorization.