Skip to content

Commit

Permalink
Merge pull request #141 from weilycoder/dev2
Browse files Browse the repository at this point in the history
Fixed errors in Vector.random when generating floating-point vectors or vectors with repeated elements.
  • Loading branch information
Mr-Python-in-China authored Oct 5, 2024
2 parents 2727298 + ef32276 commit 3b8fba8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
1 change: 1 addition & 0 deletions cyaron/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
from .polygon_test import TestPolygon
from .compare_test import TestCompare
from .graph_test import TestGraph
from .vector_test import TestVector
33 changes: 33 additions & 0 deletions cyaron/tests/vector_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import unittest
from cyaron.vector import *


def has_duplicates(lst: list):
return len(lst) != len(set(lst))


class TestVector(unittest.TestCase):
def test_unique_vector(self):
v = Vector.random(10**5, [10**6])
self.assertFalse(has_duplicates(list(map(lambda tp: tuple(tp), v))))
self.assertTrue(all(map(lambda v: 0 <= v[0] <= 10**6, v)))
v = Vector.random(1000, [(10**5, 10**6)])
self.assertTrue(all(map(lambda v: 10**5 <= v[0] <= 10**6, v)))
with self.assertRaises(
Exception,
msg="1st param is so large that CYaRon can not generate unique vectors",
):
v = Vector.random(10**5, [10**4])

def test_repeatable_vector(self):
v = Vector.random(10**5 + 1, [10**5], VectorRandomMode.repeatable)
self.assertTrue(all(map(lambda v: 0 <= v[0] <= 10**5, v)))
self.assertTrue(has_duplicates(list(map(lambda tp: tuple(tp), v))))
v = Vector.random(1000, [(10**5, 10**6)], VectorRandomMode.repeatable)
self.assertTrue(all(map(lambda v: 10**5 <= v[0] <= 10**6, v)))

def test_float_vector(self):
v = Vector.random(10**5, [10**5], VectorRandomMode.float)
self.assertTrue(all(map(lambda v: 0 <= v[0] <= 10**5, v)))
v = Vector.random(10**5, [(24, 25)], VectorRandomMode.float)
self.assertTrue(all(map(lambda v: 24 <= v[0] <= 25, v)))
4 changes: 2 additions & 2 deletions cyaron/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ def random(num: int = 5, position_range: list = None, mode: VectorRandomMode = 0

result = []
if mode == VectorRandomMode.repeatable:
result = [[random.randint(x, y) for x, y in zip(offset, length)] for _ in range(num)]
result = [[random.randint(x, x + y) for x, y in zip(offset, length)] for _ in range(num)]
elif mode == VectorRandomMode.float:
result = [[random.uniform(x, y) for x, y in zip(offset, length)] for _ in range(num)]
result = [[random.uniform(x, x + y) for x, y in zip(offset, length)] for _ in range(num)]
elif mode == VectorRandomMode.unique and vector_space > 5 * num:
# O(NlogN)
num_set = set()
Expand Down

0 comments on commit 3b8fba8

Please sign in to comment.