Python problem solving questions and answers

Are you a Python developer brushing up on your skills before an interview? If so, then this tutorial will usher you through a series of Python practice problems meant to simulate common coding test scenarios. After you develop your own solutions, you’ll walk through the Real Python team’s answers so you can optimize your code, impress your interviewer, and land your dream job!

In this tutorial, you’ll learn how to:

  • Write code for interview-style problems
  • Discuss your solutions during the interview
  • Work through frequently overlooked details
  • Talk about design decisions and trade-offs

This tutorial is aimed at intermediate Python developers. It assumes a basic knowledge of Python and an ability to solve problems in Python. You can get skeleton code with failing unit tests for each of the problems you’ll see in this tutorial by clicking on the link below:

Each of the problems below shows the file header from this skeleton code describing the problem requirements. So download the code, fire up your favorite editor, and let’s dive into some Python practice problems!

Python Practice Problem 1: Sum of a Range of Integers

Let’s start with a warm-up question. In the first practice problem, you’ll write code to sum a list of integers. Each practice problem includes a problem description. This description is pulled directly from the skeleton files in the repo to make it easier to remember while you’re working on your solution.

You’ll see a solution section for each problem as well. Most of the discussion will be in a collapsed section below that. Clone that repo if you haven’t already, work out a solution to the following problem, then expand the solution box to review your work.

Problem Description

Here’s your first problem:

Sum of Integers Up To n [integersums.py]

Write a function, add_it_up[], that takes a single integer as input and returns the sum of the integers from zero to the input parameter.

The function should return 0 if a non-integer is passed in.

Remember to run the unit tests until you get them passing!

Problem Solution

Here’s some discussion of a couple of possible solutions.

How did writing the solution go? Ready to look at the answer?

For this problem, you’ll look at a few different solutions. The first of these is not so good:

# integersums.py
def first[n]:
    num = 1
    sum = 0
    while num >>

>>> import string
>>> x = string.ascii_lowercase
>>> x
'abcdefghijklmnopqrstuvwxyz'
>>> x[3:]
'defghijklmnopqrstuvwxyz'
>>> x[:3]
'abc'

You can see that x[3:] is all the letters after the third letter, 'c', while x[:3] is just the first three letters.

Line 6 in the solution, letters[shift_num:] + letters[:shift_num], creates a list of letters shifted by shift_num letters, with the letters at the end wrapped around to the front. Once you have the list of letters and the mask of letters you want to map to, you call .maketrans[] to create a translation table.

Next, you pass the translation table to the string method .translate[]. It maps all characters in letters to the corresponding letters in mask and leaves all other characters alone.

This question is an exercise in knowing and using the standard library. You may be asked a question like this at some point during an interview. If that happens to you, it’s good to spend some time thinking about possible answers. If you can remember the method—.translate[] in this case—then you’re all set.

But there are a couple of other scenarios to consider:

  1. You may completely draw a blank. In this case, you’ll probably solve this problem the way you solve the next one, and that’s an acceptable answer.

  2. You may remember that the standard library has a function to do what you want but not remember the details.

If you were doing normal work and hit either of these situations, then you’d just do some searching and be on your way. But in an interview situation, it will help your cause to talk through the problem out loud.

Asking the interviewer for specific help is far better than just ignoring it. Try something like “I think there’s a function that maps one set of characters to another. Can you help me remember what it’s called?”

In an interview situation, it’s often better to admit that you don’t know something than to try to bluff your way through.

Now that you’ve seen a solution using the Python standard library, let’s try the same problem again, but without that help!

Python Practice Problem 3: Caesar Cipher Redux

For the third practice problem, you’ll solve the Caesar cipher again, but this time you’ll do it without using .translate[].

Problem Description

The description of this problem is the same as the previous problem. Before you dive into the solution, you might be wondering why you’re repeating the same exercise, just without the help of .translate[].

That’s a great question. In normal life, when your goal is to get a working, maintainable program, rewriting parts of the standard library is a poor choice. The Python standard library is packed with working, well-tested, and fast solutions for problems large and small. Taking full advantage of it is a mark of a good programmer.

That said, this is not a work project or a program you’re building to satisfy a need. This is a learning exercise, and it’s the type of question that might be asked during an interview. The goal for both is to see how you can solve the problem and what interesting design trade-offs you make while doing it.

So, in the spirit of learning, let’s try to resolve the Caesar cipher without .translate[].

Problem Solution

For this problem, you’ll have two different solutions to look at when you’re ready to expand the section below.

For this problem, two different solutions are provided. Check out both and see which one you prefer!

Solution 1

For the first solution, you follow the problem description closely, adding an amount to each character and flipping it back to the beginning of the alphabet when it goes on beyond z:

 1# caesar.py
 2import string
 3
 4def shift_n[letter, amount]:
 5    if letter not in string.ascii_lowercase:
 6        return letter
 7    new_letter = ord[letter] + amount
 8    while new_letter > ord["z"]:
 9        new_letter -= 26
10    while new_letter >>

>>> x = 1
>>> x + 3
4
>>> [x + 3] // 3
1
>>> [[x + 3] // 3] * 3
3

Using the rounding of integer math allows you to get the next-highest multiple of three above a given value. Once you have this, subtracting three will give you the multiple of three below the given number.

There are a few more low-level utility functions to examine before you start building on top of them.

Moving to the Next Spot

Your solution will need to walk through the grid structure one cell at a time. This means that at some point, you’ll need to figure out what the next position should be. compute_next_position[] to the rescue!

compute_next_position[] takes the current x- and y-coordinates as input and returns a tuple containing a finished flag along with the x- and y-coordinates of the next position:

# sudokusolve.py
def compute_next_position[x, y]:
    nextY = y
    nextX = [x + 1] % 9
    if nextX 

Chủ Đề