Python for Coding Interviews
Variables
Python is dynamically typed, meaning you don’t need to declare the type of a variable. Here’s how it works:
n = 0
print(n) # Output: 0
n = "ABC"
print(n) # Output: ABC
Multiple Assignments
You can assign multiple variables in one line:
a, b = 1, "Hello"
print(a, b) # Output: 1 Hello
Incrementing
Incrementing variables is straightforward:
n = 1
n = n + 1
n += 1
Note: n++
is not valid in Python.
Null Values
In Python, None
represents the absence of a value:
n = 4
n = None
print(n) # Output: None
If Statements
Python’s if statements don’t require parentheses or curly braces. Instead, they use colons and indentation:
if n == 0:
print("Zero")
elif n == 1:
print("One")
else:
print("Other")
Logical Operators
Python uses and
and or
instead of &&
and ||
:
if n > 0 and n < 10:
print("Single digit")
Loops
While Loops
n = 0
while n < 5:
print(n)
n += 1
For Loops
Python’s for
loops are quite powerful:
for i in range(5):
print(i)
You can also specify start and end points:
for i in range(2, 6):
print(i)
Reverse Loops
To loop in reverse:
for i in range(5, 1, -1):
print(i)
Math Operations
Division
Python uses decimal division by default:
print(5 / 2) # Output: 2.5
print(5 // 2) # Output: 2 (integer division)
print(-3 // 2) # Output: -2 (rounding down)
Modulo
The modulo operator %
works as expected but can behave differently with negative numbers:
print(10 % 3) # Output: 1
print(-10 % 3) # Output: 2
Useful Math Helpers
Python’s math
module offers many helpful functions:
import math
print(math.floor(2.7)) # Output: 2
print(math.ceil(2.7)) # Output: 3
print(math.sqrt(16)) # Output: 4.0
print(math.pow(2, 3)) # Output: 8.0
Arrays (Lists)
Basic Operations
Lists are dynamic arrays in Python:
arr = [1, 2, 3]
print(arr) # Output: [1, 2, 3]
arr.append(4)
print(arr) # Output: [1, 2, 3, 4]
arr.pop()
print(arr) # Output: [1, 2, 3]
arr.insert(1, 7)
print(arr) # Output: [1, 7, 2, 3]
Slicing
print(arr[1:3]) # Output: [7, 2]
List Comprehension
squared = [x**2 for x in range(5)]
print(squared) # Output: [0, 1, 4, 9, 16]
Strings
Strings in Python are immutable:
s = "Hello"
print(s[1:4]) # Output: ell
# Strings are immutable
# s[0] = 'h' # This will raise an error
# Concatenation creates a new string
s = s + " World"
print(s) # Output: Hello World
Conversion
num = int("123")
print(num) # Output: 123
s = str(123)
print(s) # Output: 123
Queues
Python’s deque
can be used for queues:
from collections import deque
q = deque()
q.append(1)
q.append(2)
print(q) # Output: deque([1, 2])
q.popleft()
print(q) # Output: deque([2])
Hash Sets
Sets in Python offer O(1) time complexity for inserts and lookups:
s = {1, 2, 3}
print(s) # Output: {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}
s.remove(2)
print(s) # Output: {1, 3, 4}
Hash Maps (Dictionaries)
Dictionaries are the go-to data structure for key-value pairs:
d = {"Alice": 88, "Bob": 77}
print(d) # Output: {'Alice': 88, 'Bob': 77}
d["Charlie"] = 99
print(d) # Output: {'Alice': 88, 'Bob': 77, 'Charlie': 99}
print(d.get("Alice")) # Output: 88
del d["Bob"]
print(d) # Output: {'Alice': 88, 'Charlie': 99}
Tuples
Tuples are immutable lists:
t = (1, 2, 3)
print(t[0]) # Output: 1
# t[0] = 0 # This will raise an error
Heaps
Heaps are great for priority queues:
import heapq
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 2)
print(heap) # Output: [1, 3, 2]
print(heapq.heappop(heap)) # Output: 1
print(heap) # Output: [2, 3]
Functions
Basic Functions
def multiply(n, m):
return n * m
print(multiply(2, 3)) # Output: 6
Nested Functions
Nested functions can access variables from the outer function:
def outer(a, b):
def inner():
return a + b
return inner()
print(outer(1, 2)) # Output: 3
Classes
Python classes are concise and powerful:
class MyClass:
def __init__(self, nums):
self.nums = nums
self.size = len(nums)
def get_length(self):
return self.size
def get_double_length(self):
return self.get_length() * 2
my_obj = MyClass([1, 2, 3])
print(my_obj.get_length()) # Output: 3
print(my_obj.get_double_length()) # Output: 6
Conclusion
This covers the essentials of Python you need to know for coding interviews. With practice, you’ll find Python’s syntax straightforward and its features powerful. Python played a crucial role in my journey to securing a job at Google, and I hope it helps you too.
Recommended Resources
by NeetCode
Leave a Reply