Python list operations 2 hackerrank Solution
Ngày đăng:
08/01/2022
Trả lời:
0
Lượt xem:
230
Consider a list (list = []). You can perform the following commands:
Initialize your list and read in the value offollowed bylines of commands where each command will be of thetypes listed above. Iterate through each command in order and perform the corresponding operation on your list. Input Format The first line contains an integer,, denoting the number of commands. Each lineof thesubsequent lines contains one of the commands described above. Constraints
Output Format For each command of typeprint, 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] Lists - Hacker Rank SolutionWe can solve this using list methods and conditionals. Problem Tester's code: 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 |