Python Interview Questions
These Python interview questions will challenge your algorithmic thinking skills as well as your Python programming skills. The first few questions are more Python-specific, and then we have a bunch of general data structures and algorithms questions in Python
When should you not use a list comprehension?
Slicing lists from the end
We want to run some analytics on our investments. To start, we're given a list containing the balance at the end of the day for some number of days. The last item in the list represents yesterday's closing balance and each previous item refers to the day before.
daily_balances = [107.92, 108.67, 109.86, 110.15]
Python 2.7The first step in the process is to grab adjacent items in the list. To get started, we want a function that takes in our list of daily_balances and prints pairs of adjacent balances for the last 3 days:
show_balances(daily_balances)
Python 2.7should print:
"slice starting 3 days ago: [108.67, 109.86]"
"slice starting 2 days ago: [109.86, 110.15]"
Python 2.7We just hired a new intern, Dan, to help us with this but something doesn't seem to be working quite right. Here's his function:
def show_balances(daily_balances):
# do not include -1 because that slice will only have 1 balance, yesterday
for day in range(-3, -1):
balance_slice = daily_balances[day : day + 2]
# use positive number for printing
print("slice starting %d days ago: %s" % (abs(day), balance_slice))
Python 2.7What's his code is printing, and how can we fix it?
Count Capital Letters
Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory.
Assume you have an open file handle object, such as:
with open(SOME_LARGE_FILE) as fh:
count = # your code here
Python 2.7Rest assured—there is a clean, readable answer!
Best in Subclass
When I was younger, my parents always said I could have pets if I promised to take care of them. Now that I'm an adult, I decided the best way to keep track of them is with some Python classes!
class Pet(object):
num_pets = 0
def __init__(self, name):
self.name = name
self.num_pets += 1
def speak(self):
print("My name's %s and the number of pets is %d" % (self.name, self.num_pets))
Python 2.7Since these pets won't sit still long enough to be put into a list, I need to keep track with the class attribute num_pets.
That should be enough to get me started. Let's create a few pets:
rover = Pet("rover")
spot = Pet("spot")
Python 2.7and see what they have to say:
rover.speak()
spot.speak()
Python 2.7Hmm... I'm not getting the output I expect. What did these two lines print, and how do we fix it?
When is a number not itself?
Given some simple variables:
big_num_1 = 1000
big_num_2 = 1000
small_num_1 = 1
small_num_2 = 1
Python 2.7What's the output we get from running the following?
big_num_1 is big_num_2
small_num_1 is small_num_2
Python 2.7Here's a hint
Here at Interview Cake, we've decided to keep all our interview questions inside Python dictionaries. We have a default template to get us started:
question_template = {
"title": "default title",
"question": "default question",
"answer": "default answer",
"hints": []
}
Python 2.7and a function to help us populate new questions:
def make_new_question(title, question, answer, hints=None):
new_q = question_template.copy()
# always require title, question, answer
new_q["title"] = title
new_q["question"] = question
new_q["answer"] = answer
# sometimes there aren't hints, that's fine. Otherwise, add them:
if hints is not None:
new_q["hints"].extend(hints)
return new_q
Python 2.7Then we added a few questions (abbreviated for simplicity):
question_1 = make_new_question("title1", "question1", "answer1", ["q1 hint1", "q1 hint2"])
question_2 = make_new_question("title2", "question2", "answer2")
question_3 = make_new_question("title3", "question3", "answer3", ["q3 hint1"])
Python 2.7What did we do wrong? How can we fix it?
Generating the Matrix
We want to build a matrix of values, like a multiplication table. The output we want in this case should be a list of lists, like:
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
Python 2.7Trying to keep our code clean and concise, we've come up with a matrix generator:
iterator = (i for i in range(1, 4))
matrix = [[x * y for y in iterator] for x in iterator]
Python 2.7But our output isn't what we expected. Can you figure out what we got instead, and how to fix it?
Implement a queue with two stacks. Assume you already have a stack implementation.
Computer the nth Fibonacci number. Careful--the recursion can quickly spin out of control!
Find the area of overlap between two rectangles. In the name of love.
Write a function that will replace your role as a cashier and make everyone rich or something.
Write a function that finds the corresponding closing parenthesis given the position of an opening parenthesis in a string.
Write a super-simple JavaScript parser that can find bugs in your intern's code.
Write a function to see if a binary tree is 'superbalanced'--a new tree property we just made up.
Write a function to check that a binary tree is a valid binary search tree.
Find the second largest element in a binary search tree. keep reading »
I'm making a new search engine called MillionGazillion(tm), and I need help figuring out what data structures to use. keep reading »
You've hit the mother lode: the cake vault of the Queen of England. Figure out how much of each cake to carry out to maximize profit.
You're building a word cloud. Write a function to figure out how many times each word appears so we know how big to make each word in the cloud.
You've implemented a Stack class, but you want to access the largest element in your stack from time to time. Write an augmented LargestStack class.
In a beautiful Amazon utopia where breakfast is delivered by drones, one drone has gone missing. Write a function to figure out which one is missing.
Write a function to delete a node from a linked list. Turns out you can do it in constant time!
Write a function to reverse a linked list in place.
Find the kth to last node in a singly-linked list. We'll start with a simple solution and move on to some clever tricks.
Write a function to reverse a string in place.
Write a function to reverse the word order of a string, in place. It's to decipher a supersecret message and head off a heist.
Efficiently sort numbers in an array, where each number is below a certain maximum.
Find the repeat number in an array of numbers. Optimize for runtime.
Given an array of numbers in sorted order, how quickly could we check if a given number is present in the array?
I wanted to learn some big words to make people think I'm smart, but I messed up. Write a function to help untangle the mess I made.
Writing a simple recommendation algorithm that helps people choose which movies to watch during flights
Check if any permutation of an input string is a palindrome.
Write a recursive function of generating all permutations of an input string.
Do an in-place shuffle on an array of numbers. It's trickier than you might think!
Write a function to tell us if cafe customer orders are served in the same order they're paid for.
Given a 7-sided die, make a 5-sided die.
Given a 5-sided die, make a 7-sided die.
A building has 100 floors. Figure out the highest floor an egg can be dropped from without breaking.
Figure out which number is repeated. But here's the catch: optimize for space.
Figure out which number is repeated. But here's the catch: do it in linear time and constant space!
Your friend copied a bunch of your files and put them in random places around your hard drive. Write a function to undo the damage.
Figure out the optimal buy and sell time for a given stock, given its prices yesterday.
For each number in an array, find the product of all the other numbers. You can do it faster than you'd think!
Find the highest possible product that you can get by multiplying any 3 numbers from an input array. keep reading »
Write a function for merging meeting times given everyone's schedules. It's an enterprise end-to-end scheduling solution, dog. keep reading »
Write code to continually track the max, min, mean, and mode as new numbers are inserted into a tracker class.
Design a ticket sales site, like Ticketmaster
Comments
Post a Comment