Table of Contents
Image by Author
Almost all interviews for data science roles include up to two rounds of coding to test a candidate’s problem solving skills. So even if you have an impressive project portfolio, you’ll have to clear the initial coding interview rounds to progress further.
Choosing a language like Python—to tackle coding interviews—can be very helpful as it’s much simpler to learn and use than languages like C++ and Java. In this guide, we’ll go over useful Python tips for coding interviews.
We’ll cover reversing and sorting arrays, customizing array sorts, list and dictionary comprehensions, unpacking iterables, and more. Let’s dive right in!
In any coding interview, you’ll have questions on arrays. In Python, lists provide the same functionality as arrays. You can do the following:
- Look up the element at a particular index in constant time.
- Append to the end of the list and remove items from the end of the list in constant time.
- Insert an element at a particular index in O(n) time.
When you need to reverse a list in place, without creating a new list, you can call the
reverse() method on the list. Here, we initialize the
nums list and call the
reverse() method on it.
nums = [90,23,19,45,33,54] nums.reverse() print(nums)
We see that the original list has been reversed:
Output >> [54, 33, 45, 19, 23, 90]
Another common array operation is sorting. When you need to sort a list in place, you can call the
sort() method on the list object.
nums is also a list of numbers, and calling the
sort() method on
nums sorts the list in place in ascending order:
nums = [23,67,12,78,94,113,47] nums.sort() print(nums)
Output >> [12, 23, 47, 67, 78, 94, 113]
As seen, the
sort() method sorts the list in ascending order by default.
To sort the list in descending order, you can set
True in the
sort() method call:
Output >> [113, 94, 78, 67, 47, 23, 12]
Note: For a list of strings (such as [“plums”,”cherries”,”grapes”]) the default sorting is in alphabetical order. Setting
reverse = True sorts the list of strings in reverse alphabetical order.
Customize Sort with Lambda
Sometimes, you need more customized sorting beyond the trivial ascending and descending order sorts. You can customize the list
sort() by setting the
key parameter to a callable.
As an example, let’s sort the
nums list based on the remainder obtained on dividing by 7.
nums.sort(key=lambda num:num%7) print(nums)
Output >> [113, 78, 23, 94, 67, 47, 12]
To check if the output is correct, let’s create a list of remainders
rem_list = [num%7 for num in nums] print(rem_list)
Output >> [1, 1, 2, 3, 4, 5, 5]
We see that 1 and 5 occur twice in
rem_list. Let’s parse what this means:
- Both 13 and 78 leave a remainder of one when divided by 7. But 13 appears before 78 in the sorted list because it appears before 78 in the original
- Similarly, both 47%7 and 12%7 evaluate to 5. And 47 appears before 12 in the sorted list because it appears before 12 in the original list, too.
sort()method performs a stable sort where the order of the elements in the original list is preserved—if two or more elements are equal under a given sorting criterion. In this case, the criterion is
You can also customize the sorting of lists of strings. Here, we sort the list
str_list based on the number of occurrences of ‘p’:
str_list = ["puppet","trumpet","carpet","reset"] str_list.sort(key=lambda x:x.count('p')) print(str_list)
Output >> ['reset', 'trumpet', 'carpet', 'puppet']
Comprehensions are one of the powerful features of Python that let you write idiomatic code. They let you create new iterables from existing ones and can often be a concise alternative to for loops.
List Comprehension Example
Suppose we have the
nums list. We’d now like to get the list of all numbers in
nums that are divisible by 3. To do so, we can use list comprehension expressions of the form:
[output for item in iterable if condition].
Here, we filter the
nums based on the condition
num%3==0 to get the
nums = [15,12,90,27,10,34,26,77] div_by_3 = [num for num in nums if num%3==0] print(div_by_3)
Output >> [15, 12, 90, 27]
Dictionary Comprehension Examples
Dictionary comprehension is helpful when you need to create a new dictionary from existing iterables instead of using for loops.
These expressions are generally of the form:
key:value for key in some_iterable. Meaning we can access the keys and create the values on the go (from the keys)!
Suppose we want to create a Python dictionary containing the numbers 1 to 10 as the keys and the squares of those numbers as the values. We can do it using dictionary comprehension like so:
squares_dict = i:i**2 for i in range(1,11) print(squares_dict)
We see that we have the numbers and the squares of the numbers as key-value pairs:
Output >> 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100
Here’s another example. From the
strings list, we construct the
str_len dictionary, where keys are the strings and values are the length of these strings:
strings = ["hello","coding","blue","work"] str_len = string:len(string) for string in strings print(str_len)
Output >> 'hello': 5, 'coding': 6, 'blue': 4, 'work': 4
In Python, you can unpack iterables into one or more variables depending on how you’d like to use them. This is especially helpful when you need to use only a subset of the elements for further processing.
Let’s create a list
list1 = [i*2 for i in range(4)] print(list1)
If we want to use all the four elements in
list1, we simply assign it to four different variables as shown:
num1, num2, num3, num4 = list1 print(num1) Output >> 0 print(num2) Output >> 2 print(num3) Output >> 4 print(num4) Output >> 6
If you want only the first elements in the list in a variable, say,
num1 and the remaining elements (sublist) in another variable, say,
num2, you can use * before the variable name so it’ll capture the remaining elements in
num1, *num2 = list1 print(num1) Output >> 0 print(num2) Output >> [2, 4, 6]
Similarly, if you want the first and the last elements in the list, you can unpack as shown below. The elements 2 and 4 are subsumed in the variable
num1, *num2, num3 = list1 print(num1) Output >> 0 print(num2) Output >> [2, 4] print(num3) Output >> 6
Suppose you have a list of strings and the task is to join them into a single string using a separator.
You can use the
join() string method like so:
separator.join(list) will join the elements in the list using the separator.
Here are a few examples. Consider the
fruits list shown:
fruits = ["apples","grapes","berries","oranges","melons"]
To join the strings in the
fruits list using — as the separator, specify ‘–‘ as the separator string:
print('--'.join(fruits)) Output >> 'apples--grapes--berries--oranges--melons'
To join the strings without any white space, use an empty string as the separator:
print(''.join(fruits)) Output >> 'applesgrapesberriesorangesmelons'
To join the strings using a single white space, specify ‘ ‘ as the separator:
print(' '.join(fruits)) Output >> 'apples grapes berries oranges melons'
Let’s use the previous
fruits = ["apples","grapes","berries","oranges","melons"]
You can use the
range function and list index to get the items and index simultaneously:
However, it’s convenient to use the
enumerate() function. You can loop through both the index and the item at the index, simultaneously, using the
for idx,fruit in enumerate(fruits): print(f"At index idx: fruit")
We see that we get the indices 0 to 4 along with the elements are those indices:
Output >> At index 0: apples At index 1: grapes At index 2: berries At index 3: oranges At index 4: melons
By default, the index starts at zero. Sometimes you may want to start at a non-zero index. To do this, you can specify the start index as the second position argument as the second position argument in the
enumerate() function call:
for idx,fruit in enumerate(fruits,1): print(f"At index idx: fruit")
Now the index starts at 1 index instead of zero:
Output >> At index 1: apples At index 2: grapes At index 3: berries At index 4: oranges At index 5: melons
enumerate() allows you to loop through iterables, you can use it inside list and dictionary comprehensions.
For example, you can store the index and the items as keys and values in the dictionary using the
enumerate() function in the dictionary comprehension expression:
idx_dict = idx:fruit for idx,fruit in enumerate(fruits) print(idx_dict) Output >> 0: 'apples', 1: 'grapes', 2: 'berries', 3: 'oranges', 4: 'melons'
Python’s built-in math module comes with out-of-the-box support for common mathematical operations. Here are some functions that will come in handy:
math.ceil() and math.floor()
You’ll often have to round down and round up numbers to the nearest integers; the
ceil() functions in the built-in math module help you do this:
floor()function rounds down a given number to the greatest integer that is less than or equal to the given number. and
ceil()function rounds up the given number to the smallest integer that is greater than or equal to the given number.
Here’s an example:
Image by Author
As 3 is the smallest integer greater than 2.47, ceil(2.47) gives 3:
import math num1 = 2.47 print(math.ceil(num1)) Output >> 3
And as 3 is the greatest integer less than 3.97 so floor(3.97) also gives 3:
num2 = 3.97 print(math.floor(num2)) Output >> 3
math.sqrt() and List Comprehension
To get the square root of a number, you can use the
sqrt() function from the math module. You can use it in conjunction with comprehensions to extend functionality.
Here, we use the
sqrt() function in a list comprehension expression to generate the s
sqrt_nums = [math.sqrt(num) for num in range(1,11)] print(sqrt_nums) Output >> [1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0, 3.1622776601683795]
For a more easily readable output, let’s round the numbers to two decimal places using the built-in
sqrt_nums = [round(math.sqrt(num),2) for num in range(1,11)] print(sqrt_nums) Output >> [1.0, 1.41, 1.73, 2.0, 2.24, 2.45, 2.65, 2.83, 3.0, 3.16]
And that’s a wrap! I hope you found a few useful tips to add to your Python toolbox.
If you’re looking to learn and practice Python, and are interested in integrating ChatGPT into your learning workflow, check out this guide on how to use ChatGPT as a Python Programming Assistant.
Bala Priya C is a technical writer who enjoys creating long-form content. Her areas of interest include math, programming, and data science. She shares her learning with the developer community by authoring tutorials, how-to guides, and more.