1 | from decimal import Decimal, ROUND_FLOOR
|
---|
2 | from typing import List
|
---|
3 |
|
---|
4 | from tudelft.utilities.immutablelist.AbstractImmutableList import AbstractImmutableList
|
---|
5 |
|
---|
6 |
|
---|
7 | class Range(AbstractImmutableList[Decimal]):
|
---|
8 | '''
|
---|
9 | Range is an immutable list of numbers from low to high with given step size.
|
---|
10 | This class is compatible with pyson.
|
---|
11 | '''
|
---|
12 | def __init__(self, low:Decimal, high: Decimal, step:Decimal):
|
---|
13 | '''
|
---|
14 | @param low the first element in the range
|
---|
15 | @param high the maximum value of the range. The last item
|
---|
16 | in the range may be below or equal to this.
|
---|
17 | @param step this value is added to low repeatedly to give all elements
|
---|
18 | '''
|
---|
19 | assert isinstance(low, Decimal) and isinstance(high, Decimal) \
|
---|
20 | and isinstance(step, Decimal)
|
---|
21 | self._low=low
|
---|
22 | self._high=high
|
---|
23 | self._step=step
|
---|
24 |
|
---|
25 | def getLow(self)->Decimal:
|
---|
26 | return self._low
|
---|
27 |
|
---|
28 | def getHigh(self)->Decimal:
|
---|
29 | return self._high
|
---|
30 |
|
---|
31 | def getStep(self)->Decimal:
|
---|
32 | return self._step
|
---|
33 |
|
---|
34 | def get(self, index:int)-> Decimal:
|
---|
35 | return self._low+ self._step * index
|
---|
36 |
|
---|
37 | def size(self) -> int:
|
---|
38 | if self._low > self._high:
|
---|
39 | return 0
|
---|
40 | return 1 + \
|
---|
41 | int( (( self._high - self._low )/self._step) .quantize(Decimal('1'), rounding=ROUND_FLOOR) )
|
---|
42 |
|
---|
43 | def contains(self, value:Decimal) -> bool:
|
---|
44 | '''
|
---|
45 | @param value value to look for
|
---|
46 | @return Returns true iff this contains the specified value.
|
---|
47 | '''
|
---|
48 | return value>=self._low and value<= self._high and (value-self._low) % self._step == 0
|
---|
49 |
|
---|
50 |
|
---|
51 | def __eq__(self, other)->bool:
|
---|
52 | return isinstance(other, self.__class__) and \
|
---|
53 | self._low == other._low and \
|
---|
54 | self._high == other._high and\
|
---|
55 | self._step == other._step
|
---|
56 |
|
---|
57 | def __repr__(self):
|
---|
58 | return "Range["+str(self._low)+","+str(self._high)+","+str(self._step)+"]"
|
---|
59 |
|
---|
60 | def __hash__(self):
|
---|
61 | return hash((self._low, self._high, self._step))
|
---|
62 | |
---|