Hackerrank:- List Discussion Question( with Two Solutions)

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

  1. insert i e: Insert 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: Pop 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.



Solution:1:-'''if __name__ == '__main__':

    N = int(input())
    result = []
    for n in range(N):
        x = input().split(" ")
        command = x[0]
        if command == 'append':
            result.append(int(x[1]))
        if command == 'print':
            print(result)
        if command == 'insert':
            result.insert(int(x[1]), int(x[2]))
        if command == 'reverse':
            result == result[::-1]
        if command == 'pop':
            result.pop()
        if command == 'sort':
            result == sorted(result)
        if command == 'remove':
            result.remove(int(x[1]))
        print(result)'''


Solution 2:-if __name__ == '__main__':
    N = int(input())
    
    list=[]
    for i in range(N):
        a=input().split()
        for i in range(1,len(a)):
            a[i]=int(a[i])
        if a[0]=="insert":
            list.insert(a[1],a[2])
        elif a[0]=="print":
            print(list)
        elif a[0]=="remove":
            list.remove(a[1])
        elif a[0]=="append":
            list.append(a[1])
        elif a[0]=="sort":
            list.sort()
        elif a[0]=="pop":
            list.pop()
                       
            
        elif a[0]=="reverse":
            list.reverse()
        
            
                       
            
     
        
        

    
    

    
    





Comments

Popular posts from this blog

XAMPP, SQL BASIC COMMANDS

The Minion Game Hackerrank Solution

Arrays - DS | HackerRank Solutions