Interview Code Snippets

2 min read

I use these python APIs in interviews

Dataclasses

Create a class with autogenerated

  • __init__()
  • __repr__(). So it looks good when you print it
  • __eq__(). Compares like it's a tuple.
  • __lt__(), __le__(), __gt__(), and __ge__() if you pass in order=True
Snippet
from dataclasses import dataclass

@dataclass
class Node:
    foo: str
    bar: int

n = Node('baz', 1)

print(n) # Node(foo='baz', bar=1) 

DefaultDict

When accessing an element for the first time, it returns a default value. Useful when counting occurrences of a key.

contains() still works correctly

Snippet
from collections import defaultdict

x = defaultdict(int) # default value 0
y = defaultdict(list) # default value []

print('foo' in x)
x['foo'] += 1
print(x)

Deque

A double ended queue. Can add/remove elements to either end. It's not a linked list because it doesn't have constant time addition/removal in the middle.

Snippet
from collections import deque

de = deque()
de.appendleft(1)
de.append(2)
de.appendleft(0)
print(de) # deque([0, 1, 2])

de.remove(1) # Careful, this is O(N) complexity, not O(1) like a linked list
print(de) # deque([0, 2])

n = de.pop() 
print(n, de) # 2 deque([0])

n = de.popleft() 
print(n, de) # 0 deque([])


Priority Queue

A min priority queue. Add integers, tuples of comparable objects or objects that implement __lt__ and __eq__. Can hack it to work as a max priority queue.

The difference between this and heapq is that this is thread safe.

Snippet
from dataclasses import dataclass

@dataclass(order=True)
class Job(object):
    priority: int
    description: str
    
from queue import PriorityQueue
q = PriorityQueue()

q.put( Job(3, 'Mid-level job') )
q.put( Job(10, 'Low-level job') )
q.put( Job(1, 'Important job') )

# A simple tuple would also work
# q.put((1, 'important job'))

# To reverse the priorities, multiple the priority by -1

print(q.qsize()) # 3

while not q.empty():
    next_job = q.get()
    print ('Processing job:', next_job.description)

Random

Generate random ints or floats.

Snippet
import random

print(random.random()) # Float from  0.0 <= x < 1.0
random.randrange(10)   # Integer from 0 <= x < 10