Skip to content

Commit

Permalink
add 2024_07_24 TIL
Browse files Browse the repository at this point in the history
  • Loading branch information
terri1102 authored Jul 24, 2024
1 parent 7253e2d commit 63cca5c
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions StudyGroups/TIL/2024/JULY/2024_07_24.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
![TIL pic](../기본형2_python.png)

## 문제: 문자열 내 마음대로 정렬하기
https://school.programmers.co.kr/learn/courses/30/lessons/12915

## 아이디어
### 1. sorted 사용
n 번째 인덱스에 맞게 정렬하는 것이니 일단 표준 라이브러리의 `sorted`에 key로 인덱스를 주면 될 것이라고 생각했다.

`sorted(strings, key=lambda x: x[n])`
그런데 동순위가 있는 경우에 추가 정렬을 해야 하니 새로운 기준을 또 넣어야 했다.
튜플 형식으로 정렬 규칙을 여러 개 넣을 수 있는 건 알고 있었지만, 어떻게 넣어야 할지 몰라서 이 부분에서 막혔었다.

`sorted(strings, key=lambda x: (x[n], x))`

syntax를 찾아서 코드 제출을 해보니 일단 통과는 되었다.

근데 문제에서 원하는 방식은 이게 아닌 것 같아서 다른 풀이를 찾아봤다.

### 2. Selection sort
1. 외부 반복문은 정렬되지 않은 부분의 첫 번째 요소부터 시작하며, 내부 반복문은 이 첫 번째 요소 이후의 모든 요소를 탐색한다.
2. 최소값 찾기: 내부 반복문은 현재 범위 내에서 n번째 문자가 가장 작은 문자열을 찾는다. 만약 n번째 문자가 같다면, "문자열 자체를 비교하여" 사전순으로 정렬한다.
3. 교환: 내부 반복문이 끝난 후, 현재 범위 내에서 최소값을 가진 문자열과 현재 위치의 문자열을 교환한다.


## 풀이
```python
def solution(strings, n):
length = len(strings)

for i in range(length):
min_index = i
for j in range(i + 1, length):
if strings[j][n] < strings[min_index][n] or (strings[j][n] == strings[min_index][n] and strings[j] < strings[min_index]):
min_index = j

strings[i], strings[min_index] = strings[min_index], strings[i]

return strings
```

## 배운 점
- 첫 번째 기준으로 동순위인 것만 따로 오름차순 정렬을 하려면 `x`를 기준으로 추가로 주면 된다.

`sorted(strings, key=lambda x: (x[n], x))`

- Selection sort 구현. 이 부분은 다시 반복해서 봐야 할 것 같다.

0 comments on commit 63cca5c

Please sign in to comment.