<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>zzaer.log</title>
        <link>https://velog.io/</link>
        <description>응애 나 애기개발자 </description>
        <lastBuildDate>Thu, 18 May 2023 18:01:17 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <copyright>Copyright (C) 2019. zzaer.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/zzaerynn_" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[Lv1. 행렬의 덧셈]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%ED%96%89%EB%A0%AC%EC%9D%98-%EB%8D%A7%EC%85%88</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%ED%96%89%EB%A0%AC%EC%9D%98-%EB%8D%A7%EC%85%88</guid>
            <pubDate>Thu, 18 May 2023 18:01:17 GMT</pubDate>
            <description><![CDATA[<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(arr1, arr2):
    temp = arr1
    for i in range(len(arr1)):
        for j in range(len(arr1[0])):
            temp[i][j] = arr1[i][j]+arr2[i][j]
    return temp</code></pre>
<p>temp로 variable을 새로 지정한건 별 의미 없고 그냥 arr의 값이 바뀔까봐 temp를 이용했다 그런데 문제 상에서 다시 given array를 참조하는 일은 없으니 그냥 한 array를 정해서 그 위에 값을 더해 reassign 하는 것도 하나의 방법일듯 함 그래도 일단 정석은 temp를 쓰는 것이니 그렇게 했어요</p>
<h3 id="다른사람-풀이">다른사람 풀이</h3>
<pre><code class="language-python">def sumMatrix(A,B):
    answer = [[c + d for c, d in zip(a,b)] for a, b in zip(A,B)]
    return answer</code></pre>
<pre><code class="language-python">def sumMatrix(A,B):
    return [list(map(sum, zip(*x))) for x in zip(A, B)]</code></pre>
<p>zip을 쓰는 풀이가 많이 보였다 알다가도 모를 zip</p>
<pre><code class="language-python">import numpy as np

def sumMatrix(A,B):
    A_np = np.array(A)
    B_np = np.array(B)
    result = A_np + B_np
    return result.tolist()</code></pre>
<p>np는 약간 편법이라고 생각해서 안썼는데 쓰는 것도 나쁘지 않다 
numpy는 진짜 유용한 함수들이 많아서 알아두면 참 좋다 근데 이제 일반 python format으로 되돌리기 귀찮을 뿐</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv1. 자연수 뒤집어 배열로 만들기]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%EC%9E%90%EC%97%B0%EC%88%98-%EB%92%A4%EC%A7%91%EC%96%B4-%EB%B0%B0%EC%97%B4%EB%A1%9C-%EB%A7%8C%EB%93%A4%EA%B8%B0-d1q1qk20</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%EC%9E%90%EC%97%B0%EC%88%98-%EB%92%A4%EC%A7%91%EC%96%B4-%EB%B0%B0%EC%97%B4%EB%A1%9C-%EB%A7%8C%EB%93%A4%EA%B8%B0-d1q1qk20</guid>
            <pubDate>Wed, 17 May 2023 00:07:00 GMT</pubDate>
            <description><![CDATA[<h3 id="문제-설명">문제 설명</h3>
<p>자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.</p>
<h3 id="제한-조건">제한 조건</h3>
<ul>
<li>n은 10,000,000,000이하인 자연수입니다.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>n</th>
<th>return</th>
</tr>
</thead>
<tbody><tr>
<td>12345</td>
<td>[5,4,3,2,1]</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(n):
    answer = []
    while (n &gt; 0):
        answer.append(n%10)
        n = n//10
    return answer</code></pre>
<p>정석.............
그러나 약간 조잡한.. 그리고 긴...</p>
<p>다른 사람들 풀이를 봤는데 전체적으로 map이나 list를 쓴 풀이가 많았다</p>
<pre><code class="language-python">def digit_reverse(n):
    return list(map(int, reversed(str(n))))</code></pre>
<p>이런식으로 하는거지
알고는 있는데 적용을 못한 거다 바보</p>
<pre><code class="language-python">def digit_reverse(n):
    return [int(i) for i in str(n)][::-1]</code></pre>
<p>map을 안쓰더라도 이렇게 그냥 String으로만도 해결할 수 있는 것이었다
저걸 까먹고 있었네
처음에 string argument인가..? 인덱싱을 반대로 하면 되나? 이런 생각했었는데 막상 적용은 완전 반대로 한걸 보면 갈길이 멀다! 배울 것이 많다</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv1. 자연수 뒤집어 배열로 만들기]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%EC%9E%90%EC%97%B0%EC%88%98-%EB%92%A4%EC%A7%91%EC%96%B4-%EB%B0%B0%EC%97%B4%EB%A1%9C-%EB%A7%8C%EB%93%A4%EA%B8%B0</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%EC%9E%90%EC%97%B0%EC%88%98-%EB%92%A4%EC%A7%91%EC%96%B4-%EB%B0%B0%EC%97%B4%EB%A1%9C-%EB%A7%8C%EB%93%A4%EA%B8%B0</guid>
            <pubDate>Wed, 17 May 2023 00:05:51 GMT</pubDate>
            <description><![CDATA[<h3 id="문제-설명">문제 설명</h3>
<p>자연수 n을 뒤집어 각 자리 숫자를 원소로 가지는 배열 형태로 리턴해주세요. 예를들어 n이 12345이면 [5,4,3,2,1]을 리턴합니다.</p>
<h3 id="제한-조건">제한 조건</h3>
<ul>
<li>n은 10,000,000,000이하인 자연수입니다.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>n</th>
<th>return</th>
</tr>
</thead>
<tbody><tr>
<td>12345</td>
<td>[5,4,3,2,1]</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(n):
    answer = []
    while (n &gt; 0):
        answer.append(n%10)
        n = n//10
    return answer</code></pre>
<p>정석.............
그러나 약간 조잡한.. 그리고 긴...</p>
<p>다른 사람들 풀이를 봤는데 전체적으로 map이나 list를 쓴 풀이가 많았다</p>
<pre><code class="language-python">def digit_reverse(n):
    return list(map(int, reversed(str(n))))</code></pre>
<p>이런식으로 하는거지
알고는 있는데 적용을 못한 거다 바보</p>
<pre><code class="language-python">def digit_reverse(n):
    return [int(i) for i in str(n)][::-1]</code></pre>
<p>map을 안쓰더라도 이렇게 그냥 String으로만도 해결할 수 있는 것이었다
저걸 까먹고 있었네
처음에 string argument인가..? 인덱싱을 반대로 하면 되나? 이런 생각했었는데 막상 적용은 완전 반대로 한걸 보면 갈길이 멀다! 배울 것이 많다</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv1. 공원산책]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%EA%B3%B5%EC%9B%90%EC%82%B0%EC%B1%85</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%EA%B3%B5%EC%9B%90%EC%82%B0%EC%B1%85</guid>
            <pubDate>Sat, 13 May 2023 16:14:06 GMT</pubDate>
            <description><![CDATA[<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/172928">[Lv1. 공원산책]</a></p>
<h3 id="문제-설명">문제 설명</h3>
<p>지나다니는 길을 &#39;O&#39;, 장애물을 &#39;X&#39;로 나타낸 직사각형 격자 모양의 공원에서 로봇 강아지가 산책을 하려합니다. 산책은 로봇 강아지에 미리 입력된 명령에 따라 진행하며, 명령은 다음과 같은 형식으로 주어집니다.</p>
<p>[&quot;방향 거리&quot;, &quot;방향 거리&quot; … ]
예를 들어 &quot;E 5&quot;는 로봇 강아지가 현재 위치에서 동쪽으로 5칸 이동했다는 의미입니다. 로봇 강아지는 명령을 수행하기 전에 다음 두 가지를 먼저 확인합니다.</p>
<p>주어진 방향으로 이동할 때 공원을 벗어나는지 확인합니다.
주어진 방향으로 이동 중 장애물을 만나는지 확인합니다.
위 두 가지중 어느 하나라도 해당된다면, 로봇 강아지는 해당 명령을 무시하고 다음 명령을 수행합니다.
공원의 가로 길이가 W, 세로 길이가 H라고 할 때, 공원의 좌측 상단의 좌표는 (0, 0), 우측 하단의 좌표는 (H - 1, W - 1) 입니다.</p>
<p><img src="https://user-images.githubusercontent.com/62426665/217702316-1bd5d3ba-c1d7-4133-bfb5-36bdc85a08ba.png" alt="park"></p>
<p>공원을 나타내는 문자열 배열 park, 로봇 강아지가 수행할 명령이 담긴 문자열 배열 routes가 매개변수로 주어질 때, 로봇 강아지가 모든 명령을 수행 후 놓인 위치를 [세로 방향 좌표, 가로 방향 좌표] 순으로 배열에 담아 return 하도록 solution 함수를 완성해주세요.</p>
<h3 id="제한사항">제한사항</h3>
<ul>
<li>3 ≤ park의 길이 ≤ 50<ul>
<li>3 ≤ park[i]의 길이 ≤ 50</li>
</ul>
</li>
<li>park[i]는 다음 문자들로 이루어져 있으며 시작지점은 하나만 주어집니다.<ul>
<li>S : 시작 지점</li>
<li>O : 이동 가능한 통로</li>
<li>X : 장애물</li>
</ul>
</li>
<li>park는 직사각형 모양입니다.<ul>
<li>1 ≤ routes의 길이 ≤ 50</li>
<li>routes의 각 원소는 로봇 강아지가 수행할 명령어를 나타냅니다.</li>
<li>로봇 강아지는 routes의 첫 번째 원소부터 순서대로 명령을 수행합니다.</li>
<li>routes의 원소는 &quot;op n&quot;과 같은 구조로 이루어져 있으며, op는 이동할 방향, n은 이동할 칸의 수를 의미합니다.</li>
</ul>
</li>
<li>op는 다음 네 가지중 하나로 이루어져 있습니다.<ul>
<li>N : 북쪽으로 주어진 칸만큼 이동합니다.</li>
<li>S : 남쪽으로 주어진 칸만큼 이동합니다.</li>
<li>W : 서쪽으로 주어진 칸만큼 이동합니다.</li>
<li>E : 동쪽으로 주어진 칸만큼 이동합니다.</li>
</ul>
</li>
<li>1 ≤ n ≤ 9</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>park</th>
<th>routes</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[&quot;SOO&quot;,&quot;OOO&quot;,&quot;OOO&quot;]</td>
<td>[&quot;E 2&quot;,&quot;S 2&quot;,&quot;W 1&quot;]</td>
<td>[2,1]</td>
</tr>
<tr>
<td>[&quot;SOO&quot;,&quot;OXX&quot;,&quot;OOO&quot;]</td>
<td>[&quot;E 2&quot;,&quot;S 2&quot;,&quot;W 1&quot;]</td>
<td>[0,1]</td>
</tr>
<tr>
<td>[&quot;OSO&quot;,&quot;OOO&quot;,&quot;OXO&quot;,&quot;OOO&quot;]</td>
<td>[&quot;E 2&quot;,&quot;S 3&quot;,&quot;W 1&quot;]</td>
<td>[0,0]</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(park, routes):

    # pos = currPos
    pos = [0,0] # row, column = dy, dx

    # find S
    for idx, row in enumerate(park): 
        if &quot;S&quot; in row:
            pos[0] = idx
            pos[1] = row.find(&quot;S&quot;)
    # print(&quot;S pos: &quot;, pos)
    # nx dx
    dx = {&quot;N&quot; : 0, &quot;S&quot; :  0, &quot;E&quot; : 1, &quot;W&quot; : -1}
    dy = {&quot;N&quot; : -1, &quot;S&quot; : 1, &quot;E&quot; : 0, &quot;W&quot; : 0}

    # execute oper
    for route in routes:
        direc, step = route.split(&quot; &quot;)
        if isValid(pos, direc, step, park):
            pos[1] = pos[1] + int(step) * dx[direc] 
            pos[0] = pos[0] + int(step) * dy[direc] 
            # print(&quot;pos after move :&quot;, pos)
        else:
            # print(direc, step , &quot; is not valid oper&quot;)
            continue

    return pos

def isValid(pos, direc, step, park):

    # w, h, dx, dy
    dx = {&quot;N&quot; : 0, &quot;S&quot; :  0, &quot;E&quot; : 1, &quot;W&quot; : -1}
    dy = {&quot;N&quot; : -1, &quot;S&quot; : 1, &quot;E&quot; : 0, &quot;W&quot; : 0}
    # size
    width, height = len(park[0]),len(park) 

    ny, nx = pos
    print(direc, step)
    for i in range(int(step)):
        nx = nx + dx[direc]
        ny = ny + dy[direc]
        # if nx/ny in the right pos (inner)
        if 0 &lt;= nx &lt; width and 0 &lt;= ny &lt; height :
            if ((park[ny][nx] == &quot;X&quot;)) :
                return False
        # if nx &lt; 0 or ny &lt; 0 or ny &gt;= height or nx &gt;= width :   (outer) 
        else:
            return False
        # print(&quot;    curPos moving: &quot;, pos, direc, step, &quot; nx, ny : &quot;, nx, ny)
        # printPark(park)
    return True

# def printPark(park):
#     for i in park:
#         print(i)</code></pre>
<p>굉장히 조잡하다..! 처음 짜 본 미로 탐색 코드라서 그럴지도요
미로에서 가장 주의해야할 점은 우리가 평소에 다르던 좌표랑 다르다는 것이다..! 문제만 잘 읽었어도 눈치 챌 수 있었을지도 모르겠는데 </p>
<ul>
<li>pos = [0,0]</li>
</ul>
<p>이라고 적은 후에 당연히 x, y  좌표라고 생각하고 다뤘는데 알고 보니 y,x였다 matrix 를 다루는 법을.. 잊어버린거죠.. 네.. ㅋㅋㅋ ㅋ 
진행 방향에 따라 달라지는 것이니 이걸 주의해서 해야겠다</p>
<p>그리고 또 놀라운 점.. dx, dy 를 함수마다 설정해줬는데 그냥 global variable로 주고 싶으면 def solution 위에.. 그냥.. 정의해주면 되는거였어요 멍청아</p>
<p>자꾸 에러가 나서 여러가지 프린트를 해가면서 오류를 고쳐나갔다
print park 함수를 따로 짜서 X를 잘 피해가는지도 확인해주었다 </p>
<p>풀 때는 자꾸 에러 나서 너무너무너무너무 짜증났는데 하고 나니까 행복하네요
그리고 풀 때는 아.. 코드 너무 긴가? 이런 생각만 계속 했었는데 다 끝내고 다른사람들 풀이 구경하니까 다들 저만큼 길게 풀었더라고요 너무 걱정하지 말자 좋은 코드는 예쁜 코드나 읽기 쉬운 코드가 아니라 작동하는 코드 일뿐.. !</p>
<h3 id="다른-사람-풀이">다른 사람 풀이</h3>
<pre><code class="language-python">from collections import deque

def solution(park, routes):
    answer = []

    x = len(park)
    y = len(park[0])

    new_park = []

    for i in range(x):
        new_park.append(list(park[i]))
        if &quot;S&quot; in park[i]:
            start_x, start_y = i,park[i].index(&quot;S&quot;)

    for i in routes:
        where, how = i.split(&#39; &#39;)
        flag = 0

        if where == &quot;E&quot;:
            if 0&lt;=start_y+int(how)&lt;y:
                for i in range(start_y,start_y+int(how)+1):
                    if new_park[start_x][i]==&#39;X&#39;:
                        flag = 1
                        break
                if flag == 0:
                    start_y = start_y+int(how)

        elif where == &quot;W&quot;:
            if 0&lt;=start_y-int(how)&lt;y:
                for i in range(start_y-int(how),start_y+1):
                    if new_park[start_x][i]==&#39;X&#39;:
                        flag = 1
                        break
                if flag == 0:
                    start_y = start_y-int(how)

        elif where == &quot;S&quot;:
            if 0&lt;=start_x+int(how)&lt;x:
                for i in range(start_x,start_x+int(how)+1):
                    if new_park[i][start_y]==&#39;X&#39;:
                        flag = 1
                        break
                if flag == 0:
                    start_x = start_x+int(how)

        else:
            if 0&lt;=start_x-int(how)&lt;x:
                for i in range(start_x-int(how),start_x+1):
                    if new_park[i][start_y]==&#39;X&#39;:
                        flag = 1
                        break
                if flag == 0:
                    start_x = start_x-int(how)

    return [start_x,start_y]</code></pre>
<p>deque 를 사용했길래 눈에 들어왔던 문제</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv1. 둘만의 암호]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%EB%91%98%EB%A7%8C%EC%9D%98-%EC%95%94%ED%98%B8</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%EB%91%98%EB%A7%8C%EC%9D%98-%EC%95%94%ED%98%B8</guid>
            <pubDate>Wed, 10 May 2023 14:37:01 GMT</pubDate>
            <description><![CDATA[<h3 id="문제-설명">문제 설명</h3>
<p>두 문자열 s와 skip, 그리고 자연수 index가 주어질 때, 다음 규칙에 따라 문자열을 만들려 합니다. 암호의 규칙은 다음과 같습니다.</p>
<p>문자열 s의 각 알파벳을 index만큼 뒤의 알파벳으로 바꿔줍니다.
index만큼의 뒤의 알파벳이 z를 넘어갈 경우 다시 a로 돌아갑니다.
skip에 있는 알파벳은 제외하고 건너뜁니다.
예를 들어 s = &quot;aukks&quot;, skip = &quot;wbqd&quot;, index = 5일 때, a에서 5만큼 뒤에 있는 알파벳은 f지만 [b, c, d, e, f]에서 &#39;b&#39;와 &#39;d&#39;는 skip에 포함되므로 세지 않습니다. 따라서 &#39;b&#39;, &#39;d&#39;를 제외하고 &#39;a&#39;에서 5만큼 뒤에 있는 알파벳은 [c, e, f, g, h] 순서에 의해 &#39;h&#39;가 됩니다. 나머지 &quot;ukks&quot; 또한 위 규칙대로 바꾸면 &quot;appy&quot;가 되며 결과는 &quot;happy&quot;가 됩니다.</p>
<p>두 문자열 s와 skip, 그리고 자연수 index가 매개변수로 주어질 때 위 규칙대로 s를 변환한 결과를 return하도록 solution 함수를 완성해주세요.</p>
<h3 id="제한사항">제한사항</h3>
<ul>
<li>5 ≤ s의 길이 ≤ 50</li>
<li>1 ≤ skip의 길이 ≤ 10</li>
<li>s와 skip은 알파벳 소문자로만 이루어져 있습니다.</li>
<li>skip에 포함되는 알파벳은 s에 포함되지 않습니다.</li>
<li>1 ≤ index ≤ 20</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>s</th>
<th>skip</th>
<th>index</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>&quot;aukks&quot;</td>
<td>&quot;wbqd&quot;</td>
<td>5</td>
<td>&quot;happy&quot;</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(s, skip, index):
    answer = &#39;&#39;
    alphabet = &#39;abcdefghijklmnopqrstuvwxyz&#39;
    # 전처리 - skip letters remove
    for char in skip:
        alphabet = alphabet.replace(char, &quot;&quot;)
    # 이제 계산
    for letter in s: 
        answer += alphabet[(alphabet.index(letter) + index)%(26-len(skip))]
    return answer</code></pre>
<p>원래는 이렇게 안하고 약간 다른방식으로 (많이는 안다르지만) 했었는데 시간 초과 나길래 음 알파벳 길이를 줄여봐야겠다해서 반으로 줄였더니 시간 내에 다 통과되었다</p>
<pre><code class="language-python">### 시간초과 코드!
def solution(s, skip, index):
    answer = &#39;&#39;
    alphabet = &#39;abcdefghijklmnopqrstuvwxyz&#39;*2 # 2배 길이의 string
    # 전처리 - skip letters remove
    for char in skip:
        alphabet = alphabet.replace(char, &quot;&quot;)
    # 이제 계산
    for letter in s: 
        answer += alphabet[(alphabet.index(letter) + index)] # 나눗셈을 안하고 바로 계산한 next char
    return answer</code></pre>
<p>코드 중 다른부분은 주석이 달려있는 두 줄이다
2배 길이로 늘이다보니 메모리가 늘어나면서 자연스럽게 연산량이 늘어난 것 같다
string을 반으로 줄이고 index 처리를 한번 더 했음에도 불구하고 시간초과가 따로 안나온걸 보면 이게 더 효율이 좋다!</p>
<h3 id="다른사람-코드">다른사람 코드</h3>
<h4 id="다른-코드-1">다른 코드 1</h4>
<pre><code class="language-python">from string import ascii_lowercase

def solution(s, skip, index):
    result = &#39;&#39;

    a_to_z = set(ascii_lowercase)
    a_to_z -= set(skip)
    a_to_z = sorted(a_to_z)
    l = len(a_to_z)

    dic_alpha = {alpha:idx for idx, alpha in enumerate(a_to_z)}

    for i in s:
        result += a_to_z[(dic_alpha[i] + index) % l]

    return result</code></pre>
<p>set을 이용해서 sorting 하는 방식 </p>
<h4 id="다른코드-2">다른코드 2</h4>
<pre><code class="language-python">def solution(s, skip, index):
    answer = &#39;&#39;
    arr = [chr(i) for i in range(97, 123) if chr(i) not in skip] * 10
    # print(arr, len(arr))
    for i in s:
        answer += arr[arr.index(i) + index]
    return answer</code></pre>
<p>ascii 코드 쓴 거 하나 더!
알아둬야하긴 하는데 맨날 까먹어서 큰일이애오</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv1. 카드뭉치]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%EC%B9%B4%EB%93%9C%EB%AD%89%EC%B9%98</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%EC%B9%B4%EB%93%9C%EB%AD%89%EC%B9%98</guid>
            <pubDate>Wed, 10 May 2023 05:42:22 GMT</pubDate>
            <description><![CDATA[<p>[Lv1. 카드뭉치]</p>
<h3 id="문제-설명">문제 설명</h3>
<p>코니는 영어 단어가 적힌 카드 뭉치 두 개를 선물로 받았습니다. 코니는 다음과 같은 규칙으로 카드에 적힌 단어들을 사용해 원하는 순서의 단어 배열을 만들 수 있는지 알고 싶습니다.</p>
<p>원하는 카드 뭉치에서 카드를 순서대로 한 장씩 사용합니다.
한 번 사용한 카드는 다시 사용할 수 없습니다.
카드를 사용하지 않고 다음 카드로 넘어갈 수 없습니다.
기존에 주어진 카드 뭉치의 단어 순서는 바꿀 수 없습니다.
예를 들어 첫 번째 카드 뭉치에 순서대로 [&quot;i&quot;, &quot;drink&quot;, &quot;water&quot;], 두 번째 카드 뭉치에 순서대로 [&quot;want&quot;, &quot;to&quot;]가 적혀있을 때 [&quot;i&quot;, &quot;want&quot;, &quot;to&quot;, &quot;drink&quot;, &quot;water&quot;] 순서의 단어 배열을 만들려고 한다면 첫 번째 카드 뭉치에서 &quot;i&quot;를 사용한 후 두 번째 카드 뭉치에서 &quot;want&quot;와 &quot;to&quot;를 사용하고 첫 번째 카드뭉치에 &quot;drink&quot;와 &quot;water&quot;를 차례대로 사용하면 원하는 순서의 단어 배열을 만들 수 있습니다.</p>
<p>문자열로 이루어진 배열 cards1, cards2와 원하는 단어 배열 goal이 매개변수로 주어질 때, cards1과 cards2에 적힌 단어들로 goal를 만들 있다면 &quot;Yes&quot;를, 만들 수 없다면 &quot;No&quot;를 return하는 solution 함수를 완성해주세요.</p>
<h3 id="제한사항">제한사항</h3>
<ul>
<li>1 ≤ cards1의 길이, cards2의 길이 ≤ 10</li>
<li>1 ≤ cards1[i]의 길이, cards2[i]의 길이 ≤ 10</li>
<li>cards1과 cards2에는 서로 다른 단어만 존재합니다.</li>
<li>2 ≤ goal의 길이 ≤ cards1의 길이 + cards2의 길이</li>
<li>1 ≤ goal[i]의 길이 ≤ 10</li>
<li>goal의 원소는 cards1과 cards2의 원소들로만 이루어져 있습니다.</li>
<li>cards1, cards2, goal의 문자열들은 모두 알파벳 소문자로만 이루어져 있습니다.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>cards1</th>
<th>cards2</th>
<th>goal</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[&quot;i&quot;, &quot;drink&quot;, &quot;water&quot;]</td>
<td>[&quot;want&quot;, &quot;to&quot;]</td>
<td>[&quot;i&quot;, &quot;want&quot;, &quot;to&quot;, &quot;drink&quot;, &quot;water&quot;]</td>
<td>&quot;Yes&quot;</td>
</tr>
<tr>
<td>[&quot;i&quot;, &quot;water&quot;, &quot;drink&quot;]</td>
<td>[&quot;want&quot;, &quot;to&quot;]</td>
<td>[&quot;i&quot;, &quot;want&quot;, &quot;to&quot;, &quot;drink&quot;, &quot;water&quot;]</td>
<td>&quot;No&quot;</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<p> 첫 시도.. </p>
<pre><code class="language-python">def solution(cards1, cards2, goal):
    answer = &#39;Yes&#39;
    pt1 = 0 #cards1 pointer
    pt2 = 0 #cards2 pointer
    for word in goal:
        print(word)
        if cards1[pt1] == word and len(cards1) &gt; pt1:
            pt1 += 1
        elif cards2[pt2] == word and len(cards2) &gt; pt2:
            pt2 += 1
        else:
            return &quot;No&quot;
            break
    return answer</code></pre>
<p>계속해서 index out of range 가 나왔다 len 조건으로 처리해주고 있는데 도대체 왜 인덱스 에러가 뜨지?? 하고 궁금했는데 응.. 순서를 반대로 했군ㅎㅎ..ㅎ...
바로 해결 완료 </p>
<pre><code class="language-python">def solution(cards1, cards2, goal):
    answer = &#39;Yes&#39;
    pt1 = 0 #cards1 pointer
    pt2 = 0 #cards2 pointer
    for word in goal:
        print(word)
        if len(cards1) &gt; pt1 and cards1[pt1] == word :
            pt1 += 1
        elif len(cards2) &gt; pt2 and cards2[pt2] == word:
            pt2 += 1
        else:
            return &quot;No&quot;
            break
    return answer</code></pre>
<p>투포인터를 쓰는 아주 대표적인 문제였다 
다른 사람들 풀이를 봤는데 스택으로 처리해서 pop으로 해당 단어를 없애주기도 하고 다양한 모습들을 봤다
다만 게속 length를 체크해주는 모습은 동일했음!</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 시소 짝궁]]></title>
            <link>https://velog.io/@zzaerynn_/Lv2.-%EC%8B%9C%EC%86%8C-%EC%A7%9D%EA%B6%81</link>
            <guid>https://velog.io/@zzaerynn_/Lv2.-%EC%8B%9C%EC%86%8C-%EC%A7%9D%EA%B6%81</guid>
            <pubDate>Tue, 09 May 2023 09:21:33 GMT</pubDate>
            <description><![CDATA[<p>[Lv2. 시소 짝궁]</p>
<h3 id="문제-설명">문제 설명</h3>
<p>어느 공원 놀이터에는 시소가 하나 설치되어 있습니다. 이 시소는 중심으로부터 2(m), 3(m), 4(m) 거리의 지점에 좌석이 하나씩 있습니다.
이 시소를 두 명이 마주 보고 탄다고 할 때, 시소가 평형인 상태에서 각각에 의해 시소에 걸리는 토크의 크기가 서로 상쇄되어 완전한 균형을 이룰 수 있다면 그 두 사람을 시소 짝꿍이라고 합니다. 즉, 탑승한 사람의 무게와 시소 축과 좌석 간의 거리의 곱이 양쪽 다 같다면 시소 짝꿍이라고 할 수 있습니다.
사람들의 몸무게 목록 weights이 주어질 때, 시소 짝꿍이 몇 쌍 존재하는지 구하여 return 하도록 solution 함수를 완성해주세요.</p>
<h3 id="제한-사항">제한 사항</h3>
<ul>
<li>2 ≤ weights의 길이 ≤ 100,000</li>
<li>100 ≤ weights[i] ≤ 1,000</li>
<li>몸무게 단위는 N(뉴턴)으로 주어집니다.</li>
<li>몸무게는 모두 정수입니다.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>weights</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[100,180,360,100,270]</td>
<td>4</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(weights):
    answer = 0
    ratios = [1, 2/3, 0.5, 1.5, 0.75, 4/3]
    for i in range(len(weights)):
        for j in range(i+1, len(weights)):
            if weights[i]/weights[j] in ratios:
                # print(weights[i], weights[j], weights[i]/weights[j])
                answer += 1
    return answer</code></pre>
<p>처음에 짰던 풀이.. 눈물 좔좔 남
더블 룹 때문에 time complexity O(n^2)이라 시간 초과가 너무 많이떴었다
해싱이나 딕셔너리 쪽을 쓰는게 좋겠다고 생각은 했는데 어떻게 하지 고민하다가 defaultdict 발견</p>
<pre><code class="language-python">from collections import defaultdict
def solution(weights):
    answer = 0
    dict = defaultdict(int)
    #defaultdict은 말 그대로 딕셔너리 생성자 (그런데 타입을 지정해줄 수 있는 - int, set...)
    for weight in weights:
        answer += dict[weight]+ dict[weight/2] + dict[weight*2] + dict[weight*2/3] + dict[weight*3/2] + dict[weight*3/4] +dict[weight*4/3]
        dict[weight] += 1
    return answer</code></pre>
<p>이렇게 수정했다
외부 라이브러리를 썼긴 하지만 어찌저찌 해결은 .. 했다는 것
비율가짓수(시소 거리)가 몇개 되지 않는데도 불구하고 생각보다 케이스가 많아서 당황했다 더 많아졌을때 general solution을 찾을 수 있는 방법에 대해서도 생각해봐야함</p>
<h3 id="다른-사람-풀이">다른 사람 풀이</h3>
<pre><code class="language-python">from itertools import combinations
from collections import Counter

def solution(weights):
    cnt = 0
    weights = Counter(weights)
    for a, b in combinations(weights.keys(), 2): # 서로 다른 무게
        if a*2 == b*3 or a*2 == b*4 or a*3 == b*4 or b*2 == a*3 or b*2 == a*4 or b*3 == a*4:
            cnt += weights[a] * weights[b]
    for v in weights.values(): # 같은 무게
        if v &gt; 1:
            cnt += sum([i for i in range(1, v)])
    return cnt</code></pre>
<p>다른 사람 풀이 구경하다가 당황했던 건데 combinations써도 .. 괜찮았던거임..? 어째서..? time complexity .. 왜..?</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv1. 과일장수]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%EA%B3%BC%EC%9D%BC%EC%9E%A5%EC%88%98</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%EA%B3%BC%EC%9D%BC%EC%9E%A5%EC%88%98</guid>
            <pubDate>Fri, 05 May 2023 06:31:00 GMT</pubDate>
            <description><![CDATA[<p>[Lv1. 과일장수]</p>
<h3 id="문제-설명">문제 설명</h3>
<p>과일 장수가 사과 상자를 포장하고 있습니다. 사과는 상태에 따라 1점부터 k점까지의 점수로 분류하며, k점이 최상품의 사과이고 1점이 최하품의 사과입니다. 사과 한 상자의 가격은 다음과 같이 결정됩니다.</p>
<p>한 상자에 사과를 m개씩 담아 포장합니다.
상자에 담긴 사과 중 가장 낮은 점수가 p (1 ≤ p ≤ k)점인 경우, 사과 한 상자의 가격은 p * m 입니다.
과일 장수가 가능한 많은 사과를 팔았을 때, 얻을 수 있는 최대 이익을 계산하고자 합니다.(사과는 상자 단위로만 판매하며, 남는 사과는 버립니다)</p>
<p>예를 들어, k = 3, m = 4, 사과 7개의 점수가 [1, 2, 3, 1, 2, 3, 1]이라면, 다음과 같이 [2, 3, 2, 3]으로 구성된 사과 상자 1개를 만들어 판매하여 최대 이익을 얻을 수 있습니다.</p>
<p>(최저 사과 점수) x (한 상자에 담긴 사과 개수) x (상자의 개수) = 2 x 4 x 1 = 8
사과의 최대 점수 k, 한 상자에 들어가는 사과의 수 m, 사과들의 점수 score가 주어졌을 때, 과일 장수가 얻을 수 있는 최대 이익을 return하는 solution 함수를 완성해주세요.</p>
<h3 id="제한사항">제한사항</h3>
<ul>
<li>3 ≤ k ≤ 9</li>
<li>3 ≤ m ≤ 10</li>
<li>7 ≤ score의 길이 ≤ 1,000,000</li>
<li>1 ≤ score[i] ≤ k</li>
<li>이익이 발생하지 않는 경우에는 0을 return 해주세요.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>k</th>
<th>m</th>
<th>score</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>3</td>
<td>4</td>
<td>[1, 2, 3, 1, 2, 3, 1]</td>
<td>8</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
<td>[4, 1, 2, 2, 4, 4, 4, 4, 1, 2, 4, 2]</td>
<td>33</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(k, m, score):
    answer = 0
    score.sort(reverse=True) # sort
    pos = -1
    # print(score)
    while (pos &lt; len(score)-m):
        pos += m
        answer += score[pos]
        # print(pos, score[pos], &quot;answer: &quot;, answer)

    return answer*m</code></pre>
<p>처음에 했던건 이렇게 안짜고 조건들을 제대로 활용을 못하고 그냥 정말 뇌를 빼고 코딩했던 것 같다
sorting 한 score를 m씩 잘라서 새로 assign 한 다음에 minimum 값 구하는식으로 접근했는데 너무 쓸데없는 연산이 많았고 score 자체를 계속 만지다보니까 시간 초과가 자꾸 떠서 좀 더 간단하게 구현할 수 있는 방법은 없나 살펴보다가 조금 발전시켰다
sorting이 되어있기 떄문에 minimum value를 찾기가 쉬웠고(가장 마지막 index에 있는 값이 minumum val)
score를 계속 자를 필요가 없었고 그냥 포인트를 옮기면서 그 위치의 값만 읽어들이면 되는 문제였다 
생각보다 간단한 문제였는데 혼자 문제를 좀 꼬아서 생각해서 무겁게 푸는 경향이 있는 것 같다
푸는 것도 중요하지만 경량화도 중요한 문제인듯
쉬워졌다고 느껴지면 다시 어려워지고.. 낯설다 정말 코테</p>
<h3 id="다른사람-풀이">다른사람 풀이</h3>
<pre><code class="language-python">def solution(k, m, score):
    return sum(sorted(score)[len(score)%m::m])*m</code></pre>
<p>접근 방식은 나랑 비슷한데 한줄로 짜냈다는게.....
신기해서 좀 가져와봤어요읽으면 이해는 되는데  내가 저렇게 짜진 못하네
역시 조금 더 연습</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv1. 잘못누른자판]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%EC%9E%98%EB%AA%BB%EB%88%84%EB%A5%B8%EC%9E%90%ED%8C%90</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%EC%9E%98%EB%AA%BB%EB%88%84%EB%A5%B8%EC%9E%90%ED%8C%90</guid>
            <pubDate>Wed, 03 May 2023 08:40:49 GMT</pubDate>
            <description><![CDATA[<p>[잘못누른자판]</p>
<h3 id="문제-설명">문제 설명</h3>
<p>휴대폰의 자판은 컴퓨터 키보드 자판과는 다르게 하나의 키에 여러 개의 문자가 할당될 수 있습니다. 키 하나에 여러 문자가 할당된 경우, 동일한 키를 연속해서 빠르게 누르면 할당된 순서대로 문자가 바뀝니다.</p>
<p>예를 들어, 1번 키에 &quot;A&quot;, &quot;B&quot;, &quot;C&quot; 순서대로 문자가 할당되어 있다면 1번 키를 한 번 누르면 &quot;A&quot;, 두 번 누르면 &quot;B&quot;, 세 번 누르면 &quot;C&quot;가 되는 식입니다.</p>
<p>같은 규칙을 적용해 아무렇게나 만든 휴대폰 자판이 있습니다. 이 휴대폰 자판은 키의 개수가 1개부터 최대 100개까지 있을 수 있으며, 특정 키를 눌렀을 때 입력되는 문자들도 무작위로 배열되어 있습니다. 또, 같은 문자가 자판 전체에 여러 번 할당된 경우도 있고, 키 하나에 같은 문자가 여러 번 할당된 경우도 있습니다. 심지어 아예 할당되지 않은 경우도 있습니다. 따라서 몇몇 문자열은 작성할 수 없을 수도 있습니다.</p>
<p>이 휴대폰 자판을 이용해 특정 문자열을 작성할 때, 키를 최소 몇 번 눌러야 그 문자열을 작성할 수 있는지 알아보고자 합니다.</p>
<p>1번 키부터 차례대로 할당된 문자들이 순서대로 담긴 문자열배열 keymap과 입력하려는 문자열들이 담긴 문자열 배열 targets가 주어질 때, 각 문자열을 작성하기 위해 키를 최소 몇 번씩 눌러야 하는지 순서대로 배열에 담아 return 하는 solution 함수를 완성해 주세요.</p>
<p>단, 목표 문자열을 작성할 수 없을 때는 -1을 저장합니다.</p>
<h3 id="제한사항">제한사항</h3>
<ul>
<li>1 ≤ keymap의 길이 ≤ 100</li>
<li>1 ≤ keymap의 원소의 길이 ≤ 100</li>
<li>keymap[i]는 i + 1번 키를 눌렀을 때 순서대로 바뀌는 문자를 의미합니다.</li>
<li>예를 들어 keymap[0] = &quot;ABACD&quot; 인 경우 1번 키를 한 번 누르면 A, 두 번 누르면 B, 세 번 누르면 A 가 됩니다.</li>
<li>keymap의 원소의 길이는 서로 다를 수 있습니다.</li>
<li>keymap의 원소는 알파벳 대문자로만 이루어져 있습니다.</li>
<li>1 ≤ targets의 길이 ≤ 100</li>
<li>1 ≤ targets의 원소의 길이 ≤ 100</li>
<li>targets의 원소는 알파벳 대문자로만 이루어져 있습니다.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>keymap</th>
<th>targets</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[&quot;ABACD&quot;, &quot;BCEFD&quot;]</td>
<td>[&quot;ABCD&quot;,&quot;AABB&quot;]</td>
<td>[9, 4]</td>
</tr>
<tr>
<td>[&quot;AA&quot;]</td>
<td>[&quot;B&quot;]</td>
<td>[-1]</td>
</tr>
<tr>
<td>[&quot;AGZ&quot;, &quot;BSSS&quot;]</td>
<td>[&quot;ASA&quot;,&quot;BGZ&quot;]</td>
<td>[4, 6]</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(keymap, targets):
    answer = []
    dict = {}
    for target in targets: # for each word target
        res = 0
        for char in target: # for each char in target
            if char in dict.keys():
                res += dict[char]

            else: # if char not in dict.keys() = not been detected yet
                for key in keymap: # each key, such as &quot;ABACD&quot; 
                    for idx, char in enumerate(key): # (0,A), (1,B)
                        if char not in dict.keys():
                            dict[char] = idx + 1
                res += dict[char]
                print(char, res)
        answer.append(res)
    return answer</code></pre>
<p>처음에 뭔가 잘못했던 코드
왜 잘못됐을까요..
그것은 바로 key의 각 char 중에 만약에 dictionary에 assign되지 않은 키에 대한 케이스를 다루지 않았기 때문입니다.... 바보
물론 문제는 그것 뿐만이 아니라 char 가 이미 dictionary에 들어가있을때 새로 들어오는 키와 값을 비교하지 않았다는 것도..! ㅋㅋㅋㅋ.ㅋ.. </p>
<pre><code class="language-python">for key in keymap: # each key, such as &quot;ABACD&quot; 
    for idx, char in enumerate(key): # (0,A), (1,B)
        if char not in dict.keys():        
            dict[char] = idx + 1
res += dict[char]</code></pre>
<p>이렇게 했었는데 바로 res 에 더할게 아니라 체크를 먼저 한 다음에 진행했었어야했어요..멍청이
근데 이걸 막상 문제 풀때는 해결을 못해서 뭐지? 코드가 잘못됐나? 하고 한참을 생각하다가 코드를 새로 짜고서야 드디어 찾아냈습니다</p>
<pre><code class="language-python">def solution(keymap, targets):
    answer = []
    dict = {}
    for target in targets:
        res = 0
        # update dictionary
        for key in keymap:
            for idx, char in enumerate(key):
                if char not in dict.keys():
                    dict[char] = idx+1
                else: 
                    # if char already in dict, compare the value from the other key 
                    # assign the minimum value
                    dict[char] = min(dict[char], idx+1)
        # find the value from the dictionary 
        for char in target: 
            if char in dict.keys():
                res += dict[char]

            else:
                res = -1
                break

        answer.append(res)
    return answer</code></pre>
<p>원래 생각했던 방법은 dictionary를 업데이트 해가면서 바로 값을 더하는식으로 (dp?라고 내 나름대로 생각..) 하는거였는데 예상치 못하게 오류가 생겨서 아예 dictionary를 완성한 후에 그걸 바탕으로 값을 더해가는 식으로 바꿨다</p>
<p>시간복잡도는 비슷한 것 같아요</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv1. 덧칠하기]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%EB%8D%A7%EC%B9%A0%ED%95%98%EA%B8%B0</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%EB%8D%A7%EC%B9%A0%ED%95%98%EA%B8%B0</guid>
            <pubDate>Tue, 02 May 2023 08:13:37 GMT</pubDate>
            <description><![CDATA[<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/161989">[ Lv1. 덧칠하기 ]</a></p>
<h3 id="문제-설명">문제 설명</h3>
<p>어느 학교에 페인트가 칠해진 길이가 n미터인 벽이 있습니다. 벽에 동아리 · 학회 홍보나 회사 채용 공고 포스터 등을 게시하기 위해 테이프로 붙였다가 철거할 때 떼는 일이 많고 그 과정에서 페인트가 벗겨지곤 합니다. 페인트가 벗겨진 벽이 보기 흉해져 학교는 벽에 페인트를 덧칠하기로 했습니다.</p>
<p>넓은 벽 전체에 페인트를 새로 칠하는 대신, 구역을 나누어 일부만 페인트를 새로 칠 함으로써 예산을 아끼려 합니다. 이를 위해 벽을 1미터 길이의 구역 n개로 나누고, 각 구역에 왼쪽부터 순서대로 1번부터 n번까지 번호를 붙였습니다. 그리고 페인트를 다시 칠해야 할 구역들을 정했습니다.</p>
<p>벽에 페인트를 칠하는 롤러의 길이는 m미터이고, 롤러로 벽에 페인트를 한 번 칠하는 규칙은 다음과 같습니다.</p>
<p>롤러가 벽에서 벗어나면 안 됩니다.
구역의 일부분만 포함되도록 칠하면 안 됩니다.
즉, 롤러의 좌우측 끝을 구역의 경계선 혹은 벽의 좌우측 끝부분에 맞춘 후 롤러를 위아래로 움직이면서 벽을 칠합니다. 현재 페인트를 칠하는 구역들을 완전히 칠한 후 벽에서 롤러를 떼며, 이를 벽을 한 번 칠했다고 정의합니다.</p>
<p>한 구역에 페인트를 여러 번 칠해도 되고 다시 칠해야 할 구역이 아닌 곳에 페인트를 칠해도 되지만 다시 칠하기로 정한 구역은 적어도 한 번 페인트칠을 해야 합니다. 예산을 아끼기 위해 다시 칠할 구역을 정했듯 마찬가지로 롤러로 페인트칠을 하는 횟수를 최소화하려고 합니다.</p>
<p>정수 n, m과 다시 페인트를 칠하기로 정한 구역들의 번호가 담긴 정수 배열 section이 매개변수로 주어질 때 롤러로 페인트칠해야 하는 최소 횟수를 return 하는 solution 함수를 작성해 주세요.</p>
<h3 id="제한사항">제한사항</h3>
<p>-1 ≤ m ≤ n ≤ 100,000
-1 ≤ section의 길이 ≤ n
-1 ≤ section의 원소 ≤ n
-section의 원소는 페인트를 다시 칠해야 하는 구역의 번호입니다.
-section에서 같은 원소가 두 번 이상 나타나지 않습니다.
-section의 원소는 오름차순으로 정렬되어 있습니다.</p>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>n</th>
<th>m</th>
<th>section</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>8</td>
<td>4</td>
<td>[2, 3, 6]</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>4</td>
<td>[1, 3]</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>1</td>
<td>[1, 2, 3, 4]</td>
<td>4</td>
</tr>
</tbody></table>
<hr>
<h3 id="풀이">풀이</h3>
<p>처음에 문제를 잘못 이해했다... </p>
<h4 id="풀이1">풀이1</h4>
<pre><code class="language-python">import math
 def solution(n,m,section):
    length = (section[-1] - section[0]) + 1 # 실제 길이를 나타내기 위해 +1 해주기!
    answer = math.ceil(length/m)
    return answer</code></pre>
<p>그 결과 이런 이상한 코드가 탄생했는데..! 
이렇게 하면 문제점이 중간에 칠할 곳이 없을 경우에도 그 중간에 뭔가 빈칸이 있다고 생각해서 쓸데 없이 계속 칠하게 된다는 점!
그래서 횟수가 과도하게 나와서 실패가 나오는 항목들이 많았다 </p>
<p>그래서 방법을 수정했다</p>
<h4 id="풀이2">풀이2</h4>
<pre><code class="language-python">def solution(n, m, section):
    curr = section[0] # starting point
    answer = 1 
    for sect in section:
        if (sect - curr) &gt;= m:
            curr = sect
            answer += 1
    return answer</code></pre>
<p>하나씩 section에 들어있는 칠해야하는 구간들을 살피면서 처음에 칠한 위치에서 (m-1)만큼보다 더 차이가 클 경우(코드에서는 아래와 같이 표기)</p>
<pre><code class="language-python">if (sect - curr) &gt;= m:</code></pre>
<p>그 타일에서부터 새로 칠해야한다고 규칙을 정했다
(m-1)인 이유는 해당 타일의 위치에서부터 칠하기 시작하기 때문에, 현재 위치가 3이고 m=4인 경우 3,4,5,6 총 4개의 타일을 칠하지만 끝 타일인 6은 4-1인 3만큼만 더해진 값이기 때문이다 </p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv1. 추억점수]]></title>
            <link>https://velog.io/@zzaerynn_/Lv1.-%EC%B6%94%EC%96%B5%EC%A0%90%EC%88%98</link>
            <guid>https://velog.io/@zzaerynn_/Lv1.-%EC%B6%94%EC%96%B5%EC%A0%90%EC%88%98</guid>
            <pubDate>Fri, 21 Apr 2023 07:30:12 GMT</pubDate>
            <description><![CDATA[<h3 id="문제-설명">문제 설명</h3>
<p>사진들을 보며 추억에 젖어 있던 루는 사진별로 추억 점수를 매길려고 합니다. 사진 속에 나오는 인물의 그리움 점수를 모두 합산한 값이 해당 사진의 추억 점수가 됩니다. 예를 들어 사진 속 인물의 이름이 [&quot;may&quot;, &quot;kein&quot;, &quot;kain&quot;]이고 각 인물의 그리움 점수가 [5점, 10점, 1점]일 때 해당 사진의 추억 점수는 16(5 + 10 + 1)점이 됩니다. 다른 사진 속 인물의 이름이 [&quot;kali&quot;, &quot;mari&quot;, &quot;don&quot;, &quot;tony&quot;]이고 [&quot;kali&quot;, &quot;mari&quot;, &quot;don&quot;]의 그리움 점수가 각각 [11점, 1점, 55점]]이고, &quot;tony&quot;는 그리움 점수가 없을 때, 이 사진의 추억 점수는 3명의 그리움 점수를 합한 67(11 + 1 + 55)점입니다.</p>
<p>그리워하는 사람의 이름을 담은 문자열 배열 name, 각 사람별 그리움 점수를 담은 정수 배열 yearning, 각 사진에 찍힌 인물의 이름을 담은 이차원 문자열 배열 photo가 매개변수로 주어질 때, 사진들의 추억 점수를 photo에 주어진 순서대로 배열에 담아 return하는 solution 함수를 완성해주세요.</p>
<h3 id="제한사항">제한사항</h3>
<ul>
<li>3 ≤ name의 길이 = yearning의 길이≤ 100</li>
<li>3 ≤ name의 원소의 길이 ≤ 7</li>
<li>name의 원소들은 알파벳 소문자로만 이루어져 있습니다.</li>
<li>name에는 중복된 값이 들어가지 않습니다.</li>
<li>1 ≤ yearning[i] ≤ 100</li>
<li>yearning[i]는 i번째 사람의 그리움 점수입니다.</li>
<li>3 ≤ photo의 길이 ≤ 100</li>
<li>1 ≤ photo[i]의 길이 ≤ 100</li>
<li>3 ≤ photo[i]의 원소(문자열)의 길이 ≤ 7</li>
<li>photo[i]의 원소들은 알파벳 소문자로만 이루어져 있습니다.</li>
<li>photo[i]의 원소들은 중복된 값이 들어가지 않습니다.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>name</th>
<th>yearning</th>
<th>photo</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[&quot;may&quot;, &quot;kein&quot;, &quot;kain&quot;, &quot;radi&quot;]</td>
<td>[5, 10, 1, 3]</td>
<td>[[&quot;may&quot;, &quot;kein&quot;, &quot;kain&quot;, &quot;radi&quot;],[&quot;may&quot;, &quot;kein&quot;, &quot;brin&quot;, &quot;deny&quot;], [&quot;kon&quot;, &quot;kain&quot;, &quot;may&quot;, &quot;coni&quot;]]</td>
<td>[19, 15, 6]</td>
</tr>
<tr>
<td>[&quot;kali&quot;, &quot;mari&quot;, &quot;don&quot;]</td>
<td>[11, 1, 55]</td>
<td>[[&quot;kali&quot;, &quot;mari&quot;, &quot;don&quot;], [&quot;pony&quot;, &quot;tom&quot;, &quot;teddy&quot;], [&quot;con&quot;, &quot;mona&quot;, &quot;don&quot;]]</td>
<td>[67, 0, 55]</td>
</tr>
<tr>
<td>[&quot;may&quot;, &quot;kein&quot;, &quot;kain&quot;, &quot;radi&quot;]</td>
<td>[5, 10, 1, 3]</td>
<td>[[&quot;may&quot;],[&quot;kein&quot;, &quot;deny&quot;, &quot;may&quot;], [&quot;kon&quot;, &quot;coni&quot;]]</td>
<td>[5, 15, 0]</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(name, yearning, photo):
    answer = []
    # assign nums to dict
    dict = {}
    for i in range(len(name)):
        dict[name[i]] = yearning[i]
    # photos
    for lst in photo:
        score = 0
        for person in lst: 
            if person in list(dict.keys()):
                score += dict[person]
        answer.append(score)
    return answer</code></pre>
<p>정석에 가까운 풀이지 않나.. 뭐 그런 생각.. 인덱스를 찾아서 구할 까 생각도 했는데 그냥 dictionary 만들어서 참조하는게 제일 쉬울 것 같아서 선택했다 간단한 문제라 크게 어렵진 않았는데 다른 사ㅏㄹㅁ 들 풀이를 보다보니 적어두고 싶어서 남겨둠 </p>
<h3 id="다른-사람-풀이">다른 사람 풀이</h3>
<pre><code class="language-python">def solution(이름, 점수, 사진):
    return [sum(점수[이름.index(j)] for j in i if j in 이름) for i in 사진]</code></pre>
<p>한줄로 짜서 대단하다.. 싶었던 풀이 내가 쓰고 싶었던 것도 이런 코드 이긴 했는데 인덱스 사용해서 했어도 이렇게까지는 진행 안됐을듯 ㅎㅎ..</p>
<pre><code class="language-python">def solution(name, yearning, photo):
    dictionary = dict(zip(name,yearning))
    scores = []
    for pt in photo:
        score = 0
        for p in pt:
            if p in dictionary:
                score += dictionary[p]
        scores.append(score)
    return scores</code></pre>
<p> zip으로 바로 처리한게 신기해서 적어둔다 zip 하면 오브젝트 타입이 달라지니까 일부러 안쓴건데 그냥 리스트로 overwrite 하면 되는거였음.. </p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2.마법의 엘리베이터]]></title>
            <link>https://velog.io/@zzaerynn_/Lv2.%EB%A7%88%EB%B2%95%EC%9D%98-%EC%97%98%EB%A6%AC%EB%B2%A0%EC%9D%B4%ED%84%B0</link>
            <guid>https://velog.io/@zzaerynn_/Lv2.%EB%A7%88%EB%B2%95%EC%9D%98-%EC%97%98%EB%A6%AC%EB%B2%A0%EC%9D%B4%ED%84%B0</guid>
            <pubDate>Tue, 18 Apr 2023 06:18:59 GMT</pubDate>
            <description><![CDATA[<p>[마법의 엘리베이터]</p>
<h4 id="문제-설명">문제 설명</h4>
<p>마법의 세계에 사는 민수는 아주 높은 탑에 살고 있습니다. 탑이 너무 높아서 걸어 다니기 힘든 민수는 마법의 엘리베이터를 만들었습니다. 마법의 엘리베이터의 버튼은 특별합니다. 마법의 엘리베이터에는 -1, +1, -10, +10, -100, +100 등과 같이 절댓값이 10c (c ≥ 0 인 정수) 형태인 정수들이 적힌 버튼이 있습니다. 마법의 엘리베이터의 버튼을 누르면 현재 층 수에 버튼에 적혀 있는 값을 더한 층으로 이동하게 됩니다. 단, 엘리베이터가 위치해 있는 층과 버튼의 값을 더한 결과가 0보다 작으면 엘리베이터는 움직이지 않습니다. 민수의 세계에서는 0층이 가장 아래층이며 엘리베이터는 현재 민수가 있는 층에 있습니다.</p>
<p>마법의 엘리베이터를 움직이기 위해서 버튼 한 번당 마법의 돌 한 개를 사용하게 됩니다.예를 들어, 16층에 있는 민수가 0층으로 가려면 -1이 적힌 버튼을 6번, -10이 적힌 버튼을 1번 눌러 마법의 돌 7개를 소모하여 0층으로 갈 수 있습니다. 하지만, +1이 적힌 버튼을 4번, -10이 적힌 버튼 2번을 누르면 마법의 돌 6개를 소모하여 0층으로 갈 수 있습니다.</p>
<p>마법의 돌을 아끼기 위해 민수는 항상 최소한의 버튼을 눌러서 이동하려고 합니다. 민수가 어떤 층에서 엘리베이터를 타고 0층으로 내려가는데 필요한 마법의 돌의 최소 개수를 알고 싶습니다. 민수와 마법의 엘리베이터가 있는 층을 나타내는 정수 storey 가 주어졌을 때, 0층으로 가기 위해 필요한 마법의 돌의 최소값을 return 하도록 solution 함수를 완성하세요.</p>
<h4 id="제한사항">제한사항</h4>
<ul>
<li>1 ≤ storey ≤ 100,000,000</li>
</ul>
<h4 id="입출력-예">입출력 예</h4>
<table>
<thead>
<tr>
<th>storey</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>16</td>
<td>6</td>
</tr>
<tr>
<td>2554</td>
<td>16</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">#성공한 코드
def solution(storey):
    answer = 0
    while (storey): #storey != 0
        last = storey%10 # last digit
        # 6 7 8 9
        if (last &gt; 5):
            answer += 10 - last
            storey += 10 # adds one to the second last digit
        # 0 1 2 3 4
        elif (last &lt; 5):
            answer += last
        # 5
        else:
            if ((storey//10)%10 &gt; 4):  
                storey += 10 # adds one to the second last digit
            answer += 10- last
        storey = storey//10
    return answer</code></pre>
<p>해냈다..! 간단한거였는데 시간이 계속 안맞아서 실패가 떴다</p>
<pre><code class="language-python"># 실패한 코드
def solution(storey):
    answer = 0
    while (storey): 
        last = storey%10 
        # 6 7 8 9
        if (last &gt; 5):
            answer += 10 - last
            storey += 10 
        # 0 1 2 3 4
        elif (last &lt; 5):
            answer += last
        # 5
        else:
            if ((storey//10)%10 &gt; 4):  
                storey += 10 
            storey = storey//10 ## 여기! 
            answer += 10- last
    return answer</code></pre>
<p>다 풀어두고 어라.. 이상하다..? 하면서 계속 갸우뚱 거리고 있었는데 코드를 살펴보니 storey //10 부분의 순서가 이상하게 들어가있었다 
순서를 바꾸니 바로 해결..!
너무 루프 안 깊숙히에 변수를 저장하거나 계산하지 말 것.... 힘드네 이거 </p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 연속된 부분 수열의 합]]></title>
            <link>https://velog.io/@zzaerynn_/Lv2.-%EC%97%B0%EC%86%8D%EB%90%9C-%EB%B6%80%EB%B6%84-%EC%88%98%EC%97%B4%EC%9D%98-%ED%95%A9</link>
            <guid>https://velog.io/@zzaerynn_/Lv2.-%EC%97%B0%EC%86%8D%EB%90%9C-%EB%B6%80%EB%B6%84-%EC%88%98%EC%97%B4%EC%9D%98-%ED%95%A9</guid>
            <pubDate>Fri, 14 Apr 2023 08:14:25 GMT</pubDate>
            <description><![CDATA[<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/178870">[연속된 부분 수열의 합]</a></p>
<h4 id="문제-설명">문제 설명</h4>
<p>비내림차순으로 정렬된 수열이 주어질 때, 다음 조건을 만족하는 부분 수열을 찾으려고 합니다.</p>
<p>기존 수열에서 임의의 두 인덱스의 원소와 그 사이의 원소를 모두 포함하는 부분 수열이어야 합니다.
부분 수열의 합은 k입니다.
합이 k인 부분 수열이 여러 개인 경우 길이가 짧은 수열을 찾습니다.
길이가 짧은 수열이 여러 개인 경우 앞쪽(시작 인덱스가 작은)에 나오는 수열을 찾습니다.
수열을 나타내는 정수 배열 sequence와 부분 수열의 합을 나타내는 정수 k가 매개변수로 주어질 때, 위 조건을 만족하는 부분 수열의 시작 인덱스와 마지막 인덱스를 배열에 담아 return 하는 solution 함수를 완성해주세요. 이때 수열의 인덱스는 0부터 시작합니다.</p>
<h4 id="제한사항">제한사항</h4>
<p>5 ≤ sequence의 길이 ≤ 1,000,000
1 ≤ sequence의 원소 ≤ 1,000
sequence는 비내림차순으로 정렬되어 있습니다.
5 ≤ k ≤ 1,000,000,000
k는 항상 sequence의 부분 수열로 만들 수 있는 값입니다.</p>
<h4 id="입출력-예">입출력 예</h4>
<table>
<thead>
<tr>
<th>sequence</th>
<th>k</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[1, 2, 3, 4, 5]</td>
<td>7</td>
<td>[2, 3]</td>
</tr>
<tr>
<td>[1, 1, 1, 2, 3, 4, 5]</td>
<td>5</td>
<td>[6, 6]</td>
</tr>
<tr>
<td>[2, 2, 2, 2, 2]</td>
<td>6</td>
<td>[0, 2]</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<p>누가봐도 투 포인터를 써야하는 문제...!
완탐이 아니라 dp를 써보려고 matrix 를 설정해서 시도해보았으나 장렬히 실패
왜그런지 모르겠지만 숫자 입력이 이상하게 되더라구..? 저는 한 element만 입력하고 싶은데 한 column이 다 입력되어부렀어요 for loop 두번 써서 그런가 하기에는 그 전에는.. 괜찮았던거 같은데..? ㅎㅎ... 잘은.. 모르겠지만 아무튼 그런가봐요</p>
<h3 id="다른-사람-풀이">다른 사람 풀이</h3>
<pre><code class="language-python">def solution(sequence, k):
    partial_sum = 0
    right = 0
    result = []
    for left in range(len(sequence)):
        #left = left pointer
        while right &lt; len(sequence) and partial_sum &lt; k:
        #right = right pointer
        # while right is smaller than the given sequence
        # and while the partial sum is smaller than k (since it is sorted)
            partial_sum += sequence[right]
            #add the current value of right to the partial sum
            right += 1
            #and move the right pointer to the right

        if partial_sum == k:
        #if the partial sum reaches the goal
            if not result:
            # if result is empty:
                result = [left, right - 1]
                #assign current pointer pos to the result(the indexes)
            else:
            # if result is not empty:
                result = result if result[1] - result[0] &lt;= (right - 1) - left else [left, right - 1]
                #compare the result(old index) with current=new index(left, right)
                #if new is smaller : assign that to the result

        partial_sum -= sequence[left]

    return result</code></pre>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv2. 뒤에 있는 큰 수 찾기]]></title>
            <link>https://velog.io/@zzaerynn_/Lv2.-%EB%92%A4%EC%97%90-%EC%9E%88%EB%8A%94-%ED%81%B0-%EC%88%98-%EC%B0%BE%EA%B8%B0</link>
            <guid>https://velog.io/@zzaerynn_/Lv2.-%EB%92%A4%EC%97%90-%EC%9E%88%EB%8A%94-%ED%81%B0-%EC%88%98-%EC%B0%BE%EA%B8%B0</guid>
            <pubDate>Thu, 13 Apr 2023 16:59:02 GMT</pubDate>
            <description><![CDATA[<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/154539">[뒤에 있는 큰 수 찾기]</a></p>
<h3 id="문제-설명">문제 설명</h3>
<p>정수로 이루어진 배열 numbers가 있습니다. 배열 의 각 원소들에 대해 자신보다 뒤에 있는 숫자 중에서 자신보다 크면서 가장 가까이 있는 수를 뒷 큰수라고 합니다.
정수 배열 numbers가 매개변수로 주어질 때, 모든 원소에 대한 뒷 큰수들을 차례로 담은 배열을 return 하도록 solution 함수를 완성해주세요. 단, 뒷 큰수가 존재하지 않는 원소는 -1을 담습니다.</p>
<h3 id="제한사항">제한사항</h3>
<p>4 ≤ numbers의 길이 ≤ 1,000,000
1 ≤ numbers[i] ≤ 1,000,000</p>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>numbers</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[2, 3, 3, 5]</td>
<td>[3, 5, 5, -1]</td>
</tr>
<tr>
<td>[9, 1, 5, 3, 6, 2]</td>
<td>[-1, 5, 6, 6, -1, -1]</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-코드">내 코드</h3>
<pre><code class="language-python">def solution(numbers):
    answer = []
    for num in numbers:
        idx = numbers.index(num)
        answer.append(bigger(num, numbers[idx+1:]))
    return answer

def bigger(std, numbers): #std for standard
    for num in numbers:
        if (std &lt; num):
            return num
    return -1</code></pre>
<p>brute force로 냅다 찾아버리는.. ㅋㅋㅋㅋ 그래서 O(n^2)이라 시간 초과로 통과못했다 자료구조를 써야한다는 건 이해했는데 어떤 자료구조를 써야할지는 생각을 못하겠더라 linked list? 이생각했다가 바로 접었고 ㅋㅋㅋ 쓰면 스택이나 큐를 쓰나? 했는데 어떻게 써야할지 감이 안잡혔다
포기하고 다른사람이 짠 코드를 봤는데도 이해가 안가서 고민중이다</p>
<h4 id="다른사람-풀이"><a href="https://growingquokka.tistory.com/286">다른사람 풀이</a></h4>
<pre><code class="language-python">def solution(numbers):
    stack = [] # store the numbers which the next bigger number is not found
    answer = [0] * len(numbers) #initialize stack

    for i in range(len(numbers)):
        while stack and numbers[stack[-1]] &lt; numbers[i]: 
        # while stack not empty and
        # while recent num from numbers(numbers indexed by top of the stack) is smaller 
        # than the next number from numbers
            answer[stack.pop()] = numbers[i]
            # stack.pop() = the next bigger number
    # for / while loop -&gt; repeats until condition fails
        stack.append(i)
        # i-th number is not bigger than previous ones

    while stack:
        answer[stack.pop()] = -1
        # numbers in the stack = doesnt have bigger number :(

    return answer</code></pre>
<p>손으로 적어가면서 주석 달고 손코딩 해보니까 약간 이해가 간다 음 이런 시스템으로 스택을 쓰는구나 싶은 정도의 이해?
그러나 나보고 이 문제 풀으라고 했을때 냅다 스택을 생각해내지는 못할 정도의 수준
그리고 사실 스택까지는 이해는 했는데 잠깐씩 어라 이게 왜..? 싶기도 한 걸 보니 아직 갈길이 멀다 
완탐 말고 다른방법으로 구현하는 방식들을 좀 더 공부해둬야할 것 같다 </p>
<h4 id="다른-사람-풀이-2">다른 사람 풀이 2</h4>
<pre><code class="language-python">from collections import defaultdict
def solution(numbers):
    answer = [-1]*len(numbers)
    for i in range(len(numbers)-1,-1,-1):
        for j in range(i-1,-1,-1):
            if numbers[j] &gt;= numbers[i]:    break
            answer[j] = numbers[i]
    return answer</code></pre>
<p>프로그래머스에서 긁어와서 출처는 딱히 없다 누구 코드라고 할 수 없는.. 출처를 달 수 없는 코드 ㅋㅋㅋ 
처음에 접근했던 방식이랑 비슷한 것 같아서 긁어왔다 set이나 dictionary key로 했었는데 defaultdict import 가능한지 몰라서 안했다 
아직 갈길이 멀다<del>~</del></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[2007. 패턴 마디의 길이]]></title>
            <link>https://velog.io/@zzaerynn_/2007.-%ED%8C%A8%ED%84%B4-%EB%A7%88%EB%94%94%EC%9D%98-%EA%B8%B8%EC%9D%B4</link>
            <guid>https://velog.io/@zzaerynn_/2007.-%ED%8C%A8%ED%84%B4-%EB%A7%88%EB%94%94%EC%9D%98-%EA%B8%B8%EC%9D%B4</guid>
            <pubDate>Wed, 05 Apr 2023 13:00:07 GMT</pubDate>
            <description><![CDATA[<p><a href="https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=2&amp;contestProbId=AV5P1kNKAl8DFAUq&amp;categoryId=AV5P1kNKAl8DFAUq&amp;categoryType=CODE&amp;problemTitle=&amp;orderBy=FIRST_REG_DATETIME&amp;selectCodeLang=PYTHON&amp;select-1=2&amp;pageSize=10&amp;pageIndex=1">[2007. 패턴 마디의 길이]</a></p>
<h4 id="제약-사항">[제약 사항]</h4>
<p>각 문자열의 길이는 30이다. 마디의 최대 길이는 10이다.</p>
<h4 id="입력">[입력]</h4>
<ul>
<li><p>가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다.</p>
</li>
<li><p>각 테스트 케이스의 첫 번째 줄에는 길이가 30인 문자열이 주어진다.</p>
</li>
</ul>
<h4 id="출력">[출력]</h4>
<ul>
<li><p>출력의 각 줄은 &#39;#t&#39;로 시작하고, 공백을 한 칸 둔 다음 정답을 출력한다.</p>
</li>
<li><p>(t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)</p>
</li>
</ul>
<h4 id="예시"><strong>[예시]</strong></h4>
<table>
<thead>
<tr>
<th>입력</th>
<th>출력</th>
</tr>
</thead>
<tbody><tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>KOREAKOREAKOREAKOREAKOREAKOREA</td>
<td>#1 5</td>
</tr>
<tr>
<td>SAMSUNGSAMSUNGSAMSUNGSAMSUNGSA</td>
<td>#2 7</td>
</tr>
<tr>
<td>GALAXYGALAXYGALAXYGALAXYGALAXY</td>
<td>#3 6</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">for test_case in range(1, T + 1):
    #print(&quot;testcase: &quot;, test_case)  
    inputval = input()
    # input에서 한줄을 인식해온다 - KOREAKOREAKOREAKOREAKOREAKOREA
    for i in range(1, 11):
    # range에서 0을 포함하지 않은 이유는 
        if inputval[ : i ] == inputval[ i : i * 2 ] :    
        # 하나의 패턴이 그 다음에도 반복된다면
            if (inputval[:i] * (len(inputval)/i) == inputval):
            #그리고 이 패턴이 문자열 끝까지 이어진다면
                print(&quot;#&quot;+test_case+ &quot; &quot; + i )
                # 이 숫자가 문자열 중 가장 짧은 패턴일것이기 때문에 바로 break
                break</code></pre>
<p>라고 작성했는데 계속 runtime error 가 나타났다 SWEA 플랫폼은 처음이라 잘 모르겠어서 일단 여기에 글로써 남겨둔다
다른 사람들의 풀이도 검색해봤는데 내 풀이와 큰 차이가 없었고..? 당황스럽네</p>
<h3 id="다른-사람-풀이">다른 사람 풀이</h3>
<pre><code class="language-python">T = int(input())
for tc in range(1, T + 1):
    text = input()
    pattern =[]
    next_pattern=[]
    ans = 0
    for i in range(11):                    # 마디의 최대 길이가 10이므로 range(11)
        pattern = text[:i]                # patten리스트에 패턴 입력
        next_pattern = text[i:i*2]        # 다음 패턴 입력
        if i!=0 and pattern == next_pattern :    # 다음 패턴과 이번 패턴이 같은경우
            ans = len(pattern)            # 길이 출력
            break
    print(&#39;#{} {}&#39;.format(tc, ans))</code></pre>
<p>흠 다시 봐도 내거랑 크게 다르지 않다 심지어 이 사람은 내가 추가로 고려해줬던 두번째 if 문에 해당하는 경우에 대한 예외사항을 체크하지 않았다 
ex. aaaacaaaac의 경우에는 aaaac가 한 마디이므로 5가 되어야하는데, 이 코드대로 한다면 1을 리턴할 것이기 때문이다 </p>
<p>아직은 왜 틀렸는지 잘 모르겠어서.. 일단은 여기에 적어두겠다 
D2에 해당하는 문제여서 금방 풀었는데 컴파일은 되고 결과가 나오지 않아 당황스러울 뿐</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv0.가위바위보]]></title>
            <link>https://velog.io/@zzaerynn_/Lv0.%EA%B0%80%EC%9C%84%EB%B0%94%EC%9C%84%EB%B3%B4</link>
            <guid>https://velog.io/@zzaerynn_/Lv0.%EA%B0%80%EC%9C%84%EB%B0%94%EC%9C%84%EB%B3%B4</guid>
            <pubDate>Mon, 03 Apr 2023 11:53:19 GMT</pubDate>
            <description><![CDATA[<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/120839">[가위바위보]</a></p>
<h3 id="문제-설명">문제 설명</h3>
<p>가위는 2 바위는 0 보는 5로 표현합니다. 가위 바위 보를 내는 순서대로 나타낸 문자열 rsp가 매개변수로 주어질 때, rsp에 저장된 가위 바위 보를 모두 이기는 경우를 순서대로 나타낸 문자열을 return하도록 solution 함수를 완성해보세요.</p>
<h3 id="제한사항">제한사항</h3>
<ul>
<li>0 &lt; rsp의 길이 ≤ 100</li>
<li>rsp와 길이가 같은 문자열을 return 합니다.</li>
<li>rsp는 숫자 0, 2, 5로 이루어져 있습니다</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>rsp</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>&quot;2&quot;</td>
<td>&quot;0&quot;</td>
</tr>
<tr>
<td>&quot;205&quot;</td>
<td>&quot;052&quot;</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(rsp):
    answer = &#39;&#39;
    for i in range(len(rsp)):
        if rsp[i] == &#39;0&#39;:
            answer += &#39;5&#39;
        elif rsp[i] == &#39;2&#39;:
            answer += &#39;0&#39;
        elif rsp[i] == &#39;5&#39; :
            answer += &#39;2&#39;
    return answer</code></pre>
<p>잼민이 냄새가 폴폴 나네요... 1학년 같음</p>
<h3 id="다른-사람-풀이">다른 사람 풀이</h3>
<p>마음에 드는 풀이가 꽤나 많았다 신기한 코드들 조아</p>
<h4 id="다른사람-풀이-1">다른사람 풀이 1</h4>
<pre><code class="language-python">def solution(rsp):
    return rsp.translate(str.maketrans(&#39;025&#39;, &#39;502&#39;))</code></pre>
<p>translate 이라는 함수를 처음 본 나.. </p>
<h4 id="다른-사람-풀이-2">다른 사람 풀이 2</h4>
<pre><code class="language-python">def solution(rsp):
    d = {&#39;0&#39;:&#39;5&#39;,&#39;2&#39;:&#39;0&#39;,&#39;5&#39;:&#39;2&#39;}
    return &#39;&#39;.join(d[i] for i in rsp)</code></pre>
<p>써도써도 익숙해지지 않는 .. ㅋㅋ.... dictionary 제발 공부해야지</p>
<h4 id="다른-사람-풀이-3">다른 사람 풀이 3</h4>
<pre><code class="language-python">def solution(rsp):
    rsp =rsp.replace(&#39;2&#39;,&#39;s&#39;)
    rsp =rsp.replace(&#39;5&#39;,&#39;p&#39;)
    rsp =rsp.replace(&#39;0&#39;,&#39;r&#39;)
    rsp =rsp.replace(&#39;r&#39;,&#39;5&#39;)
    rsp =rsp.replace(&#39;s&#39;,&#39;0&#39;)
    rsp =rsp.replace(&#39;p&#39;,&#39;2&#39;)
    return rsp</code></pre>
<p>접근법 자체는 나랑 비슷했는데 한번에 replace 한다는 점에서 긴 문자열에 유용할 것 같다는 생각이 들었다 </p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv0. 짝수는 싫어요]]></title>
            <link>https://velog.io/@zzaerynn_/Lv0.-%EC%A7%9D%EC%88%98%EB%8A%94-%EC%8B%AB%EC%96%B4%EC%9A%94</link>
            <guid>https://velog.io/@zzaerynn_/Lv0.-%EC%A7%9D%EC%88%98%EB%8A%94-%EC%8B%AB%EC%96%B4%EC%9A%94</guid>
            <pubDate>Mon, 03 Apr 2023 11:43:40 GMT</pubDate>
            <description><![CDATA[<p>[짝수는 싫어요]</p>
<h3 id="문제-설명">문제 설명</h3>
<p>정수 n이 매개변수로 주어질 때, n 이하의 홀수가 오름차순으로 담긴 배열을 return하도록 solution 함수를 완성해주세요.</p>
<h3 id="제한사항">제한사항</h3>
<p>1 ≤ n ≤ 100</p>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>n</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>10</td>
<td>[1, 3, 5, 7, 9]</td>
</tr>
<tr>
<td>15</td>
<td>[1, 3, 5, 7, 9, 11, 13, 15]</td>
</tr>
</tbody></table>
<hr>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(n):
    answer = list(range(1,n+1,2))
    return answer</code></pre>
<p>arange 대신 list(range)를 생각해내야하는게 매번 좀 빡세다 
대신 다른 방법에 익숙해져야겠다</p>
<h3 id="다른-사람-풀이">다른 사람 풀이</h3>
<pre><code class="language-python">def solution(n):
    return [i for i in range(1, n+1, 2)]</code></pre>
<p>보면 이해가 되지만 막상 내가 짜기엔 좀 어려운 감이 있다 익숙하지 않아서 그런가봐</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv0. 옹알이(1)]]></title>
            <link>https://velog.io/@zzaerynn_/Lv0.-%EC%98%B9%EC%95%8C%EC%9D%B41</link>
            <guid>https://velog.io/@zzaerynn_/Lv0.-%EC%98%B9%EC%95%8C%EC%9D%B41</guid>
            <pubDate>Mon, 03 Apr 2023 11:38:04 GMT</pubDate>
            <description><![CDATA[<h3 id="문제-설명">문제 설명</h3>
<p>머쓱이는 태어난 지 6개월 된 조카를 돌보고 있습니다. 조카는 아직 &quot;aya&quot;, &quot;ye&quot;, &quot;woo&quot;, &quot;ma&quot; 네 가지 발음을 최대 한 번씩 사용해 조합한(이어 붙인) 발음밖에 하지 못합니다. 문자열 배열 babbling이 매개변수로 주어질 때, 머쓱이의 조카가 발음할 수 있는 단어의 개수를 return하도록 solution 함수를 완성해주세요.</p>
<h3 id="제한사항">제한사항</h3>
<ul>
<li>1 ≤ babbling의 길이 ≤ 100</li>
<li>1 ≤ babbling[i]의 길이 ≤ 15</li>
<li>babbling의 각 문자열에서 &quot;aya&quot;, &quot;ye&quot;, &quot;woo&quot;, &quot;ma&quot;는 각각 최대 한 번씩만 등장합니다.</li>
<li>즉, 각 문자열의 가능한 모든 부분 문자열 중에서 &quot;aya&quot;, &quot;ye&quot;, &quot;woo&quot;, &quot;ma&quot;가 <strong>한 번씩만</strong> 등장합니다.</li>
<li>문자열은 알파벳 소문자로만 이루어져 있습니다.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>babbling</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>[&quot;aya&quot;, &quot;yee&quot;, &quot;u&quot;, &quot;maa&quot;, &quot;wyeoo&quot;]</td>
<td>1</td>
</tr>
<tr>
<td>[&quot;ayaye&quot;, &quot;uuuma&quot;, &quot;ye&quot;, &quot;yemawoo&quot;, &quot;ayaa&quot;]</td>
<td>3</td>
</tr>
</tbody></table>
<hr>
<h3 id="풀이">풀이</h3>
<h4 id="내-풀이">내 풀이</h4>
<pre><code class="language-python">def solution(babbling):
    for i in range(len(babbling)):
        babbling[i] = babbling[i].replace(&quot;aya&quot;, &quot;/&quot;)
        babbling[i] = babbling[i].replace(&quot;woo&quot;, &quot;/&quot;)
        babbling[i] = babbling[i].replace(&quot;ye&quot;, &quot;/&quot;)
        babbling[i] = babbling[i].replace(&quot;ma&quot;, &quot;/&quot;)
        # &quot;&quot; 가 아니라 &#39;/&#39; 를 선택한 이유는 &#39;&#39;로 했을때 
        # wyeoo 같은 문자에서 ye가 사라진 후 woo가 인식되는 
        # 경우가 발생했기 때문
    for i in range(len(babbling)):
        babbling[i] = babbling[i].replace(&quot;/&quot;,&quot;&quot;)
        # 추후에 /를 없애서 수를 셈으로써 순서의 혼용으로 인한 경우를 방지함
    answer = babbling.count(&#39;&#39;)
    return answer</code></pre>
<h4 id="다른-사람-풀이">다른 사람 풀이</h4>
<p>re 를 이용한 풀이</p>
<pre><code class="language-python">import re

def solution(babbling):
    regex = re.compile(&#39;^(aya|ye|woo|ma)+$&#39;)
    cnt=0
    for e in babbling:
        if regex.match(e):
            cnt+=1
    return cnt</code></pre>
<p>re를 이용한 풀이를 생각해보려고 했으나 내가 했던 방법이 가장 쉽게 생각할 수 있는 방법이라 저렇게 풀었다 re를 사용하면 general expression이 표현 가능해지므로 다양한 형태를 표현할 수 있다. </p>
<p>다양한 풀이들이 있었으나 여기서 마무리</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv0. 영어가 싫어요]]></title>
            <link>https://velog.io/@zzaerynn_/Lv0.-%EC%98%81%EC%96%B4%EA%B0%80-%EC%8B%AB%EC%96%B4%EC%9A%94</link>
            <guid>https://velog.io/@zzaerynn_/Lv0.-%EC%98%81%EC%96%B4%EA%B0%80-%EC%8B%AB%EC%96%B4%EC%9A%94</guid>
            <pubDate>Thu, 30 Mar 2023 16:10:24 GMT</pubDate>
            <description><![CDATA[<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/120894">[영어가 싫어요]</a></p>
<p><strong>문제 설명</strong>
영어가 싫은 머쓱이는 영어로 표기되어있는 숫자를 수로 바꾸려고 합니다. 문자열 numbers가 매개변수로 주어질 때, numbers를 정수로 바꿔 return 하도록 solution 함수를 완성해 주세요.</p>
<p><strong>제한사항</strong></p>
<ul>
<li>numbers는 소문자로만 구성되어 있습니다.</li>
<li>numbers는 &quot;zero&quot;, &quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;, &quot;six&quot;, &quot;seven&quot;, &quot;eight&quot;, &quot;nine&quot; 들이 공백 없이 조합되어 있습니다.</li>
<li>1 ≤ numbers의 길이 ≤ 50</li>
<li>&quot;zero&quot;는 numbers의 맨 앞에 올 수 없습니다.</li>
</ul>
<p><strong>입출력 예시</strong></p>
<table>
<thead>
<tr>
<th>numbers</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>&quot;onetwothreefourfivesixseveneightnine&quot;</td>
<td>123456789</td>
</tr>
<tr>
<td>&quot;onefourzerosixseven&quot;</td>
<td>14067</td>
</tr>
</tbody></table>
<hr>
<h2 id="문제-풀이">문제 풀이</h2>
<h3 id="내-풀이">내 풀이</h3>
<pre><code class="language-python">def solution(numbers):
    answer = numbers
    if (&#39;one&#39; in numbers):
        answer = answer.replace(&#39;one&#39;, &#39;1&#39;)
    if (&#39;two&#39; in numbers):
        answer =answer.replace(&#39;two&#39;, &#39;2&#39;)
    if (&#39;three&#39; in numbers):
        answer =answer.replace(&#39;three&#39;, &#39;3&#39;)
    if (&#39;four&#39; in numbers):
        answer =answer.replace(&#39;four&#39;, &#39;4&#39;)
    if (&#39;five&#39; in numbers):
        answer =answer.replace(&#39;five&#39;, &#39;5&#39;)
    if (&#39;six&#39; in numbers):
        answer =answer.replace(&#39;six&#39;, &#39;6&#39;)
    if (&#39;seven&#39; in numbers):
        answer =answer.replace(&#39;seven&#39;, &#39;7&#39;)
    if (&#39;eight&#39; in numbers):
        answer =answer.replace(&#39;eight&#39;, &#39;8&#39;)
    if (&#39;nine&#39; in numbers):
        answer = answer.replace(&#39;nine&#39;, &#39;9&#39;)
    if (&#39;zero&#39; in numbers):
        answer =answer.replace(&#39;zero&#39;, &#39;0&#39;)
    return int(answer)</code></pre>
<p>비효율의 끝판왕.. 이렇게 한 이유는 enumerate 함수를 몰랐기 때문이다 dictionary를 가져와서 쓸까 잠시 고민했지만 dictionary를 잘 모르기 떄문에 벌어진 참사</p>
<h3 id="다른-사람-풀이-1">다른 사람 풀이 1</h3>
<pre><code class="language-python">def solution(numbers):
    for num, eng in enumerate([&quot;zero&quot;, &quot;one&quot;, &quot;two&quot;, &quot;three&quot;, &quot;four&quot;, &quot;five&quot;, &quot;six&quot;, &quot;seven&quot;, &quot;eight&quot;, &quot;nine&quot;]):
        numbers = numbers.replace(eng, str(num))
    return int(numbers)</code></pre>
<p>조금은 효율이 나아진 풀이
Enumerate 함수를 쓰면 해당 리스트에서 element의 인덱스, 값 을 차례로 tuple로 return 한다. 이 예시에서는 리스트를 0부터 시작하게 했지만 만약 1부터 시작하게 하고 싶을 경우에는 start 옵션을 줄 수도 있다는게 장점이었다</p>
<h3 id="다른-사람-풀이-2">다른 사람 풀이 2</h3>
<pre><code class="language-python">ef solution(numbers):
    r = {&#39;zero&#39;: &#39;0&#39;, &#39;one&#39;: &#39;1&#39;, &#39;two&#39;: &#39;2&#39;, &#39;three&#39;: &#39;3&#39;, &#39;four&#39;: &#39;4&#39;,
         &#39;five&#39;: &#39;5&#39;, &#39;six&#39;: &#39;6&#39;, &#39;seven&#39;: &#39;7&#39;, &#39;eight&#39;: &#39;8&#39;, &#39;nine&#39;: &#39;9&#39;}
    for k in r.keys():
        numbers = numbers.replace(k, r[k])
    return int(numbers)</code></pre>
<p>dictionary를 이용해서 풀어낸 풀이. str(i)로 replace 한 것도 좀 똑똑하지 않았나 뭐 그런 생각
아직은 갈길이 멀다..!</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Lv0. 한 번만 등장한 문자]]></title>
            <link>https://velog.io/@zzaerynn_/Lv0.-%ED%95%9C-%EB%B2%88%EB%A7%8C-%EB%93%B1%EC%9E%A5%ED%95%9C-%EB%AC%B8%EC%9E%90</link>
            <guid>https://velog.io/@zzaerynn_/Lv0.-%ED%95%9C-%EB%B2%88%EB%A7%8C-%EB%93%B1%EC%9E%A5%ED%95%9C-%EB%AC%B8%EC%9E%90</guid>
            <pubDate>Fri, 03 Mar 2023 17:17:04 GMT</pubDate>
            <description><![CDATA[<p><a href="https://school.programmers.co.kr/learn/courses/30/lessons/120896">[한번만 등장한 문자]</a></p>
<h3 id="문제-설명">문제 설명</h3>
<p>문자열 s가 매개변수로 주어집니다. s에서 한 번만 등장하는 문자를 사전 순으로 정렬한 문자열을 return 하도록 solution 함수를 완성해보세요. 한 번만 등장하는 문자가 없을 경우 빈 문자열을 return 합니다.</p>
<h3 id="제한사항">제한사항</h3>
<ul>
<li>0 &lt; s의 길이 &lt; 1,000</li>
<li>s는 소문자로만 이루어져 있습니다.</li>
</ul>
<h3 id="입출력-예">입출력 예</h3>
<table>
<thead>
<tr>
<th>s</th>
<th>result</th>
</tr>
</thead>
<tbody><tr>
<td>&quot;abcabcadc&quot;</td>
<td>&quot;d&quot;</td>
</tr>
<tr>
<td>&quot;abdc&quot;</td>
<td>&quot;abcd&quot;</td>
</tr>
<tr>
<td>&quot;hello&quot;</td>
<td>&quot;eho&quot;</td>
</tr>
</tbody></table>
<hr>
<h3 id="풀이">풀이</h3>
<h4 id="내-풀이">내 풀이</h4>
<pre><code class="language-python">import numpy as np

def solution(s):
    answer = &#39;&#39;
    s_sort = sorted(s)
    letters, counts= np.unique(s_sort, return_counts= True)
    for i in range(len(letters)):
        if counts[i]==1:
            answer += letters[i]
    return answer</code></pre>
<p>뭘까... 뭔가 해냈지만 짜잔 하고 해낸게 아니라 얼레벌레 해낸거같은 느낌은.. 
처음에 조건을 잘못읽고 unique 한걸 고르라는줄 알고 뭐야 쉬운데? 이러면서 대충 했는데 이게 아니었던거지
queue를 쓰면 되나? 싶다가도 그러면 해결이 안돼서 unique를 사용했다 </p>
<hr>
<p>해결하는 것만 일이 아니라 해결하고 나서도 다른 사람들 풀이를 꼭 확인하는데 그럼 여러가지 댓글이 달려있다 현업에서는 이 함수 쓰면 안된다는등등.. 어렵다...........................</p>
<h4 id="다른-사람-풀이-1">다른 사람 풀이 1</h4>
<pre><code class="language-python">def solution(s):
    answer = &quot;&quot;.join(sorted([ ch for ch in s if s.count(ch) == 1]))
    return answer</code></pre>
<p>in s 대신 in set(s)를 사용하면 중복 조회를 줄일 수 있다는 게 다른 의견이었는데 좋은 것 같다 범위를 줄여가는 것이 중요하니까 </p>
<h4 id="다른-사람-풀이-2">다른 사람 풀이 2</h4>
<pre><code class="language-python">from collections import Counter

def solution(s):
    counter = Counter(s)
    unqiue_alphabets = filter(lambda alphabet: counter[alphabet] == 1, counter.keys())
    return &#39;&#39;.join(sorted(unqiue_alphabets))</code></pre>
<p>프로그래머스를 하다보면 다른 사람들의 코드를 필연적으로 보게 되는데 그럴때마다 collections는 거의 빠지지 않고 나온다 학교에서는 잘 쓸 일이 없던 모듈이어서 몰랐나 공부해봐야겠따 </p>
]]></description>
        </item>
    </channel>
</rss>