Python for coding Interview
1 - Variables are dynamicly typed
n = 0
print('n =', n)
>>> n = 0
n = "abc"
print('n =', n)
>>> n = abc
2 - Variable - Multiple assignments
n, m = 0, "abc"
n, m, z = 0.125, "abc", False
3 - Variable - Increment
n = n + 1
n += 1
n++
4 - Variable - None is null (absence of value)
n = 4
n = None
print("n =", n)
>>> n = None
5 - If-Statements - If statements don't need parentheses or curly braces.
n = 1
if n > 2:
n -= 1
elif n == 2:
n *= 2
else:
n += 2
6 - If-Statements - Parentheses needed for multi-line conditions. and = &&, or = ||
n, m = 1, 2
if ((n > 2 and
n != m) or n == m):
n += 1
7 - Loops - While
n = 0
while n < 5:
print(n)
n += 1
>>> 0 1 2 3 4
8 - Loops - Looping from i = 0 to i = 4
for i in range(5):
print(i)
>>> 0 1 2 3 4
9 - Loops - Looping from i = 2 to i = 5
for i in range(2, 6):
print(i)
>>> 2 3 4 5
10 - Loops - Looping from i = 5 to i = 2
for i in range(5, 1, -1):
print(i)
>>> 5 4 3 2
11 - Math - Division is decimal by default
print(5 / 2)
>>> 2.5
12 - Math - Double slash rounds down
print(5 // 2)
>>> 2
13 - Math - CAREFUL: most languages round towards 0 by default, So negative numbers will round down
print(-3 // 2)
>>> -2
14 - Math - A workaround for rounding towards zero, is to use decimal division and then convert to int.
print(int(-3 / 2))
>>> -1
15 - Math - Modding is similar to most languages
print(10 % 3)
>>> 1
16 - Math - Except for negative values
print(-10 % 3)
>>> 2
17 - Math - To be consistent with other languages modulo
import math
from multiprocessing import heap
print(math.fmod(-10, 3))
>>> -1
18 - Math - More math helpers
print(math.floor(3 / 2))
>>> 1
print(math.ceil(3 / 2))
>>> 2
print(math.sqrt(2))
>>> 1.4142135623730951
print(math.pow(2, 3))
>>> 8
19 - Math - Max / Min Int
float("inf")
float("-inf")
20 - Math - Python numbers are infinite so they never overflow
print(math.pow(2, 200))
>>> 1.6069380442589903e+60
21 - Math - But still less than infinity
print(math.pow(2, 200) < float("inf"))
>>> True
22 - Arrays - Arrays (called lists in python)
arr = [1, 2, 3]
print(arr)
>>> [1, 2, 3]
23 - Arrays - Can be used as a stack
arr.append(4)
arr.append(5)
print(arr)
>>> [1, 2, 3, 4, 5]
arr.pop()
print(arr)
>>> [1, 2, 3, 4]
arr.insert(1, 7)
print(arr)
>>> [1, 7, 2, 3, 4]
arr[0] = 0
arr[3] = 0
print(arr)
>>> [0, 7, 2, 0, 4]
24 - Arrays - Initialize arr of size n with default value of 1
n = 5
arr = [1] * n
print(arr)
>>> [1, 1, 1, 1, 1]
print(len(arr))
>>> 5
25 - Arrays - Careful: -1 is not out of bounds, it's the last value
arr = [1, 2, 3]
print(arr[-1])
>>> 3
26 - Arrays - Indexing -2 is the second to last value, etc.
print(arr[-2])
>>> 2
27 - Arrays - Sublists (aka slicing)
arr = [1, 2, 3, 4]
print(arr[1:3])
>>> [2, 3]
28 - Arrays - Similar to for-loop ranges, last index is non-inclusive
print(arr[0:4])
>>> [1, 2, 3, 4]
29 - Arrays - But no out of bounds error
print(arr[0:10])
>>> [1, 2, 3, 4]
30 - Arrays - Unpacking
a, b, c = [1, 2, 3]
print(a, b, c)
>>> 1, 2, 3
31 - Arrays - Be careful though, this throws an error
a, b = [1, 2, 3]
32 - Arrays - Using index
for i in range(len(nums)):
print(nums[i])
>>> 1 2 3
33 - Arrays - Without index
for n in nums:
print(n)
>>> 1 2 3
34 - Arrays - With index and value
for i, n in enumerate(nums):
print(i, n)
>>> 0 1
>>> 1 2
>>> 2 3
35 - Arrays - Loop through multiple arrays simultaneously with unpacking
nums1 = [1, 3, 5]
nums2 = [2, 4, 6]
for n1, n2 in zip(nums1, nums2):
print(n1, n2)
>>> 1 2
>>> 3 4
>>> 5 6
36 - Arrays - Reverse
nums = [1, 2, 3]
nums.reverse()
print(nums)
>>> [3, 2, 1]
37 - Arrays - Sorting
arr = [5, 4, 7, 3, 8]
arr.sort()
print(arr)
>>> [3, 4, 5, 7, 8]
arr.sort(reverse=True)
print(arr)
>>> [8, 7, 5, 4, 3]
arr = ["bob", "alice", "jane", "doe"]
arr.sort()
print(arr)
>>> ["alice", "bob", "doe", "jane"]
38 - Arrays - Custom sort (by length of string)
arr.sort(key=lambda x: len(x))
print(arr)
>>> ["bob", "doe", "jane", "alice"]
39 - Arrays - List comprehension
arr = [i for i in range(5)]
print(arr)
>>> [0, 1, 2, 3, 4]
40 - Arrays - 2-D lists
arr = [[0] * 4 for i in range(4)]
print(arr)
print(arr[0][0], arr[3][3])
>>> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
41 - Arrays - This won't work as you expect it to
arr = [[0] * 4] * 4
42 - Strings - Strings are similar to arrays
s = "abc"
print(s[0:2])
>>> "ab"
43 - Strings - But they are immutable, this won't work
s[0] = "A"
44 - Strings - This creates a new string
s += "def"
print(s)
>>> "abcdef"
45 - Strings - Valid numeric strings can be converted
print(int("123") + int("123"))
>>> 246
46 - Strings - And numbers can be converted to strings
print(str(123) + str(123))
>>> "123123"
47 - Strings - In rare cases you may need the ASCII value of a char
print(ord("a"))
print(ord("b"))
>>> 97
>>> 98
48 - Strings - Combine a list of strings (with an empty string delimitor)
strings = ["ab", "cd", "ef"]
print("".join(strings))
>>> "abcdef"
49 - Queues - Queues (double ended queue)
from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
print(queue)
>>> deque([1, 2])
queue.popleft()
print(queue)
>>> deque([2])
queue.appendleft(1)
print(queue)
>>> deque([1, 2])
queue.pop()
print(queue)
>>> deque([1])
50 - HashSets - HashSet
mySet = set()
mySet.add(1)
mySet.add(2)
print(mySet)
>>> {1, 2}
print(len(mySet))
>>> 2
print(1 in mySet)
>>> True
print(2 in mySet)
>>> True
print(3 in mySet)
>>> False
mySet.remove(2)
print(2 in mySet)
>>> False
51 - HashSets - list to set
print(set([1, 2, 3]))
>>> {1, 2, 3}
52 - HashSets - Set comprehension
mySet = { i for i in range(5) }
print(mySet)
>>> {0, 1, 2, 3, 4}
53 - HashMaps -HashMap (aka dict)
myMap = {}
myMap["alice"] = 88
myMap["bob"] = 77
print(myMap)
>>> {"alice": 88, "bob": 77}
print(len(myMap))
>>> 2
myMap["alice"] = 80
print(myMap["alice"])
>>> 80
print("alice" in myMap)
>>> True
myMap.pop("alice")
print("alice" in myMap)
>>> False
myMap = { "alice": 90, "bob": 70 }
print(myMap)
>>> { "alice": 90, "bob": 70 }
54 - HashMaps -Dict comprehension
myMap = { i: 2*i for i in range(3) }
print(myMap)
>>> { 0: 0, 1: 2, 2: 4 }
55 - HashMaps - Looping through maps
myMap = { "alice": 90, "bob": 70 }
for key in myMap:
print(key, myMap[key])
>>> "alice" 90
>>> "bob" 70
for val in myMap.values():
print(val)
>>> 90
>>> 70
for key, val in myMap.items():
print(key, val)
>>> "alice" 90
>>> "bob" 70
56 - Tuples - Tuples are like arrays but immutable
tup = (1, 2, 3)
print(tup)
>>> (1, 2, 3)
print(tup[0])
>>> 1
print(tup[-1])
>>> 3
57 - Tuples - Can't modify, this won't work
tup[0] = 0
58 - Tuples - Can be used as key for hash map/set
myMap = { (1,2): 3 }
print(myMap[(1,2)])
>>> 3
mySet = set()
mySet.add((1, 2))
print((1, 2) in mySet)
>>> True
59 - Tuples - Lists can't be keys
myMap[[3, 4]] = 5
60 - Heaps - # under the hood are arrays
import heapq
minHeap = []
heapq.heappush(minHeap, 3)
heapq.heappush(minHeap, 2)
heapq.heappush(minHeap, 4)
61 - Heaps - Min is always at index 0
import heapq
print(minHeap[0])
>>> 2
while len(minHeap):
print(heapq.heappop(minHeap))
>>> 2 3 4
62 - Heaps - No max heaps by default, work around is, to use min heap and multiply by -1 when push & pop.
import heapq
maxHeap = []
heapq.heappush(maxHeap, -3)
heapq.heappush(maxHeap, -2)
heapq.heappush(maxHeap, -4)
63 - Heaps - Max is always at index 0
print(-1 * maxHeap[0])
>>> 4
while len(maxHeap):
print(-1 * heapq.heappop(maxHeap))
>>> 4 3 2
64 - Heaps - Build heap from initial values
arr = [2, 1, 8, 4, 5]
heapq.heapify(arr)
while arr:
print(heapq.heappop(arr))
>>> 1 2 4 5 8
65 - Functions -
def myFunc(n, m):
return n * m
print(myFunc(3, 4))
>>> 12
66 - Functions - Nested functions have access to outer variables
def outer(a, b):
c = "c"
def inner():
return a + b + c
return inner()
print(outer("a", "b"))
>>> "abc"
67 - Functions - Can modify objects but not reassign, unless using nonlocal keyword
def double(arr, val):
def helper():
for i, n in enumerate(arr):
arr[i] *= 2
nonlocal val
val *= 2
helper()
print(arr, val)
nums = [1, 2]
val = 3
double(nums, val)
>>> [2, 4] 6
68 - Classes
class MyClass:
def __init__(self, nums):
self.nums = nums
self.size = len(nums)
def getLength(self):
return self.size
def getDoubleLength(self):
return 2 * self.getLength()
myObj = MyClass([1, 2, 3])
print(myObj.getLength())
>>> 3
print(myObj.getDoubleLength())
>>> 6