[Mock] Uber 2

shsh·2021년 7월 13일
0

Mock

목록 보기
83/93

1281. Subtract the Product and Sum of Digits of an Integer

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

My Answer 1: Accepted (Runtime: 28 ms - 81.50% / Memory Usage: 14.3 MB - 39.63%)

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        product = 1
        sums = 0
        
        while n:
            product *= n%10
            sums += n%10
            n //= 10
        
        return product - sums

고대로 productsum 구해서 서로 빼주기


1188. Design Bounded Blocking Queue

Implement a thread-safe bounded blocking queue that has the following methods:

  • BoundedBlockingQueue(int capacity) The constructor initializes the queue with a maximum capacity.
  • void enqueue(int element) Adds an element to the front of the queue. If the queue is full, the calling thread is blocked until the queue is no longer full.
  • int dequeue() Returns the element at the rear of the queue and removes it. If the queue is empty, the calling thread is blocked until the queue is no longer empty.
  • int size() Returns the number of elements currently in the queue.

Your implementation will be tested using multiple threads at the same time. Each thread will either be a producer thread that only makes calls to the enqueue method or a consumer thread that only makes calls to the dequeue method. The size method will be called after every test case.

My Answer 1: Accepted (Runtime: 632 ms / Memory Usage: 5.64 MB) - 66.67%

# you can import any package that you need here
# write your code here

from queue import Queue

class BoundedBlockingQueue:
    def __init__(self, capacity: int):
        """
        @param capacity: maximum queue size
        """
        self.queue = Queue(capacity)

    def enqueue(self, element: int) -> None:
        """
        @param element: the element given to be added
        @return: nothing
        """
        self.queue.put(element)

    def dequeue(self) -> int:
        """
        @return: pop an element from the front of queue
        """
        element = self.queue.get()
        return element

    def size(self) -> int:
        """
        @return: size of queue
        """
        return self.queue.qsize()

이번에도 lintcode~
https://www.lintcode.com/problem/2462/

처음에는 라이브러리를 최대한 안쓰고자
queue, maxsize, waiting, block 변수들을 만듦

enqueue blocking 은 waiting 리스트에 저장해두기

dequeue blocking 은 block 변수에 T/F 를 저장해서
다음 enqueue 할 때, block == T => 막혔던 dequeue 해주는 걸로 하려했는데...

코드 돌아가는 걸 보니까
input 순서대로 enqueue, dequeue 가 실행되는 게 아닌 거 같음..

그리고 그동안 main.py 를 공개한 적이 없는데 공개한 걸 보니 뭔가 단서일 듯..

main.py 에서 thread 를 처리하는 것을 보고 서치해보니까
python 라이브러리 Queue 를 사용해야겠구나 판단

Queue(size) => 최대 사이즈가 size 인 queue 생성
put(), get() => element 추가, 삭제 / 이 함수들이 알아서 blocking 해줌
qsize() => queue 크기


queue 에서 blocking 기능을 제공하는 건 첨 알았네요...

Python queue library
https://docs.python.org/ko/3.7/library/queue.html

Thread와 Queue
https://nalara12200.tistory.com/144


Solution 1: Accepted (Runtime: 634 ms / Memory Usage: 5.50 MB) - 63.64%

# you can import any package that you need here
# write your code here

from collections import deque
from threading import Condition

class BoundedBlockingQueue:
    def __init__(self, capacity: int):
        """
        @param capacity: maximum queue size
        """
        self.capacity = capacity
        self.queue = deque()
        self.condition = Condition()

    def enqueue(self, element: int) -> None:
        """
        @param element: the element given to be added
        @return: nothing
        """
        with self.condition: # acquire and release
            while len(self.queue) >= self.capacity:
                self.condition.wait()
            
            self.queue.append(element)
            self.condition.notify()

    def dequeue(self) -> int:
        """
        @return: pop an element from the front of queue
        """
        with self.condition:
            while len(self.queue) == 0:
                self.condition.wait()
            
            element = self.queue.popleft()
            self.condition.notify()
            return element

    def size(self) -> int:
        """
        @return: size of queue
        """
        with self.condition:
            return len(self.queue)

deque 와 threading 의 Condition 을 사용한 방식

condition 을 wait() 로 멈췄다가 notify() 로 깨우는 듯

threading 라이브러리의 Condition
https://docs.python.org/ko/3/library/threading.html

이 문제.. 라이브러리 모르면 못 푸는 거 아닌가요...

profile
Hello, World!

0개의 댓글