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