Nezir Zahirovic - The Python Interview Handbook 2023 - 112+ Q&A (2023)
Nezir Zahirovic - The Python Interview Handbook 2023 - 112+ Q&A (2023)
Interview
HANDBOOK
Your best guide with Essential
Questions and Answers!
Buy on
1
DEDICATION
To all those who struggle at interviews,
Throughout these pages, you'll find valuable tips and advice to help you
navigate the interview process with confidence. We hope that by reading
this book, you'll gain the skills and insights you need to ace your next
interview and secure the job you've been dreaming of.
So, here's to you, the brave souls who keep pushing forward in the face
of adversity. We salute you and wish you all the best in your interview
journey.
Sincerely,
One of you!
The views and opinions expressed in this book are those of the author
and do not necessarily reflect the official and latest policy or position of
any company, organization, or institution. Any mention of commercial
products, processes, or services within this book does not constitute an
endorsement or recommendation by the author.
The author has taken all reasonable care to ensure that any examples,
code snippets, or technical information provided in this book are accurate
and up to date. However, the author cannot guarantee that the code will
work in all situations and it is the responsibility of the reader to test and
modify the code to meet their specific requirements. The author will not
be held liable for any damages, direct or indirect, arising from the use or
misuse of the code contained in this book.
Finally, the author would like to express their gratitude to all the
contributors, reviewers, and readers of this book. Your feedback,
suggestions, and support have been invaluable in creating this
comprehensive guide to Python interview preparation.
First and foremost, I would like to thank the Python community for
creating and sharing their knowledge and experience, which was
instrumental in the making of this book. Without their contributions and
support, this book would not have been possible.
I would also like to thank my family and friends for their unwavering
support and encouragement throughout this project. Your love and
encouragement kept me motivated and focused during the long hours of
research and writing.
I would also like to thank the team at OpenAI for providing the
technology that powers ChatGPT, the AI language model that assisted in
generating content for this book.
Finally, I would like to thank the readers of this book for their interest in
Python and for considering this handbook as a resource to enhance their
knowledge and skills. I hope this book provides value and helps you in
your journey to becoming a proficient Python developer.
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Example usage:
print(is_prime(17)) # Output: True
print(is_prime(4)) # Output: False
def largest_continuous_sum(numbers):
max_sum = current_sum = numbers[0]
for n in numbers[1:]:
current_sum = max(current_sum + n, n)
max_sum = max(max_sum, current_sum)
return max_sum
# Example usage:
print(largest_continuous_sum([1, -2, 3, 4, -1, 2, -6, 5]))
# Output: 10
The 'is' operator in Python checks if two objects are the same
object (i.e., they have the same memory address), whereas the
'==' operator checks if two objects have the same value. Here's an
example:
def is_palindrome(s):
return s == s[::-1]
# Example usage:
print(is_palindrome('racecar')) # Output: True
print(is_palindrome('hello')) # Output: False
def second_highest(numbers):
numbers = sorted(set(numbers))
return numbers[-2] if len(numbers) >= 2 else None
# Example usage:
print(second_highest([1, 3, 2, 4, 4, 5])) # Output: 4
print(second_highest([1])) # Output: None
def count_vowels(s):
return sum(1 for c in s.lower() if c in 'aeiou')
# Example usage:
print(count_vowels('hello world')) # Output: 3
# Example usage:
print(common_elements([1, 2, 3], [2, 3, 4])) # Output: [2, 3]
class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverse_list(head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
# Example usage:
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
reversed_head = reverse_list(head)
print(reversed_head.data) # Output: 3
print(reversed_head.next.data) # Output: 2
print(reversed_head.next.next.data) # Output: 1
# Example usage:
graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'],
'D': [], 'E': [], 'F': []}
print(shortest_path(graph, 'A', 'F'))
# Output: ['A', 'C', 'F']
# Example usage:
print(intersection([1, 2, 3, 4, 5], [2, 4, 6]))
# Output: [2, 4]
def longest_common_prefix(strings):
if not strings:
return ''
for i, c in enumerate(strings[0]):
for s in strings[1:]:
if i >= len(s) or s[i] != c:
return strings[0][:i]
return strings[0]
# Example usage:
print(longest_common_prefix(['flower', 'flow', 'flight']))
# Output: 'fl'
# Example usage:
print(binary_search([1, 3, 5, 7, 9], 5)) # Output: 2
print(binary_search([1, 3, 5, 7, 9], 2)) # Output: -1
# Example usage:
print(max_sum_subarray([1, 2, 3, 4, 5], 2)) # Output: 9
print(max_sum_subarray([100, 200, 300, 400], 2)) # Output: 700
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.head = None
def pop(self):
if self.head is None:
return None
popped_node = self.head
self.head = self.head.next
popped_node.next = None
return popped_node.data
def is_empty(self):
return self.head is None
# Example usage:
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # Output: 3
print(stack.pop()) # Output: 2
print(stack.is_empty()) # Output: False
class Queue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def dequeue(self):
if not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
if not self.stack2:
return None
return self.stack2.pop()
def is_empty(self):
return not self.stack1 and not self.stack2
# Example usage:
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue()) # Output: 1
print(queue.dequeue()) # Output: 2
print(queue.is_empty()) # Output: False
def longest_increasing_subsequence(numbers):
n = len(numbers)
dp = [1] * n
for i in range(1, n):
for j in range(i):
if numbers[i] > numbers[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
# Example usage:
print(longest_increasing_subsequence(
[10, 9, 2, 5, 3, 7, 101, 18]))
# Output: 4
import heapq
# Example usage:
graph = {
'A': {'B': 1, 'C': 4},
'B': {'A': 1, 'C': 2, 'D': 5},
'C': {'A': 4, 'B': 2, 'D': 1},
'D': {'B': 5, 'C': 1}
}
print(dijkstra(graph, 'A', 'D')) # Output: ['A', 'C', 'D']
# Example usage:
print(longest_common_substring("abcdefg", "defghi"))
# Output: "def"
Buy on
21
23) Write a Python function to check if a given string
is a palindrome.
def is_palindrome(s):
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
# Example usage:
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("hello")) # Output: False
def quicksort(numbers):
if len(numbers) <= 1:
return numbers
pivot = numbers[0]
less = []
greater = []
for number in numbers[1:]:
if number <= pivot:
less.append(number)
else:
greater.append(number)
return quicksort(less) + [pivot] + quicksort(greater)
# Example usage:
print(quicksort([3, 2, 1, 5, 4])) # Output: [1, 2, 3, 4, 5]
import itertools
def permutations(numbers):
return list(itertools.permutations(numbers))
# Example usage:
print(permutations([1, 2, 3]))
# Output: [(1, 2, 3), (1, 3, 2), (2, 1, 3),
# (2, 3, 1), (3, 1, 2), (3, 2, 1)]
# Example usage:
print(merge_sorted_arrays([1, 3, 5], [2, 4, 6]))
# Output: [1, 2, 3, 4, 5, 6]
def max_subarray_sum(arr):
max_sum = 0
current_sum = 0
for num in arr:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
# Example usage:
print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
# Output: 6
def first_non_repeating_char(s):
count = {}
for char in s:
count[char] = count.get(char, 0) + 1
for char in s:
if count[char] == 1:
return char
return None
# Example usage:
print(first_non_repeating_char("hello")) # Output: "h"
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def reverse(self):
previous = None
current = self.head
while current is not None:
next_node = current.next
current.next = previous
previous = current
current = next_node
self.head = previous
def print_list(self):
current = self.head
while current is not None:
print(current.data, end=" ")
current = current.next
print()
# Example usage:
print(binary_search([1, 2, 3, 4, 5], 3)) # Output: 2
print(binary_search([1, 2, 3, 4, 5], 6)) # Output: -1
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
# Example usage:
arr = [3, 1, 4, 2, 5]
print(merge_sort(arr)) # Output: [1, 2, 3, 4, 5]
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
# Example usage:
arr = [3, 1, 4, 2, 5]
print(quicksort(arr)) # Output: [1, 2, 3, 4, 5]
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def bfs(root):
if root is None:
return
queue = [root]
while len(queue) > 0:
node = queue.pop(0)
print(node.data, end=" ")
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
# Example usage:
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
bfs(root) # Output: 1 2 3 4 5
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def dfs(root):
if root is None:
return
print(root.data, end=" ")
dfs(root.left)
dfs(root.right)
# Example usage:
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
dfs(root) # Output: 1 2 4 5 3
a = [1, 2, 3]
b = a
a.append(4)
print(b)
30 All rights reserved InterviewBible.com 2023
36) What is the output of the following code?
a = "hello"
b = a
a += " world"
print(b)
The output is [1, 2, 3]. The [:] slice notation creates a new copy of
the list, so b refers to a different list than a. Modifying a does not
affect b.
a = [1, 2, 3]
b = a[:]
a.append(4)
print(b)
a = 5
b = 10
a, b = b, a
print(a, b)
The output is [1, 2, 3]. The copy() method creates a new copy of
the list, so b refers to a different list than a. Modifying a does not
affect b.
a = [1, 2, 3]
b = a.copy()
a.append(4)
print(b)
a = [1, 2, 3]
b = a
a = [4, 5, 6]
print(b)
a = "hello"
a[0] = "H"
print(a)
The output is still [1, 2, 3]. The + operator creates a new list, but
does not modify the original lists a and b.
a = [1, 2, 3]
b = [4, 5, 6]
a + b
print(a)
The output is [1, 2, 3, 4]. b and c are just references to the same
list as a,
a = [1, 2, 3]
b = a
c = b
a.append(4)
print(c)
The output is True and False. The == operator checks if the values
of a and b are equal, which they are, but the is operator checks if
they are the same object, which they are not.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
a = "hello"
b = a
a = a.upper()
print(b)
a = [1, 2, 3]
a *= 2
print(a)
The output is True and False. The == operator checks if the values
of a and b are equal, which they are, but the is operator checks if
they are the same object, which they are not.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
This code will raise a KeyError because "pear" is not a key in the
dictionary a.
a = "hello"
b = a
a += " world"
print(a is b)
a = [1, 2, 3]
b = a[:]
c = a
a.append(4)
print(b)
print(c)
There are two types of APIs in Python: the built-in Python API, which
provides access to Python's built-in functions and modules, and
third-party APIs, which are created by other developers and provide
access to external services and systems.
Some popular third-party APIs in Python include the Twitter API, the
Google Maps API, the Stripe API for payment processing, and the
OpenWeatherMap API for weather data.
REST API is more lightweight and simpler than SOAP API, and uses
HTTP requests and JSON or XML data formats. SOAP API, on the
other hand, uses XML messages and more complex protocols, and
is often used for more enterprise-level applications.
46
Django - a high-level web framework for building web
applications in Python, providing tools for handling routing,
templating, authentication, and more.
Flask - a lightweight web framework for building web
applications in Python, providing a simple and flexible API for
handling requests and responses.
Pillow - a library for working with images in Python, providing
tools for opening, manipulating, and saving images in various
file formats.
Pygame - a library for building games and other multimedia
applications in Python, providing tools for handling input,
graphics, sound, and more.
OpenCV - a library for computer vision and machine learning in
Python, providing tools for image and video processing, object
detection and tracking, and more.
NLTK - a library for natural language processing with Python,
providing tools for tokenization, stemming, tagging, parsing,
and more.
Flask-RESTful - a library for building RESTful APIs in Python
using the Flask framework, providing tools for defining
endpoints, handling requests and responses, and more.
Celery - a library for distributed task scheduling and
management in Python, providing tools for running tasks
asynchronously and in parallel across multiple nodes.
Gunicorn - a library for running Python web applications behind
a reverse proxy server, providing tools for handling multiple
worker processes and managing server resources.
SQLAlchemy - a library for working with databases in Python,
providing tools for defining and querying database tables,
managing transactions, and more.
47
74) What are some common design patterns used in
Python, and can you explain how they are used?
# Answer
lst = [1, 2, 3, 3, 4, 4, 4, 5]
count_4 = lst.count(4)
print(count_4)
# Output: 3
# Answer
s = " hello world "
no_whitespace_s = s.replace(" ", "")
print(no_whitespace_s)
# Output: "helloworld"
# Answer
import os
cwd = os.getcwd()
print(cwd)
# Answer
nested_lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_lst = [item for sublist in nested_lst for item
in sublist]
print(flattened_lst)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Answer
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
print(is_prime(7)) # True
print(is_prime(12)) # False
# Answer
from datetime import datetime
date_str = "2023-05-12"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(date_obj)
# Output: 2023-05-12 00:00:00
# Answer
lst = [1, 2, 3, 3, 4, 4, 5]
unique_lst = list(set(lst))
print(unique_lst)
# Output: [1, 2, 3, 4, 5]
# Answer
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False
# Answer
lst = [1, 2, 3, 4, 5]
reversed_lst = lst[::-1]
print(reversed_lst)
# Output: [5, 4, 3, 2, 1]
You can use a recursive function that checks if each element in the
list is itself a list, and if so, calls the function on that sublist.
Example code:
def flatten(lst):
flat_list = []
for item in lst:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
my_string = "12345"
if my_string.isdigit():
print("The string contains only digits.")
else:
print("The string contains non-digit characters.")
You can use the sorted function with a lambda function that
extracts the value of the key you want to sort on. Example code:
You can create a new list with only the unique elements by
converting the original list to a set and then back to a list. Example
code:
my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
unique_list = list(set(my_list))
print(unique_list) # Output: [1, 2, 3, 4, 5]
s = "Hello, world!"
if "world" in s:
print("Substring found!")
else:
print("Substring not found.")
a = [1, 2, 3, 3, 4, 4, 5]
a = list(set(a))
print(a)
# Output: [1, 2, 3, 4, 5]
a = [1, 2, 3]
b = a
b.append(4)
print(a)
# [1, 2, 3, 4]
a = [1, 2, 3, 4, 5]
print(len(a))
# Output: 5
a = []
if not a:
print("List is empty.")
else:
print("List is not empty.")
s = "hello"
a = list(s)
print(a)
s = "hello"
s = s[::-1]
print(s)
# Output: olleh
import os
filename = "file.txt"
if os.path.exists(filename):
print("File exists!")
else:
print("File does not exist.")
The '==' operator in Python checks whether two objects have the
same value. The 'is' operator, on the other hand, checks whether
two objects are the same object in memory.
However, keep in mind that during your interview, you may be asked to
solve some other job specific coding challenges or whiteboard problems,
or to discuss your past projects and experience. It's important to be
adaptable and flexible, and to showcase your problem-solving skills and
ability to work collaboratively with others.
Finally, remember that interviews are not just about technical knowledge,
but also about communication and interpersonal skills. Make sure to be
friendly, engaging, and confident, and to listen carefully to your
interviewer's questions and feedback. By doing so, you'll not only
impress your interviewer, but also demonstrate your ability to work well
with others and be a valuable asset to any team.
In conclusion, we hope that this book has been helpful in preparing you
for your Python interview. Remember to stay calm, focused, and
confident, and to showcase your skills and experience to the best of your
ability. With the right preparation and mindset, you'll be well on your way
to landing your dream job as a Python developer. Good luck!
64