Skip to content

Commit

Permalink
Fix some type issue
Browse files Browse the repository at this point in the history
  • Loading branch information
Mr-Python-in-China committed Oct 7, 2024
1 parent ba37d80 commit c92f60d
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 35 deletions.
45 changes: 25 additions & 20 deletions cyaron/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import re
import subprocess
import tempfile
from typing import Union, overload
from typing import Union, overload, Optional
from io import IOBase
from . import log
from .utils import list_like, make_unicode
Expand All @@ -19,29 +19,30 @@ class IO:

@overload
def __init__(self,
input_file: Union[IOBase, str, int, None] = None,
output_file: Union[IOBase, str, int, None] = None,
data_id: Union[str, None] = None,
input_file: Optional[Union[IOBase, str, int]] = None,
output_file: Optional[Union[IOBase, str, int]] = None,
data_id: Optional[int] = None,
disable_output: bool = False):
...

@overload
def __init__(self,
data_id: Union[str, None] = None,
file_prefix: Union[str, None] = None,
input_suffix: Union[str, None] = '.in',
output_suffix: Union[str, None] = '.out',
data_id: Optional[int] = None,
file_prefix: Optional[str] = None,
input_suffix: str = '.in',
output_suffix: str = '.out',
disable_output: bool = False):
...

def __init__(self,
input_file: Union[IOBase, str, int, None] = None,
output_file: Union[IOBase, str, int, None] = None,
data_id: Union[str, None] = None,
file_prefix: Union[str, None] = None,
input_suffix: Union[str, None] = '.in',
output_suffix: Union[str, None] = '.out',
disable_output: bool = False):
def __init__( # type: ignore
self,
input_file: Optional[Union[IOBase, str, int]] = None,
output_file: Optional[Union[IOBase, str, int]] = None,
data_id: Optional[int] = None,
file_prefix: Optional[str] = None,
input_suffix: str = '.in',
output_suffix: str = '.out',
disable_output: bool = False):
"""
Args:
input_file (optional): input file object or filename or file descriptor.
Expand Down Expand Up @@ -216,6 +217,8 @@ def output_gen(self, shell_cmd, time_limit=None):
time_limit: the time limit (seconds) of the command to run.
None means infinity. Defaults to None.
"""
if self.output_file is None:
raise ValueError("Output file is disabled")
self.flush_buffer()
origin_pos = self.input_file.tell()
self.input_file.seek(0)
Expand All @@ -224,16 +227,16 @@ def output_gen(self, shell_cmd, time_limit=None):
shell_cmd,
shell=True,
timeout=time_limit,
stdin=self.input_file,
stdout=self.output_file,
stdin=self.input_file.fileno(),
stdout=self.output_file.fileno(),
universal_newlines=True,
)
else:
subprocess.check_call(
shell_cmd,
shell=True,
stdin=self.input_file,
stdout=self.output_file,
stdin=self.input_file.fileno(),
stdout=self.output_file.fileno(),
universal_newlines=True,
)
self.input_file.seek(origin_pos)
Expand All @@ -248,6 +251,8 @@ def output_write(self, *args, **kwargs):
*args: the elements to write
separator: a string used to separate every element. Defaults to " ".
"""
if self.output_file is None:
raise ValueError("Output file is disabled")
self.__write(self.output_file, *args, **kwargs)

def output_writeln(self, *args, **kwargs):
Expand Down
4 changes: 2 additions & 2 deletions cyaron/sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ class Sequence:

def __init__(self,
formula: Callable[[int, Callable[[int], T]], T],
initial_values: Optional[Union[List[T], Tuple[T, ...],
Dict[int, T]]] = ()):
initial_values: Union[List[T], Tuple[T, ...], Dict[int,
T]] = ()):
"""
Initialize a sequence object.
Parameters:
Expand Down
38 changes: 25 additions & 13 deletions cyaron/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

import random
from enum import IntEnum
from typing import Union, Tuple, List, Set
from typing import Sequence, Union, Tuple, List, Set
from typing import cast as typecast

from .utils import list_like

Expand Down Expand Up @@ -48,28 +49,32 @@ def random(

dimension = len(position_range)

offset: List[_Number] = []
length: List[_Number] = []
offset: Sequence[_Number] = []
length: Sequence[_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]:
now_position_range = position_range[i]
if isinstance(now_position_range, tuple):
if now_position_range[1] < now_position_range[0]:
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])
offset.append(now_position_range[0])
length.append(now_position_range[1] - now_position_range[0])
else:
offset.append(0)
length.append(position_range[i])
length.append(now_position_range)
vector_space *= (length[i] + 1)

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

result: Union[List[List[int]], List[List[float]]]
if mode == VectorRandomMode.repeatable:
offset = typecast(Sequence[int], offset)
length = typecast(Sequence[int], length)
result = [[
random.randint(x, x + y) for x, y in zip(offset, length)
] for _ in range(num)]
Expand All @@ -79,8 +84,11 @@ def random(
] for _ in range(num)]
elif mode == VectorRandomMode.unique and vector_space > 5 * num:
# O(NlogN)
offset = typecast(Sequence[int], offset)
length = typecast(Sequence[int], length)
vector_space = typecast(int, vector_space)
num_set: Set[int] = set()
result: List[List[int]] = []
result = typecast(List[List[int]], [])
for i in range(0, num):
while True:
rand = random.randint(0, vector_space - 1)
Expand All @@ -93,6 +101,9 @@ def random(
result.append(tmp)
else:
# generate 0~vector_space and shuffle
offset = typecast(Sequence[int], offset)
length = typecast(Sequence[int], length)
vector_space = typecast(int, vector_space)
rand_arr = list(range(0, vector_space))
random.shuffle(rand_arr)
result = [
Expand All @@ -106,13 +117,14 @@ def random(
return result

@staticmethod
def get_vector(dimension: int, position_range: list, hashcode: int):
def get_vector(dimension: int, position_range: Sequence[int],
hashcode: int):
"""
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.
dimension: The number of dimensions for the vector.
position_range: A list of integers specifying the range for each dimension.
hashcode: A hashcode used to generate the vector.
Returns:
list: A list representing the generated vector.
"""
Expand Down

0 comments on commit c92f60d

Please sign in to comment.