-
1431. [Python]시리얼 번호Python_알고리즘/Silver III 2023. 4. 23. 00:04
1. 문제
https://www.acmicpc.net/problem/1431
2. 접근 방법
- 시간 제한: 2초
- 메모리 제한: 128MB
- 정렬
3. 파이썬 코드
N = int(input()) word_list = [] for _ in range(N): word_list.append(input()) # 0번 인덱스부터 N-1 까지 반복문을 통한 정렬 for i in range(N-1): for j in range(i+1,N): # 일단 우선 각 길이를 반환해줌 i_length = len(word_list[i]) j_length = len(word_list[j]) # 길이가 다를 경우 if i_length != j_length: # i가 앞의 인덱스이고 j가 뒤의 인덱스이기 때문에 i 가 더 큰경우 j 랑 바꿔준다. if i_length > j_length: temp = word_list[i] word_list[i] = word_list[j] word_list[j] = temp # 길이가 같은 경우 else: # 값을 더해줄 변수 생성 total_1 = 0 total_2 = 0 # 반복문을 순회하면서 0~9 사이 값이 있으면 더해준다. for k in range(i_length): if (word_list[i][k] >= "0" and word_list[i][k] <= "9"): total_1 += int(word_list[i][k]) if (word_list[j][k] >= "0" and word_list[j][k] <= "9"): total_2 += int(word_list[j][k]) # 더해준 값들을 비교하여 앞의 값이 큰 경우 작은 값순으로 정렬해야기 때문에 순서를 바꿔준다. if total_1 > total_2: temp = word_list[i] word_list[i] = word_list[j] word_list[j] = temp # 값이 같은경우 문자 순으로 정렬 elif total_1 == total_2: if word_list[i] > word_list[j]: temp = word_list[i] word_list[i] = word_list[j] word_list[j] = temp for _ in word_list: print(_)
4. 문제를 풀고난 후 생각
- 이 문제도 해결하는데 이틀이 걸렸다. 처음 작성했던 코드는 아래와 같다.
더보기N = int(input()) word_list = [] for _ in range(N): word_list.append(input()) for i in range(N-1): for j in range(i+1,N): i_length = len(word_list[i]) j_length = len(word_list[j]) if i_length != j_length: if i_length > j_length: temp = word_list[i] word_list[i] = word_list[j] word_list[j] = temp else: num = "0123456789" if not word_list[i].isalpha() and not word_list[j].isalpha(): total_1 = 0 total_2 = 0 for k in word_list[i]: if k in num: total_1 += int(k) for l in word_list[j]: if l in num: total_2 += int(l) if total_1 > total_2: temp = word_list[i] word_list[i] = word_list[j] word_list[j] = temp elif total_2 == total_1: if word_list[i] > word_list[j]: temp = word_list[i] word_list[i] = word_list[j] word_list[j] = temp else: if word_list[i].isalpha() and word_list[j].isalpha(): if word_list[i] > word_list[j]: temp = word_list[i] word_list[i] = word_list[j] word_list[j] = temp elif not word_list[i].isalpha() and word_list[j].isalpha(): temp = word_list[i] word_list[i] = word_list[j] word_list[j] = temp for _ in word_list: print(_)
- 그냥 무식하게 조건을 하나하나 다 설정해줬다. 이 과정에서 값을 더하는 과정인지 아래부분인지 정확히 어느 부분인지 모르겠지만 꼬였다. 그래서 문제를 틀렸다.
- 다음날 새로운 생각을 가지고 코드를 다시 작성하기 시작했다. 아예 싹 지우고 조건에 따라서 천천히 코드를 생각해 보았다
- 길이를 비교하는 것을 시작으로 길이가 같은 경우 앞의 문자가 뒤의 문자보다 길이가 긴 경우 위치를 바꿔주었다.
- 길이가 같은 경우에서 각 문자를 탐색하며 "0" ~ "9"사이에 있는 경우 int 형으로 변환하여 값을 더해줬고, 아무값도 안더해 질 경우 0으로 총합이 결정되었다.
- 이렇게 값을 더한 후 그 값을 가지고 대소를 비교하여 앞의 값이 큰경우 작은 값과 위치를 바꿔주고 값이 같은 경우 문자열 정렬을 진행했다.
- 정말 간단한 문제인 것 같지만 의외로 생각을 못했던 부분이 많았던 것 같다.
5. 문제를 푸는데 도움이 되는 지식
- 정렬
'Python_알고리즘 > Silver III' 카테고리의 다른 글
10974. [Python]모든 순열 (0) 2023.05.21 1003. [Python]피보나치 함수 (0) 2023.05.19 1213. [Python]팰린드롬 만들기 (0) 2023.04.22 1788. [Python]피보나치 수의 확장 (0) 2023.04.19 1515. [Python]수 이어 쓰기 (0) 2023.04.14