Skip to content

Commit 9536576

Browse files
committed
[Add] static codes
1 parent 6fdd7cd commit 9536576

File tree

4 files changed

+136
-0
lines changed

4 files changed

+136
-0
lines changed

static/codes/python-compare

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import time
2+
import tracemalloc
3+
import math
4+
import copy
5+
6+
def benchmark_functions(func_name, sizes, datas, iterations=5):
7+
results = {}
8+
9+
for solution in solutions:
10+
name = solution.__module__
11+
results[name] = {"time": [], "memory": []}
12+
13+
for size, data in zip(sizes, datas):
14+
# 실행 시간 및 메모리 측정
15+
total_time = 0
16+
total_memory = 0
17+
for _ in range(iterations):
18+
test_data = copy.deepcopy(data)
19+
20+
# 메모리 사용량 측정 시작
21+
tracemalloc.start()
22+
start_time = time.time()
23+
24+
# rotate 함수 실행
25+
func = getattr(solution, func_name)
26+
27+
if isinstance(test_data, tuple):
28+
func(*test_data)
29+
else:
30+
func(test_data)
31+
32+
# 실행 시간 측정 종료
33+
total_time += (time.time() - start_time)
34+
35+
# 메모리 측정 종료
36+
current, peak = tracemalloc.get_traced_memory()
37+
tracemalloc.stop()
38+
39+
# 피크 메모리 사용량 측정
40+
total_memory += peak
41+
42+
avg_time = total_time / iterations
43+
avg_memory = total_memory / iterations
44+
results[name]["time"].append((size, avg_time))
45+
results[name]["memory"].append((size, avg_memory))
46+
47+
return results
48+
49+
# Big-O 추정 함수 (외부 라이브러리 없이 구현)
50+
def estimate_big_o(results):
51+
for name, data in results.items():
52+
valid_data = [[size, time_taken] for size, time_taken in data["time"] if time_taken >= 0.001]
53+
54+
times = [time_taken for _, time_taken in valid_data]
55+
sizes = [size for size, _ in valid_data]
56+
57+
# 로그 변환하여 시간과 크기의 관계를 분석
58+
log_sizes = [math.log(size) for size in sizes]
59+
log_times = [math.log(time) for time in times]
60+
61+
# 선형 회귀 계산 (단순히 기울기를 추정)
62+
# 기울기 계산: (x1, y1), (x2, y2) 두 점의 기울기 = (y2 - y1) / (x2 - x1)
63+
if len(log_sizes) > 1:
64+
# 첫 번째와 마지막 점을 기준으로 기울기 추정
65+
delta_log_size = log_sizes[-1] - log_sizes[0]
66+
delta_log_time = log_times[-1] - log_times[0]
67+
if delta_log_size != 0:
68+
slope = delta_log_time / delta_log_size
69+
print(f"{name} Big-O 추정: O(n^{slope:.2f})")
70+
else:
71+
print(f"{name} Big-O 추정 실패: 로그 크기 차이가 0")
72+
else:
73+
print(f"{name} Big-O 추정 실패: 데이터가 부족합니다.")
74+
75+
def print_results(results):
76+
print("크기별 실행 시간 및 메모리 사용량 비교")
77+
for name, data in results.items():
78+
print(f"\n{name} 결과:")
79+
for (size, time_taken), (_, memory_used) in zip(data["time"], data["memory"]):
80+
print(f"크기 {size}: 시간 {time_taken:.4f}초, 메모리 {memory_used} bytes")
81+
print()

static/codes/python-env

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# 가상 파일을 모듈로 로드하는 함수
2+
def load_virtual_module(name):
3+
"""Load a virtual module from the virtual_files dictionary."""
4+
if name in virtual_files:
5+
code = virtual_files[name]
6+
module = types.ModuleType(name) # 새 모듈 객체 생성
7+
exec(code, module.__dict__) # 모듈의 __dict__에 코드 실행 결과 저장
8+
sys.modules[name] = module # sys.modules에 등록
9+
else:
10+
raise ImportError(f"No module named '{name}'")
11+
12+
# 모든 가상 파일을 sys.modules에 등록
13+
for file_name in virtual_files.keys():
14+
module_name = file_name.rsplit(".", 1)[0] # 파일 이름에서 .py 제거
15+
load_virtual_module(module_name)
16+
17+
solutions = list()

static/codes/python-footer

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
benchmark_results = benchmark_functions(func_name, sizes, datas)
2+
3+
# 결과 출력 및 Big-O 추정
4+
print_results(benchmark_results)
5+
estimate_big_o(benchmark_results)

static/codes/python-header

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from typing import List, Optional
2+
import builtins
3+
4+
list = builtins.list
5+
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
def list_to_tree(lst):
13+
if not lst:
14+
return None
15+
16+
root = TreeNode(lst[0])
17+
queue = [root]
18+
i = 1
19+
20+
while i < len(lst):
21+
node = queue.pop(0)
22+
23+
if lst[i] is not None:
24+
node.left = TreeNode(lst[i])
25+
queue.append(node.left)
26+
i += 1
27+
28+
if i < len(lst) and lst[i] is not None:
29+
node.right = TreeNode(lst[i])
30+
queue.append(node.right)
31+
i += 1
32+
33+
return root

0 commit comments

Comments
 (0)