Lists in python - HackerRank solution
Solution for hackerRank problem Lists in python
Problem
Consider a list (list=[ ]). You can perform the following commands:
- Insert i e : integer at position.
- Print : Print the list.
- Remove e : Delete the first occurrence of integer.
- Append e : Insert integer at the end of the list.
- Sort : Sort the list.
- Pop : Remove the last element from the list.
- Reverse : Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the 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
- Append 1 : Append to the list, .arr = [1]
- Append 2 : Append to the list, arr = [1, 2]
- Insert 3 1 : Insert 3 at index 1, arr = [1, 3, 2].
- : Print the array.Output:
[1, 3, 2]
Input Format
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
remove 6
append 9
append 1
sort
pop
reverse
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
Code :
#get the number of commands from user
n=int(input())
#create an empty list to perform the commands
ans=[]
for i in range(n):
#Get the command and
arguments
l=list(map(str,input().split()))
#Perform respective
operations
if(l[0]=='append'):
l.remove(l[0])
l=list(map(int,l))
for i in l:
ans.append(i)
if(l[0]=='remove'):
l.remove(l[0])
l=list(map(int,l))
for i in l:
ans.remove(i)
if(l[0]=='insert'):
l.remove(l[0])
l=list(map(int,l))
ans.insert(l[0],l[1])
if(l[0]=='print'):
print(ans)
if(l[0]=='sort'):
ans.sort()
if(l[0]=='pop'):
ans.pop()
if(l[0]=='reverse'):
ans.reverse()
Explanation of the python functions used :
- Append() - Inserts the element to the end of the list.
- Remove() - Removes the element from the user.
- Insert() - Takes two arguments and inserts the 2nd argument at index 2nd argument.
- Print() - Prints the list.
- Sort() - Sorts the elements of the list in ascending order.
- Pop() - Removes the last element in the list.
- Reverse() – Reverses the elements of the list.
Comments
Post a Comment