Python »Problems with Python practice. Prepare for your next interview

Are you a Python developer honing your skills before your interview? If so, this article will walk you through a series of practical Python tasks designed to simulate common coding testing scenarios. After developing your own solutions, you will be guided through the answers so you can optimize your code, impress the interviewer, and get your dream job!

In this article, you will learn how to:

  • Write code for interview-style tasks
  • Discuss your decisions during the interview
  • Work on overlooked details
  • Talk about design decisions and trade-offs

This article is intended for intermediate Python developers.

Python Practice 1: Sum of a Range of Integers

Let’s start with a warm-up. In the first practice task, you will write code to add a list of integers. Each practice task includes a description of the problem. This description is fetched directly from the skeleton files in the repository to make it easier to remember while you work on your solution.

Description of the problem

Here’s your first problem:

# integersums.py
""" Sum of Integers Up To n
    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.
"""

Solution

For this problem, you will consider several different solutions. The first one is not that good:

# integersums.py
def first(n):
    num = 1
    sum = 0
    while num < n + 1:
        sum = sum + num
        num = num + 1
    return sum

In this solution, you manually create a while loop to execute through 1n numbers. You keep running sum and then return it when you finish the loop.

This solution works, but it has two problems:

  1. It does not represent your knowledge of Python and how the language simplifies such tasks.
  2. It does not meet the error conditions in the problem description. Passing a string will cause the function to throw an exception when it should just return.

You will be dealing with error conditions in the final answer below, but first, let’s refine the main solution to be a little more Pythonic.

The first thing to think about while is a loop. Python has powerful mechanisms for iterating over lists and ranges. Creating your own is usually not required and this is certainly the case here. You can replace the while loop with a loop that repeats range ():

# integersums.py
def better(n):
    sum = 0
    for num in range(n + 1):
        sum += num
    return sum

You can see that the for… range () construct has replaced your while loop and shortened the code. One thing to note is that range () goes up but does not include the given number, so you need to use n + 1 here.

It was a good move! It removes some of the boilerplate range looping code and makes your intent more clear. But you can do even more here.

Summing up a list of integers is another thing Python is good at:

# integersums.py
def even_better(n):
    return sum(range(n + 1))

Wow! Using the built-in sum () module, you got it down to one line of code! While code golf usually doesn’t produce the most readable code, in this case you have a win-win: shorter, more readable code.

However, one problem remains. This code still doesn’t handle error conditions correctly. To fix this, you can wrap your previous code in a try … except block:

# integersums.py
def add_it_up(n):
    try:
        result = sum(range(n + 1))
    except TypeError:
        result = 0
    return result

This solves the problem and handles error conditions correctly.

Sometimes interviewers ask this question with a fixed limit, something like “print the sum of the first nine integers. “When the problem is formulated this way, one correct solution would be print (45).

However, if you provide this answer, then you should continue with the code that solves the problem step by step. The answer to the trick is a good place to start your answer, but it is not the best place to end.

If you want to expand on this problem, try adding an additional lower limit add_it_up () to give it more flexibility!

Python Practice 2: The Caesar Cipher

The next question has two parts. You will create a function code to calculate the Caesar cipher as you enter text. For this problem, you can use any part of the Python standard library for conversion.

Hint: There is a function in the str class that makes this task much easier!

Description of the problem

# caesar.py
""" Caesar Cipher
    A Caesar cipher is a simple substitution cipher in which each letter of the
    plain text is substituted with a letter found by moving n places down the
    alphabet. For example, assume the input plain text is the following:

        abcd xyz

    If the shift value, n, is 4, then the encrypted text would be the following:

        efgh bcd

    You are to write a function that accepts two arguments, a plain-text
    message and a number of letters to shift in the cipher. The function will
    return an encrypted string with all letters transformed and all
    punctuation and whitespace remaining unchanged.

    Note: You can assume the plain text is all lowercase ASCII except for
    whitespace and punctuation.
"""

Remember, this part of the question is really about how well you can work with the standard library. If you understand how to do the conversion without a library, keep that thought! You will need it later!

Solution

Here is a solution to the Caesar cipher problem described above.

This solution uses the .translate () class from the standard library. If you’ve been struggling with this problem, then you might want to pause and think about how you could use .translate () it in your solution.

Ok, now that you’re ready, let’s go over this solution:

 1 # caesar.py
 2 import string
 3 
 4 def caesar(plain_text, shift_num=1):
 5     letters = string.ascii_lowercase
 6     mask = letters[shift_num:] + letters[:shift_num]
 7     trantab = str.maketrans(letters, mask)
 8     return plain_text.translate(trantab)

You can see that the function uses three things from the string module:

  1. .ascii_lowercase
  2. .maketrans ()
  3. .translate ()

In the first two lines, you create a variable with all lowercase letters of the alphabet (ASCII for this program only), and then you create an amask, which is the same set of letters, just shifted. The slicing syntax is not always obvious, so let’s look at it in a real world example:

>>>

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

You can see that x[3:] these are all letters after the third letter ‘c’, while x[:3] as it is only the first three letters.

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

Then you pass the translation table to the string method .translate (). It matches all characters to letters with the corresponding mask letters and leaves all other characters alone.

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

But there are several other scenarios to consider:

  1. You can paint the void completely. In this case, you will probably solve this problem in the same way as the next one, and this is 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 a normal job and got into any of these situations, then you would just do a little research and hit the road. But in an interview situation, it will help your case speak out loud about the issue.

Asking the interviewer for specific help is much better than ignoring it. Try something like, “I think there is a function that maps one set of characters to another. Could 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.

To be continued…

Sidebar