### Run Simple Pyleet Example (Bash) Source: https://github.com/ergs0204/pyleet/blob/main/examples/programmatic_usage/README.md Command to execute the basic Pyleet programmatic usage example script, demonstrating minimal setup and execution. ```bash python simple_example.py ``` -------------------------------- ### Install Pyleet using pip Source: https://github.com/ergs0204/pyleet/blob/main/README.md This command installs the Pyleet library from PyPI using pip, the Python package installer. It's the simplest and recommended way to get Pyleet set up on your system for general use. ```bash pip install pyleet ``` -------------------------------- ### Run Advanced Pyleet Example (Bash) Source: https://github.com/ergs0204/pyleet/blob/main/examples/programmatic_usage/README.md Command to execute the comprehensive Pyleet programmatic usage example script, showcasing advanced features like multiple solution methods, various test case formats, and error handling. ```bash python programmatic_example.py ``` -------------------------------- ### Example: Implementing and Registering a Custom `Point` Class Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Illustrates the complete process of defining a custom `Point` class with `__eq__` and `__repr__` methods, implementing its serialization (`point_to_list`) and deserialization (`list_to_point`) functions, and registering them with pyleet for automated testing of custom data structures. ```python from pyleet import register_deserializer, register_serializer class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __eq__(self, other): if not isinstance(other, Point): return False return self.x == other.x and self.y == other.y def __repr__(self): return f"Point({self.x}, {self.y})" def list_to_point(data): if not data or len(data) != 2: return None return Point(data[0], data[1]) def point_to_list(point): if not point: return None return [point.x, point.y] register_deserializer("Point", list_to_point) register_serializer("Point", point_to_list) class Solution: def processPoint(self, point): """Calculate distance from origin and return as new point""" if not point: return None distance = (point.x ** 2 + point.y ** 2) ** 0.5 return Point(int(distance), 0) ``` -------------------------------- ### Example: Using Built-in pyleet Classes (ListNode/TreeNode) Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Demonstrates how to use pyleet's built-in `ListNode` and `TreeNode` classes for common LeetCode-style problems. Includes implementations for reversing a linked list and inverting a binary tree, showcasing direct usage without custom serialization setup. ```python # No imports needed for basic usage! # Or use explicit import for clarity: from pyleet import ListNode, TreeNode class Solution: def reverseList(self, head): """Reverse a linked list using built-in ListNode""" prev = None current = head while current: next_temp = current.next current.next = prev prev = current current = next_temp return prev def invertTree(self, root): """Invert a binary tree using built-in TreeNode""" if not root: return None root.left, root.right = root.right, root.left self.invertTree(root.left) self.invertTree(root.right) return root ``` -------------------------------- ### Install Pyleet from source Source: https://github.com/ergs0204/pyleet/blob/main/README.md These commands clone the Pyleet repository from GitHub, navigate into the project directory, and install the package in editable mode. This method is useful for development, contributing to the project, or if you need the latest unreleased features directly from the source code. ```bash git clone https://github.com/ergs0204/pyleet.git cd pyleet pip install -e . ``` -------------------------------- ### Implement Custom Class Serialization/Deserialization with Edge Cases Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Provides example implementations for `list_to_custom_class` (deserializer) and `custom_class_to_list` (serializer) functions. These examples emphasize the importance of handling `None` inputs and validating data formats for robust and error-tolerant data conversion. ```python def list_to_custom_class(data): # Handle None/empty input if not data: return None # Validate input format if not isinstance(data, list) or len(data) != expected_length: raise ValueError(f"Expected list of length {expected_length}, got {data}") # Create and return instance return CustomClass(data[0], data[1]) def custom_class_to_list(obj): # Handle None input if not obj: return None # Convert back to list format return [obj.attr1, obj.attr2] ``` -------------------------------- ### Pyleet Programmatic Workflow (Python) Source: https://github.com/ergs0204/pyleet/blob/main/examples/programmatic_usage/README.md Outlines the essential steps for integrating Pyleet into a Python script or notebook, from importing the library to running tests and displaying their outcomes. ```python import pyleet ``` ```python # Define your solution class with methods ``` ```python # Create test cases in any supported format ``` ```python results = pyleet.run(testcases) ``` ```python pyleet.print_results(results) ``` -------------------------------- ### Run pyleet with Custom Test Cases Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Command-line instruction for executing a pyleet solution file with a specified JSON test case file. This demonstrates how to integrate custom classes and their associated test cases into the pyleet testing workflow. ```bash pyleet your_solution.py --testcases point_testcases.json ``` -------------------------------- ### Pyleet Method Selection (Python) Source: https://github.com/ergs0204/pyleet/blob/main/examples/programmatic_usage/README.md Demonstrates how to invoke Pyleet tests with either automatic method detection or explicit selection of a specific solution method using the `pyleet.run()` function. ```python pyleet.run(testcases) ``` ```python pyleet.run(testcases, method="twoSum") ``` -------------------------------- ### Pyleet Example: Custom Class Deserialization from JSON Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md A concrete example demonstrating how Pyleet deserializes single-key dictionaries with registered deserializer keys (like 'ListNode') into custom class instances from a JSON test case. ```JSON { "input": [{"ListNode": [1, 2, 3]}], "expected": {"ListNode": [3, 2, 1]} } ``` -------------------------------- ### Example Test Cases for Custom Point Class (JSON) Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Illustrates how to define test cases in JSON format for a custom `Point` class. It specifies input and expected output using the `{"ClassName": data}` format, enabling Pyleet to run tests with custom data structures. ```json [ { "description": "Point distance calculation", "input": [{"Point": [3, 4]}], "expected": {"Point": [5, 0]} }, { "description": "Point at origin", "input": [{"Point": [0, 0]}], "expected": {"Point": [0, 0]} } ] ``` -------------------------------- ### Pyleet Result Processing (Python) Source: https://github.com/ergs0204/pyleet/blob/main/examples/programmatic_usage/README.md Shows how to display the results of Pyleet tests using `pyleet.print_results()`, with options for detailed verbose output or a more concise summary. ```python pyleet.print_results(results) ``` ```python pyleet.print_results(results, verbose=False) ``` -------------------------------- ### Pyleet Example: List with Mixed Dictionary Types Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md A concrete example showing how Pyleet processes a list containing a mix of dictionaries, some deserialized into custom classes and others remaining as regular dictionaries based on the rules. ```JSON { "input": [ [ {"ListNode": [1, 2, 3]}, {"key": "value"}, {"TreeNode": [5]} ] ], "expected": {"processed": "mixed_types"} } ``` -------------------------------- ### Pyleet Test Case Formats (Python) Source: https://github.com/ergs0204/pyleet/blob/main/examples/programmatic_usage/README.md Illustrates the different data structures supported by Pyleet for defining test cases, including tuple, dictionary, and list formats, allowing flexibility in test definition. ```python (([2, 7, 11, 15], 9), [0, 1]) ``` ```python {"input": [[2, 7, 11, 15], 9], "expected": [0, 1]} ``` ```python [[[2, 7, 11, 15], 9], [0, 1]] ``` -------------------------------- ### Pyleet Example: Regular Dictionary with Unregistered Key Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md A concrete example showing how Pyleet treats a single-key dictionary as a regular dictionary when its key does not correspond to any registered deserializer. ```JSON { "input": [{"CustomClass": [1, 2, 3]}], "expected": {"result": "processed"} } ``` -------------------------------- ### JSON Test Cases for Custom `Point` Class Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Example JSON structure for defining test cases for problems involving a custom `Point` class. It demonstrates how to specify input and expected output using the custom type name ('Point') after its serializers and deserializers have been registered. ```json [ { "description": "Point distance calculation", "input": [{"Point": [3, 4]}], "expected": {"Point": [5, 0]} }, { "description": "Point at origin", "input": [{"Point": [0, 0]}], "expected": {"Point": [0, 0]} } ] ``` -------------------------------- ### Pyleet Example: Multi-Key Dictionary Processing Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md A concrete example illustrating that Pyleet always treats dictionaries with multiple keys as regular dictionaries, regardless of their content. ```JSON { "input": [{"key": "value", "count": 5}], "expected": {"processed": true} } ``` -------------------------------- ### Python Example: Robust ListNode Deserializer Function Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Provides a Python example of a robust `list_to_listnode` deserializer function. It demonstrates how to handle `None` and empty inputs gracefully, validate input types, and raise appropriate errors for invalid data, ensuring the function's reliability. ```python def list_to_listnode(data): """ Convert list data to ListNode linked list. Args: data: Expected to be a list of values, but handles edge cases Returns: ListNode: Head of linked list, or None if data is empty/invalid """ # Handle None and empty cases if not data: return None # Handle non-list input if not isinstance(data, list): raise ValueError(f"Expected list, got {type(data).__name__}: {data}") # Create linked list dummy = ListNode(0) current = dummy for val in data: current.next = ListNode(val) current = current.next return dummy.next ``` -------------------------------- ### Pyleet Example: Mixed Nested Structure Deserialization Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md A concrete example demonstrating Pyleet's recursive processing, where custom classes are deserialized within a nested structure while other multi-key or unregistered dictionaries remain regular. ```JSON { "input": [ { "nodes": [{"ListNode": [1, 2]}, {"ListNode": [3, 4]}], "metadata": {"count": 2, "type": "linked_list"} } ], "expected": {"ListNode": [1, 2, 3, 4]} } ``` -------------------------------- ### JSON Test Cases for Built-in pyleet Classes Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Example JSON structure for defining test cases for problems involving pyleet's built-in `ListNode` and `TreeNode` classes. It illustrates how to specify input and expected output using the framework's recognized formats for these data structures. ```json [ { "description": "Reverse linked list", "input": [{"ListNode": [1, 2, 3, 4, 5]}], "expected": {"ListNode": [5, 4, 3, 2, 1]} }, { "description": "Invert binary tree", "input": [{"TreeNode": [4, 2, 7, 1, 3, 6, 9]}], "expected": {"TreeNode": [4, 7, 2, 9, 6, 3, 1]} } ] ``` -------------------------------- ### Automatically retrieve LeetCode test cases with pyleet Source: https://github.com/ergs0204/pyleet/blob/main/docs/programmatic_usage.md Shows how to use `pyleet.get_testcase()` to automatically fetch test cases for a given LeetCode problem ID or title slug, simplifying test setup and ensuring up-to-date test data. ```python import pyleet class Solution: def twoSum(self, nums, target): num_map = {} for i, num in enumerate(nums): complement = target - num if complement in num_map: return [num_map[complement], i] num_map[num] = i return [] # Automatically get test cases from LeetCode testcases = pyleet.get_testcase(problem_id=1) # Two Sum results = pyleet.run(testcases) pyleet.print_results(results) # Or use title slug testcases = pyleet.get_testcase(title_slug="two-sum") results = pyleet.run(testcases) ``` -------------------------------- ### Importing Built-in Pyleet Data Structures Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Examples demonstrating how to explicitly import the standard built-in data structures, `ListNode` and `TreeNode`, from the `pyleet` library. These are commonly used for solving linked list and tree-related algorithm problems, providing a consistent base for test cases. ```Python from pyleet import ListNode ``` ```Python from pyleet import TreeNode ``` -------------------------------- ### Pyleet Deserialization: Best Practices for Deserializer Authors Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Offers recommendations for developers writing deserializer functions. These practices focus on robustness, error handling, and clear documentation to create reliable and maintainable deserializers. ```APIDOC DeserializerAuthorsBestPractices: - Handle Invalid Input: Always validate input data in deserializer functions - Return Appropriate Defaults: Handle None and empty inputs gracefully - Document Expected Format: Clearly document what data format your deserializer expects - Use Descriptive Names: Choose clear, unambiguous names for custom classes ``` -------------------------------- ### Implement `__eq__` for Custom Class Comparison Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Demonstrates how to implement the `__eq__` method in Python classes to enable proper equality comparison between objects, crucial for automated testing and data validation within frameworks like pyleet. ```python def __eq__(self, other): if not isinstance(other, self.__class__): return False # Compare relevant attributes return self.attr1 == other.attr1 and self.attr2 == other.attr2 ``` -------------------------------- ### Programmatic Pyleet usage example Source: https://github.com/ergs0204/pyleet/blob/main/README.md This Python snippet illustrates how to use Pyleet programmatically within your Python scripts. It shows how to import the library, define a placeholder `Solution` class, fetch test cases for a specific problem ID, run the solution against these test cases, and then print the results. This approach allows for tighter integration with Python development workflows and IDEs, enabling advanced debugging and automation. ```python import pyleet class Solution: def twoSum(self, nums, target): pass testcases=pyleet.get_testcase(problem_id=1) results = pyleet.run(testcases, method="twoSum") pyleet.print_results(results) ``` -------------------------------- ### Register Custom Class Deserializer and Serializer (Python) Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Demonstrates how to register the custom `list_to_point` deserializer and `point_to_list` serializer with Pyleet. Using `register_deserializer` and `register_serializer` makes the `Point` class fully usable within Pyleet's test framework. ```python from pyleet import register_deserializer, register_serializer register_deserializer("Point", list_to_point) register_serializer("Point", point_to_list) ``` -------------------------------- ### Implement `__repr__` for Debugging and Representation Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Shows how to implement the `__repr__` method in Python classes to provide a clear, unambiguous string representation of an object, which is highly useful for debugging, logging, and interactive console inspection. ```python def __repr__(self): return f"ClassName(attr1={self.attr1}, attr2={self.attr2})" ``` -------------------------------- ### Pyleet Deserialization: Best Practices for Test Case Authors Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Provides guidelines for authors creating test cases involving custom class deserialization. Following these practices helps ensure accurate testing and avoids common pitfalls related to data formatting and validation. ```APIDOC TestCasesBestPractices: - Use Single-Key Format: Always use `{"ClassName": data}` for custom classes - Avoid Multi-Key Custom Classes: Don't mix custom class keys with other keys - Validate Data Types: Ensure data passed to deserializers is in expected format - Test Edge Cases: Verify behavior with None, empty, and invalid data ``` -------------------------------- ### Retrieve LeetCode Test Cases with pyleet.get_testcase() Source: https://github.com/ergs0204/pyleet/blob/main/docs/test_case_retrieval.md This snippet demonstrates how to use the `pyleet.get_testcase()` function to fetch test cases from LeetCode. It shows examples of retrieving test cases by problem ID and title slug, and how the retrieved test cases can be seamlessly integrated with `pyleet.run()` for execution. ```python # Get test cases by problem ID testcases = pyleet.get_testcase(problem_id=1) # Get test cases by title slug testcases = pyleet.get_testcase(title_slug="two-sum") # Use with pyleet.run() results = pyleet.run(testcases) ``` -------------------------------- ### Define a Custom Point Class (Python) Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Defines a simple `Point` class with `x` and `y` coordinates, demonstrating how to create custom data structures for Pyleet. It includes `__eq__` for proper comparison in tests and `__repr__` for helpful debugging output. ```python class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def __eq__(self, other): # Important for test comparisons if not isinstance(other, Point): return False return self.x == other.x and self.y == other.y def __repr__(self): # Helpful for debugging return f"Point({self.x}, {self.y})" ``` -------------------------------- ### Implement Solution Method for Custom Point Class (Python) Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Shows how to define a solution method (`processPoint`) within a `Solution` class that operates on the custom `Point` object. Pyleet automatically selects the appropriate method based on input types, simplifying processing of custom data structures. ```python class Solution: def processPoint(self, point): """Process a Point object""" if not point: return None # Example: calculate distance from origin distance = (point.x ** 2 + point.y ** 2) ** 0.5 return Point(int(distance), 0) ``` -------------------------------- ### Register Custom Class Serializers and Deserializers Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Illustrates how to register both deserializer and serializer functions with the pyleet framework for a custom class. This enables seamless bidirectional conversion between raw data (e.g., lists) and custom object instances, essential for automated test case processing. ```python # Register deserializer for input conversion register_deserializer("CustomClass", list_to_custom_class) # Register serializer for output conversion register_serializer("CustomClass", custom_class_to_list) ``` -------------------------------- ### Pyleet Custom Deserialization: Single-Key Registered Dictionary Rule Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Demonstrates how a single-key dictionary in JSON, where the key matches a registered deserializer (e.g., 'ListNode'), is converted into a custom class instance by Pyleet's serialization system. ```Python # Input JSON {"ListNode": [1, 2, 3]} # Output ListNode([1, 2, 3]) # Custom class instance ``` -------------------------------- ### Pyleet Dictionary Processing: Empty Dictionary Rule Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Demonstrates that an empty dictionary in JSON is always treated as a regular Python dictionary by Pyleet's serialization system, without any special deserialization. ```Python # Input JSON {} # Output {} # Regular Python dict ``` -------------------------------- ### Pyleet Custom Class Deserialization: Important Limitations Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Outlines the inherent limitations of the Pyleet custom class deserialization mechanism. These constraints are crucial for developers to understand to avoid unexpected behavior and ensure robust data handling. ```APIDOC CustomClassDeserializationLimitations: - No Type Validation: Deserializers receive raw data without validation - Multi-Key Exclusion: Dictionaries with multiple keys are never custom classes - Non-String Key Exclusion: Only string keys can trigger deserialization - Case Sensitivity: Deserializer names are case-sensitive (`"listnode"` ≠ `"ListNode"`) - No Error Recovery: Invalid data passed to deserializers may cause unexpected behavior ``` -------------------------------- ### Pyleet Custom Class Deserialization: Processing Behavior Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Describes how the Pyleet deserialization engine processes nested data structures. It emphasizes the recursive, depth-first application of rules and the allowance for mixed types within regular dictionaries. ```APIDOC CustomClassDeserializationProcessing: - Recursive Processing: All nested structures are processed using the same rules - Depth-First: Processing occurs from innermost to outermost structures - Immutable Rules: The same rules apply at every nesting level - Mixed Types Allowed: Regular dictionaries can contain custom classes as values ``` -------------------------------- ### Override Built-in ListNode Class (Python) Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Illustrates how to define a custom `ListNode` class to override Pyleet's built-in version. This advanced pattern allows for custom attributes and behaviors, such as `custom_attr`, providing flexibility for specific problem requirements. ```python # Define your own to override built-in classes class ListNode: def __init__(self, val=0, next=None, custom_attr=None): self.val = val self.next = next self.custom_attr = custom_attr # Your custom addition class Solution: def customProcessor(self, head): """Uses your custom ListNode implementation""" # ... implementation ``` -------------------------------- ### Pyleet Deserialization Output: String Input Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md This snippet shows the output when a string is provided to a `ListNode` deserializer instead of an expected list. It highlights that the deserializer iterates over string characters, which can lead to unexpected behavior if not handled gracefully. ```python ListNode(['s', 't', 'r', 'i', 'n', 'g', '_', 'i', 'n', 's', 't', 'e', 'a', 'd', '_', 'o', 'f', '_', 'l', 'i', 's', 't']) ``` -------------------------------- ### Pyleet Dictionary Processing: Single-Key Unregistered Dictionary Rule Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Illustrates that a single-key dictionary in JSON, if its key does not correspond to any registered deserializer, will be treated as a regular Python dictionary by Pyleet's serialization system. ```Python # Input JSON {"CustomClass": [1, 2, 3]} # Output {"CustomClass": [1, 2, 3]} # Regular Python dict ``` -------------------------------- ### Implement Solution with Automatic ListNode Fallback (Python) Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Demonstrates using Pyleet's built-in `ListNode` class without explicit import, relying on automatic availability. This pattern simplifies code for common LeetCode problems like reversing a linked list, where Pyleet handles the class provision. ```python # No imports needed - Pyleet automatically provides the classes class Solution: def reverseList(self, head): """ListNode is automatically available""" prev = None current = head while current: next_temp = current.next current.next = prev prev = current current = next_temp return prev ``` -------------------------------- ### Pyleet Custom Class Deserialization: Critical Requirements Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Defines the strict criteria a dictionary must meet to be recognized and deserialized as a custom class within the Pyleet framework. These rules ensure predictable behavior for the deserialization process. ```APIDOC CustomClassDeserialization: - Exactly One Key: The dictionary must have exactly one key-value pair - String Key: The key must be a string (not numeric, boolean, or other types) - Registered Deserializer: The key must exactly match a registered deserializer name (case-sensitive) - Valid Deserializer Function: The registered deserializer must be callable ``` -------------------------------- ### Implement Solution with Explicit ListNode Import (Python) Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Shows the recommended way to use Pyleet's built-in `ListNode` by explicitly importing it from `pyleet`. This approach enhances code clarity and maintainability, making dependencies explicit for operations like merging two sorted lists. ```python from pyleet import ListNode class Solution: def mergeTwoLists(self, list1, list2): """Explicit import for better code clarity""" dummy = ListNode(0) # ... implementation return dummy.next ``` -------------------------------- ### Pyleet Deserialization Edge Case: None and Empty Inputs Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Illustrates how `None` and empty list inputs for `ListNode` are handled during deserialization. Both `null` in JSON and an empty list `[]` result in `None` in Python, indicating graceful handling by the deserializer. ```python # Input JSON {"ListNode": null} # null in JSON becomes None in Python {"ListNode": []} # Empty list # Output None # Both cases return None (handled by deserializer) None ``` -------------------------------- ### Define Deserializer and Serializer for Custom Point Class (Python) Source: https://github.com/ergs0204/pyleet/blob/main/docs/custom_classes_guide.md Provides Python functions (`list_to_point` and `point_to_list`) to convert between a list representation and the custom `Point` object. These functions are crucial for enabling bidirectional serialization, allowing Pyleet to handle custom class inputs and outputs. ```python def list_to_point(data): """ Convert list to Point (for input deserialization). Format: [x, y] Example: [3, 4] -> Point(3, 4) """ if not data or len(data) != 2: return None return Point(data[0], data[1]) def point_to_list(point): """ Convert Point to list (for output serialization). Format: Point -> [x, y] Example: Point(3, 4) -> [3, 4] """ if not point: return None return [point.x, point.y] ``` -------------------------------- ### Pyleet Dictionary Processing: Multi-Key Dictionary Rule Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Shows that any dictionary in JSON containing multiple keys will always be treated as a regular Python dictionary, regardless of whether any of its keys might otherwise match a registered deserializer. ```Python # Input JSON {"key": "value", "count": 5, "active": True} # Output {"key": "value", "count": 5, "active": True} # Regular Python dict ``` -------------------------------- ### Pyleet Edge Case: Non-String Dictionary Keys Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Illustrates that Pyleet's custom class deserialization only applies to dictionaries with string keys; dictionaries with numeric or boolean keys are always treated as regular Python dictionaries. ```Python # Input JSON {1: [1, 2, 3]} # Numeric key {true: [1, 2, 3]} # Boolean key # Output {1: [1, 2, 3]} # Regular dict (numeric key ignored) {True: [1, 2, 3]} # Regular dict (boolean key ignored) ``` -------------------------------- ### Pyleet Deserialization Edge Case: Deep Nesting Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Explains that custom class detection and deserialization occur at every nesting level. Only the innermost dictionary matching the `ListNode` pattern is deserialized, while outer structures remain as regular dictionaries. ```python # Input JSON { "level1": { "level2": { "level3": {"ListNode": [1, 2, 3]} } } } # Output { "level1": { "level2": { "level3": ListNode([1, 2, 3]) # Only this gets deserialized } } } ``` -------------------------------- ### Pyleet Edge Case: Invalid Data Types for Deserializers Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Highlights a limitation where Pyleet's deserializers receive the provided data without type validation, meaning a deserializer expecting a list might receive a string if the JSON input is malformed. ```JSON {"ListNode": "string_instead_of_list"} ``` -------------------------------- ### Pyleet Dictionary Processing: Recursive Structure Handling Rule Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Explains how Pyleet's serialization system recursively applies its dictionary processing rules to nested structures, allowing custom classes to be deserialized within complex JSON objects while other parts remain regular dictionaries. ```Python # Input JSON { "nodes": [{"ListNode": [1, 2]}, {"ListNode": [3, 4]}], "metadata": {"count": 2, "type": "linked_list"} } # Output { "nodes": [ListNode([1, 2]), ListNode([3, 4])], # Custom classes "metadata": {"count": 2, "type": "linked_list"} # Regular dict } ``` -------------------------------- ### Pyleet Deserialization Edge Case: Multi-Key Dictionary Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Highlights that dictionaries with multiple keys are never treated as custom classes, even if one key matches a registered deserializer. The `ListNode` key is ignored in such cases, and the entire structure remains a regular dictionary. ```python # Input JSON {"ListNode": [1, 2, 3], "metadata": "info"} # Output {"ListNode": [1, 2, 3], "metadata": "info"} # Regular dict (multiple keys) # The ListNode key is ignored because there are multiple keys ``` -------------------------------- ### Pyleet Deserialization Edge Case: Complex Nested Data Source: https://github.com/ergs0204/pyleet/blob/main/docs/dictionary_handling_guide.md Demonstrates that deserializers receive recursively processed data, preserving complex nested structures like dictionaries and lists within the `ListNode`'s data. The nested elements are passed as-is to the `ListNode` constructor. ```python # Input JSON {"ListNode": [{"nested": "dict"}, [1, 2], "mixed"]} # Output ListNode([{"nested": "dict"}, [1, 2], "mixed"]) # The nested dict and list are preserved as-is ``` -------------------------------- ### Basic pyleet CLI Execution Source: https://github.com/ergs0204/pyleet/blob/main/docs/cli_usage.md Illustrates the fundamental command for running a LeetCode solution (`solution.py`) with a test case file (`cases.txt`) using `pyleet`. Both the full `--testcases` flag and its shorthand `-t` are demonstrated for basic execution. ```bash pyleet solution.py --testcases cases.txt # or using the shorthand pyleet solution.py -t cases.txt ``` -------------------------------- ### Run LeetCode Solution with Pyleet CLI Source: https://github.com/ergs0204/pyleet/blob/main/memory-bank/projectbrief.md This command demonstrates how to execute a LeetCode Python solution file (`solution.py`) using the Pyleet command-line interface, providing external test cases from `cases.txt`. This allows for local testing of LeetCode problems without modifying the original LeetCode code. ```Shell pyleet solution.py --testcases cases.txt ``` -------------------------------- ### Run LeetCode solution with Pyleet CLI Source: https://github.com/ergs0204/pyleet/blob/main/README.md This command demonstrates the basic usage of the Pyleet command-line interface to run a LeetCode solution file against a specified test case file. It's ideal for quick tests and integration into CI/CD pipelines. Replace `your_solution_file.py` with your Python solution and `test_cases.txt` with your test cases. ```bash pyleet your_solution_file.py --testcases test_cases.txt ``` ```bash pyleet solution.py -t cases.txt ``` -------------------------------- ### Pyleet CLI: Testing Specific Methods from a Multi-Method Class Source: https://github.com/ergs0204/pyleet/blob/main/docs/method_selection.md Shows how to use the Pyleet command-line tool to test individual methods from a Python solution file that contains multiple problem implementations. It demonstrates specifying the method name and corresponding test cases for `twoSum` and `threeSum` separately. ```bash # Test the twoSum method specifically pyleet solution.py --testcases two_sum_cases.json --method twoSum # Test the threeSum method specifically pyleet solution.py --testcases three_sum_cases.json --method threeSum ``` -------------------------------- ### Running Pyleet with External Test Cases Source: https://github.com/ergs0204/pyleet/blob/main/memory-bank/productContext.md This command demonstrates how to execute a LeetCode solution locally using the Pyleet tool. It specifies the Python solution file and an external text file containing the test cases. Pyleet will then parse the solution, load the test cases, execute the function, and report the results. ```Shell pyleet solution.py --testcases cases.txt ``` -------------------------------- ### Define pyleet test cases using tuple format Source: https://github.com/ergs0204/pyleet/blob/main/docs/programmatic_usage.md Illustrates the recommended tuple format for defining simple test cases, where each entry is a tuple containing input arguments and the expected output. ```python testcases = [ (([2, 7, 11, 15], 9), [0, 1]), # ((input_args), expected_output) (([3, 2, 4], 6), [1, 2]) ] ``` -------------------------------- ### Define pyleet test cases using dictionary format Source: https://github.com/ergs0204/pyleet/blob/main/docs/programmatic_usage.md Shows how to define more complex test cases using a dictionary format, specifying 'input' and 'expected' keys for clarity. ```python testcases = [ { "input": [[2, 7, 11, 15], 9], "expected": [0, 1] }, { "input": [[3, 2, 4], 6], "expected": [1, 2] } ] ``` -------------------------------- ### Run pyleet tests programmatically with a custom solution Source: https://github.com/ergs0204/pyleet/blob/main/docs/programmatic_usage.md Demonstrates how to integrate `pyleet` into Python code to define a solution class, set up test cases, and execute tests using `pyleet.run()` and `pyleet.print_results()`. ```python import pyleet class Solution: def twoSum(self, nums, target): """Find two numbers that add up to target.""" num_map = {} for i, num in enumerate(nums): complement = target - num if complement in num_map: return [num_map[complement], i] num_map[num] = i return [] # Define test cases directly in your code testcases = [ (([2, 7, 11, 15], 9), [0, 1]), (([3, 2, 4], 6), [1, 2]), (([3, 3], 6), [0, 1]) ] # Run the tests results = pyleet.run(testcases) pyleet.print_results(results) ``` -------------------------------- ### Python: Solution Class with Multiple LeetCode Methods Source: https://github.com/ergs0204/pyleet/blob/main/docs/method_selection.md Illustrates a Python `Solution` class containing multiple distinct LeetCode problem implementations, such as `twoSum` and `threeSum`, within a single file. This structure necessitates explicit method selection when testing specific problems. ```python class Solution: def twoSum(self, nums, target): # Implementation here pass def threeSum(self, nums): # Implementation here pass ``` -------------------------------- ### pyleet CLI Method Selection Source: https://github.com/ergs0204/pyleet/blob/main/docs/cli_usage.md Explains how to specify which method within a Python solution class `pyleet` should execute. It shows the default automatic method detection and explicit selection using the `--method` or `-m` flag, useful for solutions with multiple functions. ```bash # Automatic method selection (default behavior) pyleet solution.py --testcases cases.txt # Explicit method selection pyleet solution.py --testcases cases.txt --method twoSum pyleet solution.py --testcases cases.txt -m threeSum ``` -------------------------------- ### Pyleet CLI: Explicit Method Selection Source: https://github.com/ergs0204/pyleet/blob/main/docs/method_selection.md Demonstrates the command-line interface usage to explicitly specify a method for Pyleet to execute. This is crucial when automatic method selection is not desired or sufficient, allowing precise control over which function is tested. ```bash pyleet solution.py --testcases cases.txt --method methodName ``` -------------------------------- ### pyleet Text Test Case Format Source: https://github.com/ergs0204/pyleet/blob/main/docs/cli_usage.md Defines the plain text format for `pyleet` test case files. Each line represents a single test case, structured with input arguments enclosed in parentheses followed by the expected output, separated by a comma. ```text (([2, 7, 11, 15], 9), [0, 1]) (([3, 2, 4], 6), [1, 2]) (([3, 3], 6), [0, 1]) ``` -------------------------------- ### pyleet Basic JSON Test Case Format Source: https://github.com/ergs0204/pyleet/blob/main/docs/cli_usage.md Presents the recommended JSON structure for `pyleet` test cases. Each test case is an object containing `input` and `expected` fields, allowing for structured data and multiple arguments per input. ```json [ { "input": [[2, 7, 11, 15], 9], "expected": [0, 1] }, { "input": [[3, 2, 4], 6], "expected": [1, 2] }, { "input": [[3, 3], 6], "expected": [0, 1] } ] ``` -------------------------------- ### Pyleet CLI: Error for Non-Existent Method Source: https://github.com/ergs0204/pyleet/blob/main/docs/method_selection.md Demonstrates the error message displayed by Pyleet when an attempt is made to execute a method that does not exist within the specified solution file. The error message provides helpful feedback by listing the available methods. ```bash $ pyleet solution.py --testcases cases.txt --method nonExistentMethod Error: Method 'nonExistentMethod' not found. Available methods: ['twoSum', 'threeSum', 'maxSubArray'] ``` -------------------------------- ### Select specific methods for pyleet testing Source: https://github.com/ergs0204/pyleet/blob/main/docs/programmatic_usage.md Explains how to explicitly specify which method of a class `pyleet` should test, overriding the automatic selection. ```python # Automatic method selection (default) results = pyleet.run(testcases) # Explicit method selection results = pyleet.run(testcases, method="twoSum") ```