Skip to content

Commit ed5bacd

Browse files
Format,write notes, and add type hints for vector.py
1 parent 3b8fba8 commit ed5bacd

File tree

4 files changed

+67
-28
lines changed

4 files changed

+67
-28
lines changed

.pylintrc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
[MASTER]
22
py-version=3.5
3-
disable=R0902,R0913,R0917
3+
disable=R0902,R0913,R0917,R0912

cyaron/io.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616

1717
class IO:
18-
"""Class IO: IO tool class. It will process the input and output files."""
18+
"""IO tool class. It will process the input and output files."""
1919

2020
@overload
2121
def __init__(self,

cyaron/utils.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def list_like(data):
1010
Judge whether the object data is like a list or a tuple.
1111
object data -> the data to judge
1212
"""
13-
return isinstance(data, tuple) or isinstance(data, list)
13+
return isinstance(data, (tuple, list))
1414

1515

1616
def int_like(data):
@@ -36,6 +36,7 @@ def strtolines(str):
3636
def make_unicode(data):
3737
return str(data)
3838

39+
3940
def unpack_kwargs(funcname, kwargs, arg_pattern):
4041
rv = {}
4142
kwargs = kwargs.copy()
@@ -55,7 +56,12 @@ def unpack_kwargs(funcname, kwargs, arg_pattern):
5556
except KeyError as e:
5657
error = True
5758
if error:
58-
raise TypeError('{}() missing 1 required keyword-only argument: \'{}\''.format(funcname, tp))
59+
raise TypeError(
60+
'{}() missing 1 required keyword-only argument: \'{}\''.
61+
format(funcname, tp))
5962
if kwargs:
60-
raise TypeError('{}() got an unexpected keyword argument \'{}\''.format(funcname, next(iter(kwargs.items()))[0]))
63+
raise TypeError(
64+
'{}() got an unexpected keyword argument \'{}\''.format(
65+
funcname,
66+
next(iter(kwargs.items()))[0]))
6167
return rv

cyaron/vector.py

Lines changed: 56 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
# coding=utf8
1+
"""
2+
3+
"""
24

3-
from .utils import *
45
import random
56
from enum import IntEnum
7+
from typing import Union, Tuple, List, Set
8+
9+
from .utils import list_like
610

711

812
class VectorRandomMode(IntEnum):
@@ -11,37 +15,48 @@ class VectorRandomMode(IntEnum):
1115
float = 2
1216

1317

18+
_Number = Union[int, float]
19+
20+
1421
class Vector:
22+
"""A class for generating random vectors"""
23+
24+
IntVector = List[List[int]]
25+
FloatVector = List[List[float]]
1526

1627
@staticmethod
17-
def random(num: int = 5, position_range: list = None, mode: VectorRandomMode = 0, **kwargs):
28+
def random(
29+
num: int = 5,
30+
position_range: Union[List[Union[_Number, Tuple[_Number, _Number]]],
31+
None] = None,
32+
mode: VectorRandomMode = VectorRandomMode.unique,
33+
) -> Union[IntVector, FloatVector]:
1834
"""
19-
brief : generating n random vectors in limited space
20-
param :
21-
# num : the number of vectors
22-
# position_range : a list of limits for each dimension
23-
# single number x represents range (0, x)
24-
# list [x, y] or tuple (x, y) represents range (x, y)
25-
# mode : the mode vectors generate, see Enum Class VectorRandomMode
35+
Generate `num` random vectors in limited space
36+
Args:
37+
num: the number of vectors
38+
position_range: a list of limits for each dimension
39+
single number x represents range (0, x)
40+
list [x, y] or tuple (x, y) represents range (x, y)
41+
mode: the mode vectors generate, see Enum Class VectorRandomMode
2642
"""
2743
if position_range is None:
2844
position_range = [10]
2945

30-
if num > 1000000:
31-
raise Exception("num no more than 1e6")
3246
if not list_like(position_range):
33-
raise Exception("the 2nd param must be a list or tuple")
47+
raise TypeError("the 2nd param must be a list or tuple")
3448

3549
dimension = len(position_range)
3650

37-
offset = []
38-
length = []
51+
offset: List[_Number] = []
52+
length: List[_Number] = []
3953

4054
vector_space = 1
4155
for i in range(0, dimension):
4256
if list_like(position_range[i]):
4357
if position_range[i][1] < position_range[i][0]:
44-
raise Exception("upper-bound should larger than lower-bound")
58+
raise ValueError(
59+
"upper-bound should be larger than lower-bound")
4560
offset.append(position_range[i][0])
4661
length.append(position_range[i][1] - position_range[i][0])
4762
else:
@@ -50,16 +65,22 @@ def random(num: int = 5, position_range: list = None, mode: VectorRandomMode = 0
5065
vector_space *= (length[i] + 1)
5166

5267
if mode == VectorRandomMode.unique and num > vector_space:
53-
raise Exception("1st param is so large that CYaRon can not generate unique vectors")
68+
raise ValueError(
69+
"1st param is so large that CYaRon can not generate unique vectors"
70+
)
5471

55-
result = []
5672
if mode == VectorRandomMode.repeatable:
57-
result = [[random.randint(x, x + y) for x, y in zip(offset, length)] for _ in range(num)]
73+
result = [[
74+
random.randint(x, x + y) for x, y in zip(offset, length)
75+
] for _ in range(num)]
5876
elif mode == VectorRandomMode.float:
59-
result = [[random.uniform(x, x + y) for x, y in zip(offset, length)] for _ in range(num)]
77+
result = [[
78+
random.uniform(x, x + y) for x, y in zip(offset, length)
79+
] for _ in range(num)]
6080
elif mode == VectorRandomMode.unique and vector_space > 5 * num:
6181
# O(NlogN)
62-
num_set = set()
82+
num_set: Set[int] = set()
83+
result: List[List[int]] = []
6384
for i in range(0, num):
6485
while True:
6586
rand = random.randint(0, vector_space - 1)
@@ -74,7 +95,9 @@ def random(num: int = 5, position_range: list = None, mode: VectorRandomMode = 0
7495
# generate 0~vector_space and shuffle
7596
rand_arr = list(range(0, vector_space))
7697
random.shuffle(rand_arr)
77-
result = [Vector.get_vector(dimension, length, x) for x in rand_arr[:num]]
98+
result = [
99+
Vector.get_vector(dimension, length, x) for x in rand_arr[:num]
100+
]
78101

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

85108
@staticmethod
86109
def get_vector(dimension: int, position_range: list, hashcode: int):
87-
tmp = []
110+
"""
111+
Generates a vector based on the given dimension, position range, and hashcode.
112+
Args:
113+
dimension (int): The number of dimensions for the vector.
114+
position_range (list): A list of integers specifying the range for each dimension.
115+
hashcode (int): A hashcode used to generate the vector.
116+
Returns:
117+
list: A list representing the generated vector.
118+
"""
119+
120+
tmp: List[int] = []
88121
for i in range(0, dimension):
89122
tmp.append(hashcode % (position_range[i] + 1))
90123
hashcode //= (position_range[i] + 1)

0 commit comments

Comments
 (0)