Code snippets
This post list some of the python code snippets which are useful in coding interviews and problem solving. Such snippets, although are easy to remember and are often used in many problems.
Added here for reference and some common gotchas.
Initialize an array with initial values#
# Initialize an array of size n with 0
# Creates an array as [0, 0, 0] if n = 3
a = [0] * n
# another way to write this:
# 0, 0, 0
a = [ 0 for _ in range(3)]
# Initialize an 2D array of size rows `n` and `m` columns with value 0
# Creates an array as [[0,0], [0,0], [0,0]] if n = 3, m = 2
a = [[0] * m for _ in range(n)]
# Do not use, * operator to create multi-dimension list as it `*` copies references.
# https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list
a = [[0] * m] * n # Not to do this
# Just to avoid confusion: Use single/multiple dimension arrays as:
# Will create array a as: [[0, 0], [0, 0], [0, 0]]
a = [[0 for _ in range(m)] for _ in range(n)]
Initialize a dictionary#
What are some of the ways to initialize a dictionary in python.
# A dictionary can be initialized as
a = {}
# A dictionary can also be initialized using the library defaultdict(type),
# Using defaultdict initialize with `0` as default value, whenever the dictionary doesn't have the character.
from collections import defaultdict
a = defaultdict(int)
# Although default dict is really helpful. But needs to be careful on not modifying the dictionary during iteration, by accessing with a key which is not present.
# Example: Will give Error: `RuntimeError: dictionary changed size during iteration`
a = defaultdict(int)
a['a'] = 1
a['b'] = 2
searchKey = 'c'
for k,v in a.items():
if a[searchKey]: # Creates a new element `c` in the dictionary, which breaks the iteration.
print(k, v)
# Although this error is easy to see in this. The error is much harder to debug, as it doesn't tell which key is causing the problem.
# The issue when trying to read a key in the for loop, it also updates the map.
# Note: So always use get(key) method to access a value in the defaultDict.
a = defaultdict(int)
a['a'] = 1
a['b'] = 2
searchKey = 'c'
for k,v in a.items():
if a.get(searchKey): # Use get to read the value for the key in the default dict.
print(k, v)
Iterate over different data structures#
# Iterate over numbers from 0...n - 1
n = 10
for i in range(n):
print(i)
# Iterate over all the elements in array
a = [1, 2, 3, 4, 5]
for x in a:
print(x)
# Iterate with index and element in array
a = [1, 2, 3, 4, 5]
for i, x in enumerate(a):
print(f'i=>x, {i}=> {x}')
# Iterate over all the k, v pairs in dictionary, no order of keys.
# k:v, 1:a
# k:v, 2:b
# k:v, 3:c
d = {1: 'a', 2: 'b', 3: 'c'}
for k, v in d.items():
print(f'k:v, {k}:{v}')