Best Way to Solve Python Coding Questions | by Luay Matalka | Towards Data Science

There is certainly some controversy regarding the benefits of Python coding websites such as codewars or leetcode, and whether or not using them actually makes us better programmers. Despite that, many people still use them to prepare for Python interview questions, keeping their Python programming skills sharp, and/or just for fun. Nevertheless, there’s definitely a place for these resources for any Python programmer or data scientist.
In this tutorial, we’ll look at the best way to extract the most utility out of these python coding problems. We will look at a fairly simple Python coding question and work through the proper steps to solve it. This includes first coming up with a plan or outline using pseudocode, and then solving it in different ways starting with the simplest solution.
We need to write a function that takes a single integer value as input, and returns the sum of the integers from zero up to and including that input. The function should return 0 if a non-integer value is passed in.
So if we pass in the number 5 to the function, then it would return the sum of the integers 0 through 5, or (0+1+2+3+4+5), which equals 15. If we pass in any other data type other than an integer, such as a string, or float, etc... the function should return 0.
towardsdatascience.com
The first thing we should do is solve this problem using pseudocode. Pseudocode is just a way to plan out our steps without worrying about the coding syntax.
We can try something like this:
def add(num):    # if num is an integer then        # add the integers 0 through num and return sum        # if num is not an integer then return 0Sample inputs/outputs:# input: 5, output: 15# input: 'and', output: 0
We defined a function, add, that takes in an input, num. Within the add function, we write an outline of steps using comments. If the value passed to the function is an integer, then we will add the integers 0 through that value, and then return the sum. If the value passed to the function is not an integer, then we simply return 0. After that, we write a few examples of what we want our output to be given a specific input.
Let’s expand on this step in the pseudocode above:
# add the integers 0 through num and return sum
This step can be done in many ways. What would the pseudocode look like if we attempt this step using a for loop?
def add(num):    # if num is an integer then# create sum variable and assign it to 0# using a for loop, loop over integers 0 to num# update sum value by adding num to it# return sum# if num is not an integer then return 0
Let’s try solving it based on the blueprint we created above!
We can solve this prompt using a for loop as follows:
def add(num):    # if num is an integer then    if type(num) == int:# create sum variable and assign it to 0        sum = 0# using a for loop, loop over integers 0 to num        for x in range(num+1):# update sum value             sum += x# return sum        return sum# if num is not an integer then return 0    else:        return 0
We first check if the value passed in, num, is an integer using the type function.
if type(num) == int:
If the type is an integer, we create a sum variable and assign it the value 0.
sum = 0
We then loop over the integers starting from 0 through the integer passed in to our function using a for loop and the range function. Remember that the range function creates a range object, which is an iterable object, that starts at 0 (if we don’t specify a start value), and goes to the integer less than the stop value (since the stop value is exclusive). That is why we need to add 1 to the stop value (num+1), since we want to add up all the integers from 0 up to and including that number, num.
range(start, stop[, step])
The range function will create a range object, which is an iterable object, and thus we can use a for loop to loop through it. As we are looping through this iterable object, we are adding each number, or x, to the sum variable.
for x in range(num+1):    sum += x
Then after the for loop iterations are complete, the function returns the sum.
return sum
Lastly, if the number passed in is not an integer, we return 0.
else:    return 0
This is the code without the comments:
def add(num):    if type(num) == int:        sum = 0        for x in range(num+1):            sum += x        return sum    else:        return 0
If we test our add function, we get the correct outputs:
add(5) # 15add('and')# 0
This is a good way to solve this coding problem and it gets the job done. It is easy to read and works correctly. But, in my opinion, by trying to solve this question in other ways, we can perhaps extract more value from it by utilizing our other python knowledge along with our problem-solving skills. These other ways may or may not be more pythonic, but it can be quite fun and useful to think of different ways to solve the same problem.
Let’s try to solve this coding question in a different way.
For more information on iterable objects:
towardsdatascience.com
We recently learned what the reduce function does in a previous tutorial. The reduce function takes an iterable object and reduces it down to a single cumulative value. The reduce function can take in three arguments, two of which are required. The two required arguments are: a function (that itself takes in two arguments), and an iterable object.
We can use the reduce function to find the sum of an iterable object.
Thus, instead of a for loop, we can use reduce to solve our Python problem:
from functools import reducedef add(num):    if type(num) == int:        return reduce(lambda x,y: x+y, range(num+1))    else:        return 0
And that’s it! We use a lambda function as the function argument and the range object as our iterable object. The reduce function then reduces our range object down to a single value, the sum. And then we return that sum.
For more information about the reduce function:
towardsdatascience.com
We can shorten our code even more by using ternary operators. Using ternary operators, we can shorten our if/else statement above into one line using the following format:
x if C else y
C is our condition, which is evaluated first. If it evaluates to True, then x is evaluated and its value will be returned. Otherwise, y is evaluated and its value is returned.
We can implement this into our code as follows:
def add(num):    return reduce(lambda x,y: x+y, range(num+1)) if type(num) == int else 0
And through these changes, we managed to reduce the code within our function down to a single line. It may not be the most readable or pythonic way of solving this problem, but in my opinion, it helps us improve our coding and problem-solving skills by forcing us to figure out different ways to solve the same problem.
Let’s see if we can solve this coding question in another way.
For more information on ternary operators:
towardsdatascience.com
We can solve this coding question a different way using Python’s built-in sum function. The sum() function can take in an iterable object and returns the sum of its elements. We can also pass in a start value if we want it to be added to the elements first.
sum(iterable, start)
Let’s solve the coding question using the sum function:
def add(num):    return sum(range(num+1)) if type(num) == int else 0
And that’s it! This is likely the best way to solve this coding question, as it is both the most concise and easy to read solution. In addition, it likely will have the best performance as well.
For more information on code performance:
towardsdatascience.com
In this tutorial, we learned that solving a Python problem using different methods can enhance our coding and problem-solving skills by broadening our knowledge base. We looked at an example python coding question and went through the steps of solving it. We first planned how we were going to solve it using pseudocode. Then we implemented this outline of steps by first solving the prompt through the use of a for loop. Later, we solved the same problem using the reduce function. We also implemented ternary operators to shorten our code even further but still maintained readability. Lastly, we used the Python built-in sum function along with ternary operators to come up with the shortest but still most pythonic solution.