HackerRank-Python
Prepare > Python > Basic Data Types > Lists
stem_sw
2023. 6. 27. 20:58
Lists | HackerRank
Perform different list operations.
www.hackerrank.com
문제
onsider a list (list = []). You can perform the following commands:
- insert i e: Insert integer e at position i.
- print: Print the list.
- remove e: Delete the first occurrence of integer e.
- append e: Insert integer e at the end of the list.
- sort: Sort the list.
- pop: Pop the last element from the list.
- reverse: Reverse the list.
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.
=> 처음에 정수 N이 주어질거고 N개의 요구가 나올텐데 모두 만족시켜라
12 # 추후 요구의 수
insert 0 5 # "리스트에 삽입해라 0번 인덱스에 5를" 라는 요구임
insert 1 10
insert 0 6
print
remove 6 # "6번 인덱스를 삭제하라" 는 요구임
append 9 # "9를 append하라" 는 요구임
append 1
sort # 정렬하라는 요구임
print
pop # pop하라는 요구임
reverse
print # "앞선 요구들을 충족시킨 리스트를 출력해라"는 요구임
코드
if __name__ == '__main__':
N = int(input())
l = []
for i in range(N):
s = list(input().split())
if s[0]=='insert':
l.insert(int(s[1]),int(s[2]))
if s[0]=='remove':
l.remove(int(s[1]))
if s[0]=='append':
l.append(int(s[1]))
if s[0]=='sort':
l.sort()
if s[0]=='pop':
l.pop()
if s[0]=='reverse':
l.reverse()
if s[0]=='print':
print(l)
노트
- pop()은 리스트의 맨 마지막 요소를 리턴하고 그 요소는 삭제한다.
>>> a = [1, 2, 3]
>>> a.pop()
3
>>> a
[1, 2]
>>> a = [1, 2, 3]
>>> a.pop(1)
2
>>> a
[1, 3]
- pop(1)은 a[1] 값을 리턴하고, 리스트에서 삭제함
명령이 뭔지 파악하고 그 명령대로 리스트를 편집해주면 되겠구나!
명령을 파악하는 부분
if __name__ == '__main__':
N = int(input())
l = []
for i in range(N):
s = list(input().split())
print(s)
# OUTPUT
['insert', '0', '5']
['insert', '1', '10']
['insert', '0', '6']
['print']
['remove', '6']
['append', '9']
['append', '1']
['sort']
['print']
['pop']
['reverse']
['print']
- 주의! 문자열 들이 담긴 리스트임
if문으로 하나하나 지정해주기
if __name__ == '__main__':
N = int(input())
l = []
for i in range(N):
s = list(input().split())
if s[0] == 'insert':
l.insert(s[1], s[2])
elif s[0] == 'print':
print(l)
elif s[0] == 'append':
l.append(s[1])
elif s[0] == 'sort':
l.sort()
elif s[0] == 'pop':
l.pop()
elif s[0] == 'reverse':
l.reverse()
elif s[0] == 'remove':
l.remove([s[1]])
- l.sort()
- l.pop()
- l.reverse()
- l.remove()
- 사용법 구체적으로 익혀두자
숫자형 삽입
if __name__ == '__main__':
N = int(input())
l = []
for i in range(N):
s = list(input().split())
if s[0] == 'insert':
l.insert(int(s[1]),int(s[2]))
elif s[0] == 'print':
print(l)
elif s[0] == 'append':
l.append(int(s[1]))
elif s[0] == 'sort':
l.sort()
elif s[0] == 'pop':
l.pop()
elif s[0] == 'reverse':
l.reverse()
elif s[0] == 'remove':
l.remove(int(s[1]))
참조
HackerRank Solution: Python Lists [Basic Data Types] | GoLinuxCloud
This tutorial covers solutions for Python Lists question from Hacker Rank using if statements, map and len() method Using the split() function
www.golinuxcloud.com