Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Cache
__pycache__/

# IDE
.vscode/settings.json
20 changes: 20 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import pytest
from utils import load_prefixed_functions, profile_function

@pytest.fixture
def load_func():
"""Load function from current directory files prefixed with defined prefix

for example to use function_a, you would type: load_func("function_a")
"""
def _load(prefix: str):
return load_prefixed_functions(prefix)
return _load


@pytest.fixture
def profile():
"""Profile function and return reports"""
def _runner(func, *args, **kwargs):
return profile_function(func, *args, **kwargs)
return _runner
35 changes: 35 additions & 0 deletions data_structure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import random


class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

@classmethod
def from_list(cls, values):
"""Builds a linked list from a list of values and returns the head."""
if not values:
return None
head = cls(values[0])
current = head
for val in values[1:]:
current.next = cls(val)
current = current.next
return head

@classmethod
def generate_random(cls, count=10, low=1, high=100):
"""Generate a linked list of random, unique integers."""
if high - low + 1 < count:
raise ValueError("Range too small for the requested number of unique values.")
values = random.sample(range(low, high + 1), count)
return cls.from_list(sorted(values))

def print_list(self):
"""Prints the linked list starting from the current node."""
current = self
while current:
print(current.val, end=" -> ")
current = current.next
print("None")
29 changes: 29 additions & 0 deletions max_avg_sub_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
Given an array we want to find the maximum average of a sub array of size k.
We can do this in O(n) time using a sliding window approach.
"""

import timeit
import cProfile
import random


def max_avg_sub_array(arr: list[int], k: int=10):
n = len(arr)
window_sum = sum(arr[:k])
max_avg = window_sum / k

for i in range(k, n):
window_sum += arr[i] - arr[i - k]
max_avg = max(max_avg, window_sum / k)

return max_avg


random_array = [random.randint(-100000, 100000) for _ in range(100000)]
time_a = timeit.timeit(lambda: max_avg_sub_array(random_array), number=10)

print(f"Function time: {time_a:.6f} seconds")

print("\nProfiling Function:")
cProfile.run("max_avg_sub_array(random_array)")
31 changes: 31 additions & 0 deletions merge_list_nodes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
Given 2 lists of nodes in ascending order, merge them into a single list in ascending order.
"""

import timeit
from struct import ListNode

POW = 5

def merge_sorted_lists(list1, list2):
"""Merge two sorted lists into a single sorted list."""

dummy = ListNode(val=-1)
curr = dummy

while list1 and list2:
if list1.val < list2.val:
curr.next = list1
list1 = list1.next
else:
curr.next = list2
list2 = list2.next

curr.next = list1 if list1 else list2
return dummy.next

list1 = ListNode.generate_random(count=10**POW, low=1, high=99**POW)
list2 = ListNode.generate_random(count=10**POW, low=101**POW, high=199**POW)

time_a = timeit.timeit(lambda: merge_sorted_lists(list1, list2), number=100)
print(f"Function time: {time_a:.6f} seconds")
1 change: 1 addition & 0 deletions test_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import pytest
33 changes: 33 additions & 0 deletions utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import os
import io
import pstats
import cProfile
from importlib import import_module


def load_prefixed_functions(prefix: str):
"""Import problem function resolver identified by file prefix"""
funcs = {}
for f in os.listdir("."):
if f.startswith(prefix) and f.endswith(".py"):
mod = import_module(f[:-3])
func_name = f[5:-3] # strip "func_" and ".py"
funcs[func_name] = getattr(mod, func_name)
return funcs


def profile_function(func, *args, **kwargs):
"""Show function execution time and cProfile detail reports"""
pr = cProfile.Profile()
pr.enable()
result = func(*args, **kwargs)
pr.disable()

s = io.StringIO()
sortby = 'tottime'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())

return result