TIL 알고리즘(13)

알고리즘

목록 보기
10/21

SQL

https://www.hackerrank.com/challenges/the-pads/problem?isFullScreen=true
문제가 상대적으로 길고, 요구하는 조건이 많아서 어제 저녁에 조금 보다가 풀어봤다.
각각에 대한 출력을 만들었고, 이걸 한 컬럼에 합치면 된다.
그런데 union이 이 순서를 신경쓰지 않는다.

-- # 4
-- select * 
-- from
-- ((
-- select
--     concat_ws(' ', Name, concat('(', (substr(Occupation, 1, 1)), ')')),
--     1 as filter
-- from OCCUPATIONS
-- order by Name
-- ) 
-- union all
-- (
-- select
--     concat('There are a total of ', count(Occupation), ' ', concat(lower(Occupation), 's', '.')),
--     2 as filter
-- from OCCUPATIONS
-- group by Occupation
-- order by count(Occupation), Occupation
-- )) a
-- -- ERROR 1248 (42000) at line 1: Every derived table must have its own alias
-- order by filter


-- # 3
-- (
-- select
--     concat_ws(' ', Name, concat('(', (substr(Occupation, 1, 1)), ')')),
--     1 as SortKey
-- from OCCUPATIONS
-- ) 
-- union
-- (
-- select
--     concat('There are a total of ', count(Occupation), ' ', concat(lower(Occupation), 's', '.')),
--     2 as SortKey
-- from OCCUPATIONS
-- group by Occupation
-- )
-- order by SortKey, Name, count(Occupation), Occupation
-- -- ERROR 1054 (42S22) at line 1: Unknown column 'Name' in 'order clause'



-- # 2
-- (
-- select
--     concat_ws(' ', Name, concat('(', (substr(Occupation, 1, 1)), ')')),
--     Name as Name_
-- from OCCUPATIONS
-- ) 
-- union
-- (
-- select
--     concat('There are a total of ', count(Occupation), ' ', concat(lower(Occupation), 's', '.')),
--     Occupation as Occupation_,
--     count(Occuaption) as count_
-- from OCCUPATIONS
-- group by Occupation
-- )
-- order by Name_, count_, Occupation_



-- # 1
-- (
-- select concat_ws(' ', Name, concat('(', (substr(Occupation, 1, 1)), ')'))
-- from OCCUPATIONS
-- order by Name
-- ) 
-- union
-- (
-- select concat('There are a total of ', count(Occupation), ' ', concat(lower(Occupation), 's', '.'))
-- from OCCUPATIONS
-- group by Occupation
-- order by count(Occupation), Occupation
-- ) 

-- select count(Occupation), lower(Occupation) 's' from OCCUPATIONS group by Occupation
-- 's' and operated column can not be concat
-- 7 professors (expected)
-- 7 professor (output)

알고리즘

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

def solution(arr):
    str_ = ''
    for i in range(len(arr)):
        for j in range(len(arr)):
            if arr[i][j] == arr[j][i]:
                str_ += '1'    
            else:
                str_ += '0'
    if '0' in str_:
        return 0
    else:
        return 1

처음에는 그냥 str_이 없었다.
바로 return을 써서 결과가 잘못됐다.
첫번째 원소에서 바로 판가름이 나버렸다.
그래서 모든 원소에 대해 정보를 받았다. (str_에 쌓아둠)

뭔가 복잡한 코드같아서 다른 사람의 풀이를 참고했다.
arr[i][j] == arr[j][i]:라는 조건을 시각적으로 표현했다.
unpacking(*)으로 arr를 풀어주고, zip으로 각 자리마다의 원소를 합친다.
이를 map으로 list구조로 변경하고, 마지막으로 list로 감싸서 그래도 arr와 같은지 확인해서 return한다.

조건을 꿰뚫었다는 느낌이 들었다. 하지만 나는 바로 알아채기 힘들다.
이걸 풀어서 보자면 이해가 되지만, arr[j][i]가 크게 보아서 특정 번호들의 인덱스임을 간파하기가 힘들다.

0개의 댓글