99클럽 코테 스터디 6일차 TIL + 힙(Heap): smallest-number-in-infinite-set

Saang Bum Kim·2024년 5월 25일
0

99클럽

목록 보기
42/59
post-thumbnail

문제

링크텍스트

풀이

  • leetcode에 맞게 문제 풀이 template 만드는게 까다로왔다.
  • class SmallestInfiniteSet
    • a: b 보다 작은 자연수들로 구성된 heap
    • b: 연속한 무한 자연수열 중 최소값
  • refactoring 습관을 기르려고 합니다 ^^ (ref. 링크텍스트)
  • 시간이 흐려면서 연속한 무한 자연수열 중 일부가 a에 포함될 수 있지 않나 싶기도 합니다 ㅠㅠ

결과

def f_t(id_t):
    if id_t == 0:
        c = zip(["SmallestInfiniteSet", "addBack", \
                 "popSmallest", "popSmallest", "popSmallest", \
                 "addBack", "popSmallest", "popSmallest", "popSmallest"], \
                [[], [2], [], [], [], [1], [], [], []])
        r = [None, None, 1, 2, 3, None, 1, 4, 5]
    return c,r

import heapq

class SmallestInfiniteSet:

    def __init__(self):
        self.a = []
        self.b = 1

    def popSmallest(self) -> int:
        if not self.a:
            self.b += 1
            return self.b-1
        else:
            return heapq.heappop(self.a)

    def addBack(self, num: int) -> None:
        if self.b <= num:
            return        
        if not num in self.a:
            heapq.heappush(self.a, num)
        return
            
for i in range(1):
    c, r = f_t(i)
    a = []
    for i in c:
        if i[0][0] == 'S':
            exec('o = '+i[0]+'()')
            a.append(None)
        else:
            if i[1]:
                a.append(exec('o.'+i[0]+'(i[1][0])'))
            else:
                exec('b = o.'+i[0]+'()')
                a.append(b)
    print(a)
    print(r)

profile
old engineer

0개의 댓글