improve find_bounding_rect

This commit is contained in:
blueloveTH 2024-10-17 16:53:04 +08:00
parent 378def9360
commit 7deb596bfc
3 changed files with 7 additions and 4 deletions

View File

@ -61,7 +61,7 @@ class array2d(Generic[T]):
def count_neighbors(self, value: T, neighborhood: Neighborhood) -> 'array2d[int]': def count_neighbors(self, value: T, neighborhood: Neighborhood) -> 'array2d[int]':
"""Counts the number of neighbors with the given value for each cell.""" """Counts the number of neighbors with the given value for each cell."""
def find_bounding_rect(self, value: T) -> tuple[int, int, int, int] | None: def find_bounding_rect(self, value: T) -> tuple[int, int, int, int]:
"""Finds the bounding rectangle of the given value. """Finds the bounding rectangle of the given value.
Returns a tuple `(x, y, width, height)` or `None` if the value is not found. Returns a tuple `(x, y, width, height)` or `None` if the value is not found.

View File

@ -1,7 +1,6 @@
#include "pocketpy/pocketpy.h" #include "pocketpy/pocketpy.h"
#include "pocketpy/common/utils.h" #include "pocketpy/common/utils.h"
#include "pocketpy/objects/object.h"
#include "pocketpy/common/sstream.h" #include "pocketpy/common/sstream.h"
#include "pocketpy/interpreter/vm.h" #include "pocketpy/interpreter/vm.h"
@ -371,7 +370,7 @@ static bool array2d_find_bounding_rect(int argc, py_Ref argv) {
int width = right - left + 1; int width = right - left + 1;
int height = bottom - top + 1; int height = bottom - top + 1;
if(width <= 0 || height <= 0) { if(width <= 0 || height <= 0) {
py_newnone(py_retval()); return ValueError("value not found");
} else { } else {
py_newtuple(py_retval(), 4); py_newtuple(py_retval(), 4);
py_TValue* data = py_tuple_data(py_retval()); py_TValue* data = py_tuple_data(py_retval());

View File

@ -134,8 +134,12 @@ assert a.count(1) == 3*2
assert a.find_bounding_rect(1) == (1, 1, 3, 2) assert a.find_bounding_rect(1) == (1, 1, 3, 2)
assert a.find_bounding_rect(0) == (0, 0, 5, 5) assert a.find_bounding_rect(0) == (0, 0, 5, 5)
assert a.find_bounding_rect(2) == None
try:
a.find_bounding_rect(2)
exit(1)
except ValueError:
pass
a = array2d(3, 2, default='?') a = array2d(3, 2, default='?')
# int/float/str/bool/None # int/float/str/bool/None