Lists hackerrank solution
Consider a list (list = []). You can perform the following commands:
Initialize your list and read in the value of n followed by n 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
Input FormatThe first line contains an integer, , denoting the number of commands. Each line of the subsequent lines contains one of the commands described above. ConstraintsThe 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 012 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] ExplanationFirst we take the input from the user in the form of lists and append to another list named lists. Now, then we iterate the main list named lists and then check the lists of first element that is equal to which function? {eg: if it equal to insert, print, or ...............etc.}. Also, make a another lists that named arr that contain the elements according to the input given by the user. And then according to function we apply operations. For insert we use insert() function to insert the element in specific position. For print we simply use print() function. For remove we use remove() function to remove given element. For append we use append() function to append elements in the arr lists. For sort we use sort() function. For pop we use pop() function to remove the last element from the list named arr. And, lastly for reverse we use reverse() function to reverse the list. Solution
Consider a list (list = []). You can perform the following commands:
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.
The first line contains an integer, , denoting the number of commands.
For each command of type print, print the list on a new line.
12 insert 0 5 insert 1 10 insert 0 6 print remove 6 append 9 append 1 sort print pop reverse print
[6, 5, 10] [1, 5, 9, 10] [9, 5, 1]
We can solve this using list methods and conditionals.
arr = [] for i in range(int(raw_input())): s = raw_input().split() for i in range(1,len(s)): s[i] = int(s[i]) if s[0] == "append": arr.append(s[1]) elif s[0] == "extend": arr.extend(s[1:]) elif s[0] == "insert": arr.insert(s[1],s[2]) elif s[0] == "remove": arr.remove(s[1]) elif s[0] == "pop": arr.pop() elif s[0] == "index": print arr.index(s[1]) elif s[0] == "count": print arr.count(s[1]) elif s[0] == "sort": arr.sort() elif s[0] == "reverse": arr.reverse() elif s[0] == "print": print arr |