Learn how to replace items in a Python list by solving basic algorithms a get ready for your next coding interview Show
Update: Many of you contacted me asking for valuable resources to nail Python coding interviews. Below I share 4 courses that I strongly recommend to keep exercising after practicing the algorithms in this post:
Hope you’ll find them useful too! Now enjoy the article :D 3 Data Engineering Courses To Advance Your Career In 2021Join the data industry, change role or simply learn cutting-edge technologies by enrolling in Data Engineering…towardsdatascience.com While preparing for your next Python coding round, you might have noticed that algorithms requiring to manipulate one or more lists appear rather frequently. Sooner or later, you should expect to encounter one of them during your interviews as well.
In order to help you in the process of mastering this data structure and improve your coding skills, below I present 4 methods to replace an item in Python lists as well as four simple algorithms for you to test your skills. Most of the classic interview questions can be solved with multiple approaches, so for each problem, try to come up with your solution first, before looking at the one I provided. Similarly to other skills, algorithmic interview is one area where you can greatly improve with consistent practice. 1. IndexingThe most straightforward way to replace an item in a list is to use indexing, as it allows you to select an item or range of items in an list and then change the value at a specific position, using the assignment operator: For example let’s suppose you were working with the following list including six integers: lst = [10, 7, 12, 56, 3, 14] and you were asked to add 10 to the third integer from the left. Since lists are indexed starting from zero, you could use one of the following syntaxes to change the element with #Option 1 Now try to practice this first method solving the following problem: PROBLEM #1Given a non-empty list including integers ( between 1 and 9) , treat it as it was representing a non-negative unique integer and increment it by one. Return the updated list. In the result, the digits has to be stored such that the first digit of the number obtained by the sum, is at the head of the list, and each element in the list contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself. Note that our input list is made up of four non-negative integers that together represent the integer 9999. This in an edge case, because by adding 1 to this number, you will obtain an integer with 5 digits (instead of the original 4) and a leading 1. To account for these type of situations, the solution takes advantage of two conditional statements that start evaluating the digits from last to first (using Alternatively, if the last digit is a 9, it is replaced by a 0 and the following (second-to-last) digit is evaluated. If this is not equal to 9, then 1 is added and the amended list returned. Otherwise, if each one of following digits is a 9, then the function will return an list with a leading 1 and as many 0s as the number of the elements in the original list. 10 MCQ’s To Practice Before Your Databricks Apache Spark 3.0 Developer ExamYou put the effort. You invested money and time. Now, the exam is close and you only have one attempt…Ready to nail it?anbento4.medium.com 2. For LoopIn the problem above, the goal was to just replace the last integer in the list, incrementing it by 1, whereas iteration was just used to cover the edge cases. In this instances, using a for loop will work fine as it can be employed to iterate over the items of an list. To show how it works, let’s go back to original list and multiply all the integers by 2: lst = [10, 7, 12, 56, 3, 14]for i in range(len(lst)): The example above was elementary, but what if you were asked to apply a slightly more complex logic while replacing items in a list? PROBLEM #2Consider a list of integers. If the number is odd increment it by 1, if it is even increment it by 2. Note that, instead of #Option 10, this solution uses the #Option 11 method to iterate over all the elements of the list, check if the integers are odd or even - through the modulo operator - and replace them by adding 1 or 2 respectively. Enumerate is a built-in function in Python and can be used to add an automatic counter while looping through an iterable object. When the optional #Option 12 parameter is not specified, the counter begins from 0, behaving like it was an actual index. For this reason, it is very common to use #Option 11 to solve algorithms that require you to manipulate a list based on a condition applied to either the index or to (like in this case) the list values.3. List Comprehensions The list comprehension syntax is a more elegant method to loop through the elements of a list and apply some form of manipulation. This is because comprehensions allow you to create a new list in-line, making your code appear very clean and compact. You can convert the for loop in the example above to a comprehension as follows: lst = [10, 7, 12, 56, 3, 14]lst = [lst[i] * 2 for i in range(len(lst))]print(lst)Output: [20, 14, 24, 112, 6, 28] In order to populate the new list, you are also allowed to specify basic conditions as part of list comprehension syntax. This is exactly what you’ll need to do to solve the following algorithm: PROBLEM #3Given a list of integers, sorted in ascending order, return a list also sorted in ascending order including: In this case, the if condition is specified before the #Option 14 because of the presence of an #Option 15 statement. However when the #Option 15 is not required, you can simply follow the syntax: output = [ expression for element in list_1 if condition ] 4. Slicing & ShufflingAt times, in coding interviews, you could be asked to re-arrange the items in a list so that they appear in a different order. This can be achieved through slicing and shuffling. For example if you wished to swap the first 3 and last 3 elements in your initial list, you could write: lst = [10, 7, 12, 56, 3, 14]lst = lst[3:] + lst[:3]print(lst)Output: [56, 3, 14, 10, 7, Perhaps, in this case, talking about a replacement is a bit of a stretch as you are in fact just changing the elements’ position in the list. Nonetheless, this method is quite effective and could help you solve the following problem. PROBLEM #4Given the list of nums consisting of 2n elements in the form [x1,x2,…,xn,y1,y2,…,yn]. Return the array in the form [x1,y1,x2,y2,…,xn,yn]. The exercise provides you with the index to use for slicing (in this case #Option 17) and requires you to shuffle the input list, by creating new integer pairs. The integers belonging to each pair, should be the ones sharing the same index, if we sliced the original list in two sub-lists( #Option 18 and #Option 19) This result can easily be achieved using lst = [10, 7, 12, 56, 3, 14]for i in range(len(lst)):0 to pair together the elements included in the sub-lists and recursively add them to a new lst = [10, 7, 12, 56, 3, 14]for i in range(len(lst)):1 list.Conclusion In this article, I walked you through 4 methods to replace items in a Python list that are indexing, for loops, list comprehensions and slicing-shuffling. Each operation is straightforward per se, but you should be able to master them by choosing the most appropriate and efficient method while solving more complex challenges, in preparation for your next coding round. For this reason, I also presented and shared the solution of 4 algorithms (one for each method) that are representative of the level of complexity you will find while interviewing for junior and mid-level data roles. Also note that the problems presented in this post are slight reinterpretations of problems available on Leetcode. Each problem admits multiple solutions, therefore mines are just indicative ones. A Note For My ReadersThis post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase. |