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! Show
In this tutorial, you’ll learn how to:
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 IntegersLet’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 DescriptionHere’s your first problem:
Remember to run the unit tests until you get them passing! Problem SolutionHere’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:
In this solution, you manually build a This solution works, but it has two problems:
You’ll deal with the error conditions in the final answer below, but first let’s refine the core solution to be a bit more Pythonic. The first thing to think about is
that
You can see that the This was a nice step! It removes some of the boilerplate code of looping over a range and makes your intention clearer. But there’s still more you can do here. Summing a list of integers is another thing Python is good at:
Wow! By using the built-in There’s one problem remaining, however. This code still doesn’t handle the error conditions correctly. To fix that, you can wrap your previous code in a
This solves the problem and handles the error conditions correctly. Way to go! Occasionally,
interviewers will ask this question with a fixed limit, something like “Print the sum of the first nine integers.” When the problem is phrased that way, one correct solution would be If you give this answer, however, then you should follow up with code that solves the problem step by step. The trick answer is a good place to start your answer, but it’s not a great place to end. If you’d like to extend this problem, try adding an optional lower limit to Python Practice Problem 2: Caesar CipherThe next question is a two-parter. You’ll code up a function to compute a Caesar cipher on text input. For this problem, you’re free to use any part of the Python standard library to do the transform. Problem DescriptionThe problem statement is at the top of the skeleton source file:
Remember, this part of the question is really about how well you can get around in the standard library. If you find yourself figuring out how to do the transform without the library, then save that thought! You’ll need it later! Problem SolutionHere’s a solution to the Caesar cipher problem described above. This solution makes use of Okay, now that you’re ready, let’s look at this solution:
You can see that the function makes use of three things from the
In the first two lines, you create a variable with all the lowercase letters of the alphabet (ASCII only for this program) and then create a >>>
You can see that Line 6 in the solution, Next, you pass the translation table to the string method 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— But there are a couple of other scenarios to consider:
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 ReduxFor the third practice problem, you’ll solve the Caesar cipher again, but this time you’ll do it without using Problem DescriptionThe 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 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 Problem SolutionFor 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 1For 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
Starting on line 14, you can see that Here you can see another use for
Again, you’re encouraged not only to learn these functions but also to consider how you might respond in an interview situation if you couldn’t remember their names.
The first step of your encoding on line 7 gets the numeric value of the encoded letter by using For many letters with small shift values, you can convert the letter back to a character and you’ll be done. But consider the starting letter, A shift of one character should result in the letter You do this in lines 8 to 11 by repeatedly adding 26 to or subtracting it from the character until it’s in the range of ASCII characters. Note that this is a fairly inefficient method for fixing this issue. You’ll see a better solution in the next answer. Finally, on line 12, your conversion shift function takes the numeric value of the new letter and converts it back to a letter to return it. While this solution takes a
literal approach to solving the Caesar cipher problem, you could also use a different approach modeled after the Solution 2The second solution to this problem mimics the behavior of Python’s
built-in method
Starting with The
mod operator produces the remainder from an integer division. In this case, you divide by Next, you create the translation table. This is a change from the previous solutions and is worth some attention. You’ll see more about this toward the end of this section. Once you create the
Now let’s discuss the table creation issue. For this toy example, it probably doesn’t matter too much, but it illustrates a situation that occurs frequently in everyday development: balancing clarity of code against known performance bottlenecks. If you examine the code again, you’ll see that
The issue with that approach is that it spends time calculating the same table for every letter of the message. For small messages, this time will be negligible, but it might add up for larger messages. Another possible way that you could avoid this performance penalty would be to make At the end of the day, the choice between creating If this is a small project and you know it will be used to encode large messages, then creating the table only once could be the right decision. If this is only a portion of a larger project, meaning maintainability is key, then perhaps creating the table each time is the better option. Since you’ve looked at two solutions, it’s worth taking a moment to discuss their similarities and differences. Solution ComparisonYou’ve seen two solutions in this part of the Caesar cipher, and they’re fairly similar in many ways.
They’re about the same number of lines. The two main routines are identical except for limiting The first Although it’s about
the same length as the second version, the first version of The first version of the function is also specific to solving this particular problem. The second version of One of the mantras that came out of the Extreme Programming movement is “You aren’t gonna need it” (YAGNI). Frequently, software developers will look at a function like While that would indeed make the function more general-purpose, it would also make it more complex. The YAGNI mantra is there to remind you not to add complexity before you have a specific use case for it. To wrap up your Caesar cipher section, there are clear trade-offs between the two solutions, but the second Now that you’ve written the Caesar cipher three different ways, let’s move on to a new problem. Python Practice Problem 4: Log ParserThe log parser problem is one that occurs frequently in software development. Many systems produce log files during normal operation, and sometimes you’ll need to parse these files to find anomalies or general information about the running system. Problem DescriptionFor this problem, you’ll need to parse a log file with a specified format and generate a report:
Note that the provided skeleton code doesn’t include unit tests. This was omitted since the exact format of the report is up to you. Think about and write your own during the process. A
While that format is generated by the Real Python solution, you’re free to design your own format for the output. The sample input file should generate equivalent information. Problem SolutionIn the collapsed section below, you’ll find a possible solution to the log parser problem. When you’re ready, expand the box and compare it with what you came up with! Full SolutionSince this solution is longer than what you saw for the integer sums or the Caesar cipher problems, let’s start with the full program:
That’s your full solution. You can see that the program consists of three functions and the main section. You’ll work through them from the top. Helper Function:
|