본문 바로가기

TIL

[240122] SQL: 코드카타 110 & 파이썬: 코드카타 21

[SQL 코드카타]

1164. Product Price at a Given Date

https://leetcode.com/problems/product-price-at-a-given-date/description/

 

1) 어떤 문제가 있었나

날짜별 가격 정보를 토대로 특정일자(2019-08-16)의 가격을 추정해야 하는 것으로 이해했으나,

2019-08-16에 수정된 가격이 있으면 해당 날짜 가격으로,

그전에 수정되었으면 가장 나중에 수정된 가격으로, 수정 안됐으면 가격을 10으로 추정해야 했음

 

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

with 절로 고유 product_id 테이블 및 각 날짜별 테이블을 생성 후 left 조인해 case when 문으로 추정값을 넣으려 했지만 실패   

 

3) 어떻게 해결했나

다른 사람 풀이를 통해 union으로 진행한 건을 확인하고 나름대로 다시 풀이 진행 

select product_id, 10 price   #product_id별 change_date 최소값이 2019-08-16보다 크다? 가격 10 
  from Products
 where (product_id, change_date) in (select product_id, change_date
                        from  Products
                    group by product_id
                        having min(change_date) > '2019-08-16')
UNION 
 select product_id, new_price as price  #2019-08-16 이전 행들중 product_id별 change_date max값  
   from Products
  where (product_id, change_date) in (select product_id, max(change_date) max_date
                                        from  Products
                                        where change_date <= '2019-08-16'
                                    group by product_id)


4) 무엇을 새롭게 알았나

- coalesce, join를 통한 풀이도 가능!
- 핵심은 16일 이내 중 max 날짜의 producti_id와 change_price, 16일 이후 price는 10으로 변환하는 것 

select distinct Products.product_id, coalesce(change_price.new_price, 10) price  #coalesce
from Products 
left join (select product_id ,  new_price  #2019-08-16 이내 데이터 중 max만 뽑고 distinct product_id랑 조인  
            from Products
            where (product_id, change_date) in (select product_id, max(change_date) change_date
                                                from Products
                                            where change_date <= '2019-08-16'
                                            group by product_id )) change_price 
            on change_price.product_id = Products.product_id

[파이썬 코드카타]

하샤드 수

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

 

1) 어떤 문제가 있었나

x를 x의 각 자리수를 더한 값으로 나눴을 때 나머지가 0이면 Ture, 아니면 False   

 

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

리스트를 만들어 for 문으로 각 자리수를 넣어 더하고, 마지막에 if 절로 히샤드 수 여부 판별 

다소 길게 문제를 해결한 듯 함.

def solution(x):
    x = str(x)
    answer = []
    for i in x:
        answer.append(int(i))
        sum_answer = sum(answer)
    if int(x) % sum_answer == 0:
        answer = True
    else:
        answer = False
    return answer

 

3) 어떻게 해결했나

def solution(x):
    st = str(x)
    a = 0
    for i in st: 
        a += int(i)                   #list 만들고 sum 안해도 누적합 집계 가능     
    return True if x%a == 0 else False  #return절에 if 조건 적용 
    
#한 줄 풀이 
def solution(x):
    return True if x%sum(int(i) for i in str(x)) == 0 else False


4) 무엇을 새롭게 알았나

- list일 때는 sum, 아닐 때는 += 를 통해서 합계치를 구할 수 있으므로, list 변환 시 한 번 더 생각 필요!