Table of Contents
Question: Python Lists [Basic Data Types]
Consider a list (list = []
). You can perform the following commands:
- insert i e: Insert integer e at position i.
- print: Print the list.
- remove e: Delete the first occurrence of integer e.
- append e: Insert integer e at the end of the list.
- sort: Sort the list.
- pop: Pop the last element from the list.
- reverse: Reverse the list.
- Initialize your list and read in the value of n followed by n lines of commands where each command will be of the 7 types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Example
N = 4
append 1
append 2
insert 3 1
print
- append 1: Append 1 to the list, arr = [1].
- append 2: Append 2 to the list, arr = [1, 2].
- insert 3 1: Insert 3 at index 1,arr = [1, 3, 2].
- print: Print the array.
Output:
[1, 3, 2]
Input Format:
The first line contains an integer, n
, denoting the number of commands.
Each line i
of the n subsequent lines contains one of the commands described above.
Constraints:
The elements added to the list must be integers.
Output format:
For each command of type print, print the list on a new line.
Sample input 0:
12 insert 0 5 insert 1 10 insert 0 6 print remove 6 append 9 append 1 sort print pop reverse print
Sample output 0:
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
Possible solutions
Now we will discuss the possible solutions to the given problem. The following code is already given in the editor of the Hacker rank:
if __name__ == '__main__':
N = int(input())
Now, let us go through each of the solutions one by one.
Solution-1: Using if statements
Let us solve the problem using if statements:
if __name__ == '__main__':
N = int(input())
l = []
for i in range(N):
s = list(input().split())
if s[0]=='insert':
l.insert(int(s[1]),int(s[2]))
if s[0]=='remove':
l.remove(int(s[1]))
if s[0]=='append':
l.append(int(s[1]))
if s[0]=='sort':
l.sort()
if s[0]=='pop':
l.pop()
if s[0]=='reverse':
l.reverse()
if s[0]=='print':
print(l)
This code is a simple implementation of a list in Python. It uses a loop that iterates N number of times, where N is provided as user input. In each iteration, the program takes a user input as a string, which is split into a list of words using the split() method. The first element of this list, s[0]
, is used to determine the operation to be performed on the list l. If s[0]
is 'insert', the insert()
method is used to insert an element at a given index, with the index and the value to be inserted provided as the next two elements of the list s.
Similarly, the other operations - 'remove', 'append', 'sort', 'pop', 'reverse' and 'print' - are performed on the list based on the value of s[0]
. The final print statement prints the final state of the list after all the operations are performed.
Solution-2: Using map and len()
method
Now we will modify the above solution and use map()
and len()
methods.
if __name__ == '__main__':
N = int(input())
lst = []
for i in range(N):
arr = map(str, input().split())
arr = list(arr)
if len(arr) > 1:
for i in range(1,len(arr)):
if arr[i].isdigit():
arr[i] = int(arr[i])
if arr[0].lower() == 'insert':
lst.insert(arr[1],arr[2])
elif arr[0].lower() == 'print':
print(lst)
elif arr[0].lower() == 'remove':
lst.remove(arr[1])
elif arr[0].lower() == 'append':
lst.append(arr[1])
elif arr[0].lower() == 'sort':
lst.sort()
elif arr[0].lower() == 'pop':
lst.pop()
elif arr[0].lower() == 'reverse':
lst.reverse()
Similar to the first solution, it also uses a loop that iterates N number of times, where N is provided as user input. In each iteration, the program takes a user input as a string, which is converted to a list of strings using the map()
and split()
functions. Then, the code checks if any elements are digits and converts them to integers. Next, the first element of the list, arr[0]
, is used to determine the operation to be performed on the list lst. The operations include 'insert', 'print', 'remove', 'append', 'sort', 'pop' and 'reverse'. The program uses elif statement to check each of these cases and performs the corresponding action on the list. The final print statement prints the final state of the list after all the operations are performed. Additionally, the code also uses lower()
method which converts the first element of the list to lowercase, making the program case-insensitive.
Solution-3: Using the split()
function
We can reduce the number of lines of code using the split function as shown below:
if __name__ == '__main__':
N = int(input())
lst = []
for _ in range(N):
func, *args = input().split()
if func != 'print':
getattr(lst, func)(*map(int, args))
else:
print(lst)
This code is similar to the previous examples in that it is a simple implementation of a list in Python that uses a loop to iterate N number of times, where N
is provided as user input. However, this code uses different methods to perform the same operations on the list. Instead of using if-elif statements to check the operation to be performed, the code uses the getattr()
function which takes an object and a string as arguments, and returns the attribute of the object with the name specified in the string. Here, the lst
object is passed as the first argument, and the string value of the first element of the split input is passed as the second argument. Additionally, the code uses the *
and *args
operator to unpack the remaining elements of the input list, and the map()
function to convert the elements to integers. The print function is handled differently, by using a simple if-else statement. Finally, the code is more concise and efficient, as it avoids using multiple if-elif statements to check the operation to be performed.
Summary
In this short article, we discussed how we can use various methods to solve the Lists problem on Hacker Rank. We covered three different methods to solve the problem.
Further Reading
Question on hacker rank: Python Lists [Basic Data Types]