티스토리 뷰

728x90

Lists

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

  1. insert i e: Insert integer e at position i.
  2. print: Print the list.
  3. remove e: Delete the first occurrence of integer e.
  4. append e: Insert integer e 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 n followed by n lines of commands where each command will be of the 7 types listed above. Iterate through each command in order and perform the corresponding operation on your list.

 

Example

[1, 3, 2]

Input Format

The first line contains an integer, , denoting the number of commands.
Each line  of the  subsequent lines contains one of the commands described above.

Constraints

  • The 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 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]

 

문제해석

입력되는 커맨드를 수행하는 기능을 만들어야 한다. 입력될 수 있는 커맨드는 아래와 같이 7개이다.

1. insert i e : 리스트의 i 위치에 e 값을 입력한다.

2. print : 리스트를 출력한다.

3. remove e : 리스트에서 첫 번째로 e인 값을 삭제한다.

4. append e : 리스트의 끝에 e 값을 추가한다.

5. sort : 리스트를 정렬한다.

6. pop : 리스트의 가장 마지막 값을 가져온다.

7. reverse : 리스트를 반대로 정렬한다.

처음 입력되는 n값은 입력될 커맨드의 수이다.

 

문제풀이

이전 문제에서는 input을 받는 부분이 기본으로 있는데 이번에는 없어서 처음에 어떻게 해야할지 몰라서 난감했다. 이전 문제를 참고하여 테스트를 해보았고, input(), input().split(), args.append(input().split()) 구문에 따른 값 변화를 아래에 작성하였다.

 

input()

--------

insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print

 

input().split()

----------------

['insert', '0', '5']
['insert', '1', '10']
['insert', '0', '6']
['print']
['remove', '6']
['append', '9']
['append', '1']
['sort']
['print']
['pop']
['reverse']
['print']

 

args.append(input().split())

--------------------------------

[['insert', '0', '5'], ['insert', '1', '10'], ['insert', '0', '6'], ['print'], ['remove', '6'], ['append', '9'], ['append', '1'], ['sort'], ['print'], ['pop'], ['reverse'], ['print']]

 

최종적으로는 args.append(input().split()) 구문을 사용하여 모든 입력값을 args 리스트에 저장하였다. 

args에서 첫 번째 인덱스 값이 커맨드이므로 이 값에 따라 if문을 사용해 분기하였다. 각 커맨드에 따른 연산은 List Method로 제공되는 것과 동일하여 따로 구현할 필요없이 그냥 사용하면 되었다. 

각 값을 int()로 타입변환 하지 않으면 ['6', '5', '10'] 이런 식으로 문자열로 표현되어 에러가 발생하여 작성하였다.

if __name__ == '__main__':
    N = int(input())
   
    args = []    
    result = []
    for _ in range(N):      
        args.append(input().split())
           
    i = 0
    while i < N:        
        cmd = args[i][0]
        
        if cmd == "insert": 
            result.insert(int(args[i][1]), int(args[i][2]))
        elif cmd == "print":
            print(result)
        elif cmd == "remove":
            result.remove(int(args[i][1]))
        elif cmd =="append":
            result.append(int(args[i][1]))
        elif cmd == "sort":
            result.sort()
        elif cmd == "pop":
            result.pop()
        elif cmd == "reverse":
            result.reverse()
       
        i += 1

Discussions

insert, print와 같은 함수나 인자가 기존 List Method와 동일하다고 하였는데 이점을 이용하여 아래처럼 커맨드까지 바로 실행되도록 하였다. python3에서 컴파일은 안되어서 자세히 확인은 못하였다.

n = input()
l = []
for _ in range(n):
    s = raw_input().split()
    cmd = s[0]
    args = s[1:]
    if cmd !="print":
        cmd += "("+ ",".join(args) +")"
        eval("l."+cmd)
    else:
        print l
728x90
LIST
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함