문제

 

내가 작성한 코드
import sys
input = sys.stdin.readline

# 파일의 개수 N 입력
n = int(input())
file_dict = {}

for i in range(n):
    file_n = input().split('.')[1].replace('\n', '')
    if file_n not in file_dict.keys():
        file_dict[file_n] = 1
    else:
        file_dict[file_n] += 1
        
result = sorted(list(file_dict.keys()))

for i in result:
    print(i + ' ' + str(file_dict[i]))

 

코드 설명
import sys
input = sys.stdin.readline

> 'sys.stdin.readline' 코드는 데이터를 빠르게 입력할 수 있는 코드입니다. 대량의 데이터를 입력받아야 하는 문제일 때를 대비해서 항상 작성하고 있습니다.

 

n = int(input())
file_dict = {}

> 변수 n 은 파일의 개수를 받기 위한 변수입ㄴ디ㅏ. 

> file_dict 변수는 파일의 확장자별 수를 저장하기 위해서 빈 dict 자료형을 만들었습니다.

 

for i in range(n):
    file_n = input().split('.')[1].replace('\n', '')
    if file_n not in file_dict.keys():
        file_dict[file_n] = 1
    else:
        file_dict[file_n] += 1

> 파일의 개수만큼 파일을 받기 위해서 for문을 사용하였습니다.

> 파일이 'sbrus.txt' 와 같이 들어오는데 이 중에 필요한 'txt' 와 같은 확장자명입니다.

> 그래서 input().split('.')[1] 을 사용하면 결과가 ['sbrus', 'txt\n'] 으로 나오는데 그 뒤에 나오는 값을 추출한 것이다.

> 처음에 input().split('.')[1]을 하면 'txt'로만 나오는 줄 알았는데 'txt\n'으로 결과가 나와서 놀랐다.

> 그래서 replace('\n', '')을 사용해서 '\n' 을 제거해주었다.

> 그리고 if-else문을 사용해서 file_dict.keys()에 확장자명이 없다면 file_dic[file_n] = 1로 설정해주고, 있다면 file_dict += 1로 설정해주었습니다.

> 이렇게 하면 확장자별 수를 file_dict 변수에 담을 수 있게 됩니다.

 

result = sorted(list(file_dict.keys()))

> 확장자 이름을 사전순으로 출력해야 하므로, sorted(list(file_dict.keys())) 를 사용해서 확장자명만 추출해서 오름차순으로 정렬된 값을 result 변수에 담았습니다.

 

for i in result:
    print(i + ' ' + str(file_dict[i]))

> 확장자 이름이 사전순으로 정렬된 변수 result를 for문을 사용해서 사전순으로 출력시켰습니다.

> 원하는 출력값에 맞게 print(i, file_dict[i]) 를 사용해서 확장자명과 확장자 파일의 개수를 출력시켰습니다.

+ Recent posts