Skip to content

Instantly share code, notes, and snippets.

@hjue
Last active November 3, 2021 06:58
Show Gist options
  • Save hjue/a9c80d5bb31c75d5c9febcac2574f5fa to your computer and use it in GitHub Desktop.
Save hjue/a9c80d5bb31c75d5c9febcac2574f5fa to your computer and use it in GitHub Desktop.
leetcode-local
  • 从stdin传入测试数据
  • 动态加载实现函数
  • 运行函数
  • 检查输出是否正确
import copy
import os
import shutil
import sys
from traceback import extract_tb
import traceback
from types import TracebackType
from typing import Any, Callable, List, Optional, Tuple

# import color
# from color import format_color, use_color


def run_testcases(
    method: Callable[..., Any],
    tests: List[Tuple[Any, Any]],
    validator: Any,
) -> Tuple[List[Tuple[TracebackType, Any, Any, Any]], int]:
    """Run given test cases, and collect all failing assertions"""
    failed_testcases: List[Tuple[TracebackType, Any, Any, Any]] = []
    errored_count = 0

    for index, (inputs, expected) in enumerate(tests, start=1):
        try:
            validator(method, copy.deepcopy(inputs), expected)

            result = 'PASSED'

        except KeyboardInterrupt:
            break

        except Exception as exc:
            result = 'FAILED'

            if type(exc) != AssertionError:
                traceback.print_exc()
                errored_count += 1
                continue

            *_, trace = sys.exc_info()
            assert trace is not None

            if len(exc.args) != 1:
                raise ValueError(
                    "No assertion value provided in custom validator"
                ) from exc

            (assertion_values,) = exc.args
            if len(assertion_values) != 2:
                raise ValueError(
                    "Assertion value must be provided as (output, expected)"
                ) from exc

            output, expected = assertion_values
            failed_testcases.append((trace, inputs, expected, output))

        finally:
            test_case = f"Test {index} - ({', '.join(map(str, inputs))})"
            print(test_case, result)
            # print_test_result(test_case, result, result_color)

    return failed_testcases, errored_count
# 检测结果


def default_validator(
    method: Callable[..., Any],
    inputs: Tuple[Any, ...],
    expected: Tuple[Any, ...],
) -> None:
    """Default validator for leetcode tests"""
    output = method(*inputs)
    assert output == expected, (output, expected)


module = __import__('temperature')
solution_class = getattr(module, 'Solution')
method_names = [name for name in dir(
    solution_class) if not name.startswith('_')]
(method_name,) = method_names
method = getattr(solution_class(), method_name)
tests = getattr(module, 'tests')
validator = default_validator
failed_testcases, errored_count = run_testcases(method, tests, validator)

相关参考资料:

https://github.com/hjue/python_leetcode_runner

https://dev.to/tusharsadhwani/ace-your-leetcode-preparations-40l

https://leetcode-cn.com/problems/linked-list-cycle/

import json
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def stringToIntegerList(input):
return json.loads(input)
def stringToListNode(input):
# Generate list from the input
numbers = stringToIntegerList(input)
# Now convert that list into linked list
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
return ptr
def integerListToString(nums, len_of_list=None):
if not len_of_list:
len_of_list = len(nums)
return json.dumps(nums[:len_of_list])
def listNodeToString(node):
if not node:
return "[]"
result = ""
while node:
result += str(node.val) + ", "
node = node.next
return "[" + result[:-2] + "]"
def stringToBool(input):
return json.dumps(input)
def treeNodeToString(root):
if not root:
return "[]"
output = ""
queue = [root]
current = 0
while current != len(queue):
node = queue[current]
current = current + 1
if not node:
output += "null, "
continue
output += str(node.val) + ", "
queue.append(node.left)
queue.append(node.right)
return "[" + output[:-2] + "]"
def stringToTreeNode(input):
input = input.strip()
input = input[1:-1]
if not input:
return None
inputValues = [s.strip() for s in input.split(',')]
root = TreeNode(int(inputValues[0]))
nodeQueue = [root]
front = 0
index = 1
while index < len(inputValues):
node = nodeQueue[front]
front = front + 1
item = inputValues[index]
index = index + 1
if item != "null":
leftNumber = int(item)
node.left = TreeNode(leftNumber)
nodeQueue.append(node.left)
if index >= len(inputValues):
break
item = inputValues[index]
index = index + 1
if item != "null":
rightNumber = int(item)
node.right = TreeNode(rightNumber)
nodeQueue.append(node.right)
return root
def stringToString(input):
return input[1:-1].decode('string_escape')
def prettyPrintTree(node, prefix="", isLeft=True):
if not node:
print("Empty Tree")
return
if node.right:
prettyPrintTree(node.right, prefix +
("│ " if isLeft else " "), False)
print(prefix + ("└── " if isLeft else "┌── ") + str(node.val))
if node.left:
prettyPrintTree(node.left, prefix +
(" " if isLeft else "│ "), True)
def prettyPrintLinkedList(node):
while node and node.next:
print(str(node.val) + "->", end='')
node = node.next
if node:
print(node.val)
else:
print("Empty LinkedList")
[4, 5, 1, 9]
import json
from typing import Any, Callable, List, Optional, Tuple
from convert import *
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
return min(len(set(candyType)), len(candyType)//2)
def stringToIntegerList(input):
return json.loads(input)
def main():
import sys
import io
def readlines():
for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
yield line.strip('\n')
lines = readlines()
while True:
try:
line = next(lines)
candyType = stringToIntegerList(line)
ret = Solution().distributeCandies(candyType)
out = str(ret)
print(out)
except StopIteration:
break
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment