Python: The Secret Weapon in Technical Interviews

Python: The Secret Weapon in Technical Interviews

The Ultimate Cheatsheet

·

11 min read

Introduction

Python is your secret weapon for crushing your next interview. Even if the job you're applying for requires you to use a different programming language such as Java, Rust, or Solidity. In most interviews they let you code in any programming language of your choice so you should take advantage of that and code in Python! If you already know another programming language, Python isn't much different, it's just a matter of getting used to the different syntax. In this guide, you'll learn everything you need to know (syntax-wise) about Python!

Why Python For Technical Interviews?

Python is an excellent choice for technical interviews because it provides huge advantages that can help you solve problems quickly and efficiently. This is important because there are usually time constraints of between 10-30 minutes for solving a problem during an interview.

Python's simple and easy-to-read syntax allows you to concentrate on solving the problem rather than getting bogged down by the long and convoluted syntax of other programming languages (such as Java).

Furthermore, Python is a high-level language with many built-in functions and modules, making solving problems easier because much of the implementation is already done for you. This will save you a tremendous amount of time.

Basic Language Syntax

Printing, comments, indentation, string literals, & escape sequences

Hello World

print("Hello, World!")

SingleLine Comments

# First comment 
print("Hello, World!") 
# Second comment

MultiLine Comments

''' 
This is a 
multiline 
comment. 
'''

Indentation & Control Flow

if True: 
    print("True")
else: 
    print("False")

String Literals (Quotations in Python)

Python accepts single, double and triple quotes to denote string literals, as long as the same type of quote starts and ends the string.

word = 'word' 
sentence = "This is a sentence." 
paragraph = """This is a paragraph. It is made up of multiple lines and sentences.""" 
paragraph_2 = '''This is a paragraph with triple single quotes which is also valid.'''

Escape Sequences


print("Hello\nWorld") # \n adds a new line 
print("Hello\tWorld") # \t adds a tab space 
print("Hello \'World\' ") # \' escapes the single quote 
print("Hello \"World\" ") # \" escapes the double quote 
print("Hello \\World") # \\ escapes the backslash character

Escape Sequences Output

Hello 
World
Hello  World 
Hello 'World' 
Hello "World" 
Hello \World

Variables

Variable declaration, assignment, and incrementing/decrementing.

Declaring Variables

counter = 100 # Creates an integer variable 
miles = 1000.0 # Creates a floating point variable 
name = "Zara Ali" # Creates a string variable

Multiple Assignment

a = b = c = 100
# OR assign each on to a different value 
a,b,c = "hi", 3, 5.0
# OR unpacking
[ 1, 3, 4 ] = a,b,c

Variable Reassignment

# This variable is initially assigned as a string. 
var = "Hi there" 
# The same can be reassigned to any other value, regardless of the type. 
var = 35 var = False

Incrementing or Decrementing Variables

You can't do n++ or n-- like you can with other languages.

n = 0 
# Incrementing 
n = n+1 n += 1 
# Decrementing 
n = n-1 n -= 1

Data Types

None, Numeric, Sequence, Boolean, Set, and Dictionary.

None is Null

# None == Null
# Don't use 'null' in Python!!
n=4
n=None

String

Strings are immutable arrays in which every element is a character and they're also a type of sequence meaning you can access its elements by index.

Strings are immutable so whenever you update a string data type, it will create a completely new string which is said to be O(n) time complexity.

str = 'Hello World!'
print(str)          # Prints complete string
print(str[0])       # Prints first character of the string
print(str[2:5])     # Prints characters starting from 3rd to 5th
print(str[2:])      # Prints string starting from 3rd character
print(str * 2)      # Prints string two times
print(str + "TEST") # Prints concatenated string
print('My Fave Num: ' + str(1)) # Valid

Concatenation only works when both values that are being concatenated are strings. You can't concatenate an int with a string. You have to convert the int into a string first.

String Output

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
My Fave Num: 1

List

Lists are arrays and they're also a type of sequence meaning you can access it's elements by index.

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print(list)            # Prints complete list
print(list[0])         # Prints first element of the list
print(list[1:3])       # Prints elements starting from 2nd till 3rd 
print(list[2:])        # Prints elements starting from 3rd element
print(tinylist * 2)    # Prints list two times
print(list + tinylist) # Prints concatenated lists

List Output

['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Tuple

Tuples are immutable arrays and they're also a type of sequence meaning you can access it's elements by index.

You cannot update tuples.

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print(tuple)               # Prints the complete tuple
print(tuple[0])            # Prints first element of the tuple
print(tuple[1:3])          # Prints elements of the tuple starting from 2nd till 3rd 
print(tuple[2:])           # Prints elements of the tuple starting from 3rd element
print(tinytuple * 2)       # Prints the contents of the tuple twice
print(tuple + tinytuple)   # Prints concatenated tuples

Tuple Output

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

Numeric

Python has Integers, Float, and Complex Numbers

a = 5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))

Numeric Output

Type of a:  <class 'int'>

Type of b:  <class 'float'>

Type of c:  <class 'complex'>

Boolean

print(type(True))
print(type(False))

Boolean Output

print(type(True))
print(type(False))

Set

A set is an unordered collection with no duplicates.

Since sets are unordered, you can't access set items by referring to an index but you can access them by looping through items in a set.

# Python program to demonstrate  
# Creation of Set in Python 

# Creating a Set 
set1 = set() 
print("Initial blank Set: ") 
print(set1) 

# Creating a Set with  
# the use of a String 
set1 = set("GeeksForGeeks") 
print("\nSet with the use of String: ") 
print(set1) 

# Creating a Set with 
# the use of a List 
set1 = set(["Geeks", "For", "Geeks"]) 
print("\nSet with the use of List: ") 
print(set1) 

# Creating a Set with  
# a mixed type of values 
# (Having numbers and strings) 
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) 
print("\nSet with the use of Mixed Values") 
print(set1)

Set Output

Initial blank Set: 
set()

Set with the use of String: 
{'F', 'o', 'G', 's', 'r', 'k', 'e'}

Set with the use of List: 
{'Geeks', 'For'}

Set with the use of Mixed Values
{1, 2, 4, 6, 'Geeks', 'For'}

Dictionary

A dictionary is a hashmap and an unordered collection.

Dictionaries don't have an associated index, just like sets, so to access elements in a dictionary, you need to specify the key.

 Dict = {} 
print("Empty Dictionary: ") 
print(Dict) 

Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} 
print("\nDictionary with the use of Integer Keys: ") 
print(Dict) 

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} 
print("\nDictionary with the use of Mixed Keys: ") 
print(Dict) 

Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'}) 
print("\nDictionary with the use of dict(): ") 
print(Dict) 

Dict = dict([(1, 'Geeks'), (2, 'For')]) 
print("\nDictionary with each item as a pair: ") 
print(Dict) 

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} 

print("Accessing a element using key:") 
print(Dict['name']) 

print("Accessing a element using get:") 
print(Dict.get(3))

Dictionary Output

Empty Dictionary: 
{}

Dictionary with the use of Integer Keys: 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys: 
{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary with the use of dict(): 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair: 
{1: 'Geeks', 2: 'For'}

Accessing a element using key:
For
Accessing a element using get:
Geeks

Common Functions and Modules

Useful Functions

  • int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.

  • long(x [,base]) - Converts x to a long integer. base specifies the base if x is a string.

  • float(x) - Converts x to a floating-point number.

  • complex(real [,imag]) - Creates a complex number.

  • str(x) - Converts object x to a string representation.

  • repr(x) - Converts object x to an expression string.

  • tuple(s) - Converts s to a tuple.

  • list(s) - Converts s to a list.

  • set(s) - Converts s to a set.

  • dict(d) - Creates a dictionary. d must be a sequence of (key,value) tuples.

  • chr(x) - Converts an integer to a character.

  • ord(x) - Converts a single character to its integer value.

  • hex(x) - Converts an integer to a hexadecimal string

  • "".join([s]) - Converts a string array into a single string

List Comprehension

  • More time-efficient and space-efficient than loops.

  • Require fewer lines of code.

  • Transforms iterative statement into a formula.

List = [character for character in 'Geeks 4 Geeks!'] print(List)

matrix = [[j for j in range(3)] for i in range(3)] print(matrix)

matrix = [[j for j in range(5)] for i in range(3)] print(matrix)

numbers = [i*10 for i in range(1, 6)] print(numbers)

Map, Filter, and Reduce Functions

# Filter
y = filter(lambda x: (x>=3), (1,2,3,4))

# Map
tup= (5, 7, 22, 97, 54, 62, 77, 23, 73, 61) 
newtuple = tuple(map(lambda x: x+3 , tup))

# Reduce
reduce(lambda a,b: a+b,[23,21,45,98])

Lambda Functions

str1 = 'GeeksforGeeks'
rev_upper = lambda string: string.upper()[::-1] print(rev_upper(str1))

li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*2, li))

Data Structures:

Stack

Using List

stack = []

# append() function to push 
# element in the stack stack.append('g') 
stack.append('f') 
stack.append('g')

print('Initial stack') print(stack)

# pop() function to pop 
# element from stack in 
# LIFO order 
print('\nElements popped from stack:') 
print(stack.pop()) 
print(stack.pop()) 
print(stack.pop())

print('\nStack after elements are popped:') print(stack)

# uncommenting 
print(stack.pop()) 
# will cause an IndexError # as the stack is now empty

Using Deque

Deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity. 

python from collections import deque

stack = deque()

# append() function to push 
# element in the stack stack.append('g') 
stack.append('f') 
stack.append('g')

print('Initial stack:') print(stack)

# pop() function to pop 
# element from stack in 
# LIFO order 
print('\nElements popped from stack:') 
print(stack.pop()) print(stack.pop()) 
print(stack.pop())

print('\nStack after elements are popped:') print(stack)

# uncommenting 
print(stack.pop()) 
# will cause an IndexError 
# as the stack is now empty
  • empty() – Returns whether the stack is empty – Time Complexity: O(1)

  • size() – Returns the size of the stack – Time Complexity: O(1)

  • top() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)

  • push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)

  • pop() – Deletes the topmost element of the stack – Time Complexity: O(1)

Queue

Using List

# Initializing a queue queue = []

# Adding elements to the queue 

queue.append('g') 

queue.append('f') 

queue.append('g')

print("Initial queue") 

print(queue)

# Removing elements from the queue 

print("\nElements dequeued from queue") 

print(queue.pop(0)) 

print(queue.pop(0)) 

print(queue.pop(0))

print("\nQueue after removing elements") 

print(queue)

# Uncommenting print(queue.pop(0)) 

# will raise and IndexError 

# as the queue is now empty

Using Deque

from collections import deque

# Initializing a queue 
q = deque()

# Adding elements to a queue 
q.append('g') 
q.append('f') 
q.append('g')

print("Initial queue") 
print(q)

# Removing elements from a queue 
print("\nElements dequeued from the queue") 
print(q.popleft()) 
print(q.popleft()) 
print(q.popleft())

print("\nQueue after removing elements") 
print(q)

# Uncommenting q.popleft() 
# will raise an IndexError
  • Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow condition – Time Complexity: O(1)

  • Dequeue: Removes an item from the queue. The items are popped in the same order in which they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time Complexity: O(1)

  • Front: Get the front item from queue – Time Complexity: O(1)

  • Rear: Get the last item from queue – Time Complexity: O(1)

Heap

Using Heapq

It supports the extraction and insertion of the smallest element in the O(log n) times.

# importing "heapq" to implement heap queue 
import heapq

# initializing list 
li = [5, 7, 9, 1, 3]

# using heapify to convert list into heap 
heapq.heapify(li)

# printing created heap 
print ("The created heap is : ",end="") print (list(li))

# using heappush() to push elements into heap 
# pushes 4 
heapq.heappush(li,4)

# printing modified heap 
print ("The modified heap after push is : ",end="") 
print (list(li))

# using heappop() to pop smallest element 
print ("The popped and smallest element is : ",end="")
print (heapq.heappop(li))

Sources