Skip to content

Commit

Permalink
Format,write notes, and add type hints for vector.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Mr-Python-in-China committed Oct 5, 2024
1 parent 3b8fba8 commit ed5bacd
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 28 deletions.
2 changes: 1 addition & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[MASTER]
py-version=3.5
disable=R0902,R0913,R0917
disable=R0902,R0913,R0917,R0912
2 changes: 1 addition & 1 deletion cyaron/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@


class IO:
"""Class IO: IO tool class. It will process the input and output files."""
"""IO tool class. It will process the input and output files."""

@overload
def __init__(self,
Expand Down
12 changes: 9 additions & 3 deletions cyaron/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def list_like(data):
Judge whether the object data is like a list or a tuple.
object data -> the data to judge
"""
return isinstance(data, tuple) or isinstance(data, list)
return isinstance(data, (tuple, list))


def int_like(data):
Expand All @@ -36,6 +36,7 @@ def strtolines(str):
def make_unicode(data):
return str(data)


def unpack_kwargs(funcname, kwargs, arg_pattern):
rv = {}
kwargs = kwargs.copy()
Expand All @@ -55,7 +56,12 @@ def unpack_kwargs(funcname, kwargs, arg_pattern):
except KeyError as e:
error = True
if error:
raise TypeError('{}() missing 1 required keyword-only argument: \'{}\''.format(funcname, tp))
raise TypeError(
'{}() missing 1 required keyword-only argument: \'{}\''.
format(funcname, tp))
if kwargs:
raise TypeError('{}() got an unexpected keyword argument \'{}\''.format(funcname, next(iter(kwargs.items()))[0]))
raise TypeError(
'{}() got an unexpected keyword argument \'{}\''.format(
funcname,
next(iter(kwargs.items()))[0]))
return rv
79 changes: 56 additions & 23 deletions cyaron/vector.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
# coding=utf8
"""
"""

from .utils import *
import random
from enum import IntEnum
from typing import Union, Tuple, List, Set

from .utils import list_like


class VectorRandomMode(IntEnum):
Expand All @@ -11,37 +15,48 @@ class VectorRandomMode(IntEnum):
float = 2


_Number = Union[int, float]


class Vector:
"""A class for generating random vectors"""

IntVector = List[List[int]]
FloatVector = List[List[float]]

@staticmethod
def random(num: int = 5, position_range: list = None, mode: VectorRandomMode = 0, **kwargs):
def random(
num: int = 5,
position_range: Union[List[Union[_Number, Tuple[_Number, _Number]]],
None] = None,
mode: VectorRandomMode = VectorRandomMode.unique,
) -> Union[IntVector, FloatVector]:
"""
brief : generating n random vectors in limited space
param :
# num : the number of vectors
# position_range : a list of limits for each dimension
# single number x represents range (0, x)
# list [x, y] or tuple (x, y) represents range (x, y)
# mode : the mode vectors generate, see Enum Class VectorRandomMode
Generate `num` random vectors in limited space
Args:
num: the number of vectors
position_range: a list of limits for each dimension
single number x represents range (0, x)
list [x, y] or tuple (x, y) represents range (x, y)
mode: the mode vectors generate, see Enum Class VectorRandomMode
"""
if position_range is None:
position_range = [10]

if num > 1000000:
raise Exception("num no more than 1e6")
if not list_like(position_range):
raise Exception("the 2nd param must be a list or tuple")
raise TypeError("the 2nd param must be a list or tuple")

dimension = len(position_range)

offset = []
length = []
offset: List[_Number] = []
length: List[_Number] = []

vector_space = 1
for i in range(0, dimension):
if list_like(position_range[i]):
if position_range[i][1] < position_range[i][0]:
raise Exception("upper-bound should larger than lower-bound")
raise ValueError(
"upper-bound should be larger than lower-bound")
offset.append(position_range[i][0])
length.append(position_range[i][1] - position_range[i][0])
else:
Expand All @@ -50,16 +65,22 @@ def random(num: int = 5, position_range: list = None, mode: VectorRandomMode = 0
vector_space *= (length[i] + 1)

if mode == VectorRandomMode.unique and num > vector_space:
raise Exception("1st param is so large that CYaRon can not generate unique vectors")
raise ValueError(
"1st param is so large that CYaRon can not generate unique vectors"
)

result = []
if mode == VectorRandomMode.repeatable:
result = [[random.randint(x, 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, 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()
num_set: Set[int] = set()
result: List[List[int]] = []
for i in range(0, num):
while True:
rand = random.randint(0, vector_space - 1)
Expand All @@ -74,7 +95,9 @@ def random(num: int = 5, position_range: list = None, mode: VectorRandomMode = 0
# generate 0~vector_space and shuffle
rand_arr = list(range(0, vector_space))
random.shuffle(rand_arr)
result = [Vector.get_vector(dimension, length, x) for x in rand_arr[:num]]
result = [
Vector.get_vector(dimension, length, x) for x in rand_arr[:num]
]

for x in result:
for i in range(dimension):
Expand All @@ -84,7 +107,17 @@ def random(num: int = 5, position_range: list = None, mode: VectorRandomMode = 0

@staticmethod
def get_vector(dimension: int, position_range: list, hashcode: int):
tmp = []
"""
Generates a vector based on the given dimension, position range, and hashcode.
Args:
dimension (int): The number of dimensions for the vector.
position_range (list): A list of integers specifying the range for each dimension.
hashcode (int): A hashcode used to generate the vector.
Returns:
list: A list representing the generated vector.
"""

tmp: List[int] = []
for i in range(0, dimension):
tmp.append(hashcode % (position_range[i] + 1))
hashcode //= (position_range[i] + 1)
Expand Down

0 comments on commit ed5bacd

Please sign in to comment.