본문 바로가기

TIL

[240130] SQL: 코드카타 117 & 파이썬: 코드카타 27

[SQL 코드카타]

602. Friend Requests II: Who Has the Most Friends

https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/

 

1) 어떤 문제가 있었나

친구 초대 및 승락 리스트에서 친구가 가장 많은 사람의 id와 친구수 구하기 

 

2) 내가 시도해본 건 무엇인가

3) 어떻게 해결했나

union all로 requester_id와 accepter_id 를 교차하여 연결 후 with 절로 빼고,

메인 쿼리에서 친구수가 가장 많은 id랑 친구수만 추출 

with union_table as (select requester_id, accepter_id 
                       from RequestAccepted
                       union all 
                      select accepter_id, requester_id 
                       from RequestAccepted)
 
select requester_id id, count(requester_id) num 
  from union_table 
 group by requester_id
 order by num desc
 limit 1


4) 무엇을 새롭게 알았나

- select 절에 하나의 속성에 2중으로 집계함수를 먹일 수 없음 ex. max( count(requester_id) ) 

└ where이나 having 절 내 별도 서브쿼리를 활용해 조건절을 추가해줘야 함  


[파이썬 코드카타]

핸드폰 번호 가리기

https://school.programmers.co.kr/learn/courses/30/lessons/12948

 

1) 어떤 문제가 있었나

전화번호 뒷자리 4개 빼고 *로 치환하는 문제로 for문이 필요하나 고민하였으나 문자 슬라이싱을 해보기로 결정

 

2) 내가 시도해본 건 무엇인가

3) 어떻게 해결했나

def solution(phone_number):
    answer = ''
    num_of_number = len(phone_number) - 4 
    a = num_of_number*'*'
    b = phone_number[ num_of_number : len(phone_number)]
    answer = a + b
    return answer


4) 무엇을 새롭게 알았나

- 문자열 맨 뒷자리를 지칭하는 것이 -1라고만 알고 있었는데, -4로 하면 뒤에서부터 4번째 자리수가 나옴!

└ 하기와 같이 간단히 1줄로도 정리 가능 

def solution(phone_number):
    return '*'*(len(phone_number)-4) + phone_number[-4:]