Skip to content

Commit 972c25e

Browse files
committed
solved(python): programmers
- 2023 KAKAO BLIND RECRUITMENT / 표현 가능한 이진트리
1 parent ef514e2 commit 972c25e

4 files changed

Lines changed: 98 additions & 0 deletions

File tree

programmers/2023_KAKAO_BLIND_RECRUITMENT/python/표현_가능한_이진트리/__init__.py

Whitespace-only changes.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import math
2+
from collections import deque
3+
from typing import List
4+
5+
6+
def solution(numbers: List[int]) -> List[int]:
7+
return [int(is_binary(num)) for num in numbers]
8+
9+
10+
def is_binary(num: int) -> bool:
11+
binary = to_binary(num)
12+
queue, count = deque([(1, len(binary))]), 0
13+
14+
while queue:
15+
left, right = queue.popleft()
16+
mid = (left + right) // 2
17+
18+
if binary[mid - 1] == 0:
19+
continue
20+
21+
count += 1
22+
if left < mid:
23+
queue.append((left, mid - 1))
24+
if mid < right:
25+
queue.append((mid + 1, right))
26+
27+
return count == binary.count(1)
28+
29+
30+
def to_binary(num: int) -> List[int]:
31+
binary = []
32+
while num:
33+
binary.append(num & 1)
34+
num >>= 1
35+
36+
size = len(binary)
37+
for _ in range(size + 1, 2 ** (int(math.log2(size)) + 1)):
38+
binary.append(0)
39+
40+
return binary[::-1]
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
[
2+
{
3+
"params": [
4+
[
5+
7,
6+
42,
7+
5
8+
]
9+
],
10+
"expected": [
11+
1,
12+
1,
13+
0
14+
]
15+
},
16+
{
17+
"params": [
18+
[
19+
63,
20+
111,
21+
95
22+
]
23+
],
24+
"expected": [
25+
1,
26+
1,
27+
0
28+
]
29+
}
30+
]
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import json
2+
import os
3+
import unittest
4+
5+
from parameterized import parameterized
6+
7+
from .main import solution
8+
9+
10+
def load_sample(filename: str):
11+
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
12+
13+
with open(path, "r") as file:
14+
return [(case["params"], case["expected"]) for case in json.load(file)]
15+
16+
17+
class TestCase(unittest.TestCase):
18+
@parameterized.expand(load_sample("sample.json"))
19+
def test_case(self, params: list, expected: any):
20+
# When
21+
result = solution(*params)
22+
23+
# Then
24+
self.assertEqual(expected, result)
25+
26+
27+
if __name__ == "__main__":
28+
unittest.main()

0 commit comments

Comments
 (0)