Hacker rank List Prepare
Question:
This is my Code and it gives me this error message. Why?
if __name__ == '__main__':
l=[]
N = int(input())
for z in range(N):
x=input().split()
if (x[0]=="insert"):
l.insert(int(x[1]),int(x[2]))
elif(x[0]=="print"):
print(l)
elif(x[0]=="remove"):
l.remove(int(x[1]))
elif (x[0]=="append"):
l.append(x[1])
elif(x[0]=="sort"):
l.sort()
elif(x[0])=="pop":
l.pop()
elif(x[0]=="reverse"):
l.reverse()
Error Message – Traceback (most recent call last):
File "/tmp/submission/20220617/03/45/hackerrank-3495035b4042c8bc0c55e799a2d2e687/code/Solution.py", line 15, in
l.sort()
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’
Answers:
You appended string value at x[0] == "append"
.
It should work when you change to l.append(int(x[1])
if __name__ == '__main__':
N = int(input())
myList = []
for i in range(N):
command = input().split()
if command[0] == 'insert':
myList.insert(int(command[1]), int(command[2]))
elif command[0] == 'print':
print(myList)
elif command[0] == 'remove':
myList.remove(int(command[1]))
elif command[0] == 'append':
myList.append(int(command[1]))
elif command[0] == 'sort':
myList.sort()
elif command[0] == 'pop':
myList.pop()
elif command[0] == 'reverse':
myList.reverse()
This is my Code and it gives me this error message. Why?
if __name__ == '__main__':
l=[]
N = int(input())
for z in range(N):
x=input().split()
if (x[0]=="insert"):
l.insert(int(x[1]),int(x[2]))
elif(x[0]=="print"):
print(l)
elif(x[0]=="remove"):
l.remove(int(x[1]))
elif (x[0]=="append"):
l.append(x[1])
elif(x[0]=="sort"):
l.sort()
elif(x[0])=="pop":
l.pop()
elif(x[0]=="reverse"):
l.reverse()
Error Message – Traceback (most recent call last):
File "/tmp/submission/20220617/03/45/hackerrank-3495035b4042c8bc0c55e799a2d2e687/code/Solution.py", line 15, in
l.sort()
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’
You appended string value at x[0] == "append"
.
It should work when you change to l.append(int(x[1])
if __name__ == '__main__':
N = int(input())
myList = []
for i in range(N):
command = input().split()
if command[0] == 'insert':
myList.insert(int(command[1]), int(command[2]))
elif command[0] == 'print':
print(myList)
elif command[0] == 'remove':
myList.remove(int(command[1]))
elif command[0] == 'append':
myList.append(int(command[1]))
elif command[0] == 'sort':
myList.sort()
elif command[0] == 'pop':
myList.pop()
elif command[0] == 'reverse':
myList.reverse()