Lists in python - HackerRank solution

Solution for hackerRank problem Lists in python

Problem 

Consider a list (list=[ ]). You can perform the following commands:

  1. Insert i  e :  integer at position.
  2. Print : Print the list.
  3. Remove e : Delete the first occurrence of integer.
  4. Append e : Insert integer at the end of the list.
  5. Sort : Sort the list.
  6. Pop : Remove the last element from the list.
  7. 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

print





  • 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

The first line contains an integer, n, denoting the number of commands.
Each line i of the subsequent n 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]

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

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

What's your name, Tuple - HackerRank solution in python