Compare commits

...

2 Commits

Author SHA1 Message Date
65e8af6bb7 Added small cli for templating leetcode exercises 2022-08-31 12:28:56 +02:00
2f32bdc7b9 Add 2 more exercises 2022-08-31 12:00:11 +02:00
5 changed files with 125 additions and 0 deletions

41
cli.py Normal file
View File

@ -0,0 +1,41 @@
import click
import jinja2
from os import path
class LeetCode:
@staticmethod
def filename_from_url(url: str) -> str:
num = input("Number: ")
name = url.split("/")[4].replace("-", "_")
return f"{num}_{name}.py"
@click.group()
@click.option("--template-dir", default="./templates")
@click.pass_context
def cli(ctx: click.Context, template_dir: str):
ctx.obj["template"] = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir)
)
@cli.command()
@click.pass_context
@click.argument("url")
def leetcode(ctx: click.Context, url: str):
file_path = path.join("leetcode", LeetCode.filename_from_url(url))
if path.exists(file_path):
print("File already exists")
return 1
templates: jinja2.Environment = ctx.obj["template"]
templ = templates.get_template("leetcode.j2")
result = templ.render()
with open(file_path, mode="w", encoding="utf8") as f:
f.write(result)
if __name__ == "__main__":
cli(obj={})

26
leetcode/69_sqrtx.py Normal file
View File

@ -0,0 +1,26 @@
import pytest
class Solution:
def mySqrt(self, x: int) -> int:
left, right = 0, x
while left <= right:
mid = left + (right - left) // 2
val = mid * mid
if val <= x < (mid + 1) * (mid + 1):
return mid
elif x < val:
right = mid - 1
else:
left = mid + 1
return 0
@pytest.fixture
def solution():
return Solution()
@pytest.mark.parametrize("x, expected", [(4, 2), (8, 2)])
def test_my_sqrt(solution: Solution, x: int, expected: int):
assert solution.mySqrt(x) == expected

View File

@ -0,0 +1,41 @@
import pytest
class Solution:
def search(self, nums: list[int], target: int) -> bool:
low, high = 0, len(nums) - 1
while low <= high:
breakpoint()
mid = low + (high - low) // 2
if nums[mid] == target:
return True
if nums[mid] >= nums[low]:
if nums[low] <= target <= nums[mid]:
high = mid - 1
else:
low = mid + 1
else:
if nums[mid] <= target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return False
@pytest.fixture
def solution():
return Solution()
@pytest.mark.parametrize(
"nums, target, expected",
[
# ([2, 5, 6, 0, 0, 1, 2], 0, True),
# ([2, 5, 6, 0, 0, 1, 2], 3, False),
([1, 0, 1, 1, 1], 0, True),
],
)
def test_search(solution: Solution, nums: list[int], target: int, expected: bool):
assert solution.search(nums, target) == expected

View File

@ -1,2 +1,4 @@
pytest
black
click
jinja2

15
templates/leetcode.j2 Normal file
View File

@ -0,0 +1,15 @@
import pytest
class Solution:
pass
@pytest.fixture
def solution():
return Solution()
@pytest.mark.parametrize("", [])
def test_search(solution: Solution):
pass