[222] | 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):
|
---|
[243] | 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)
|
---|
[222] | 20 | self._low=low
|
---|
| 21 | self._high=high
|
---|
| 22 | self._step=step
|
---|
| 23 |
|
---|
[243] | 24 | def getLow(self)->Decimal:
|
---|
[222] | 25 | return self._low
|
---|
| 26 |
|
---|
[243] | 27 | def getHigh(self)->Decimal:
|
---|
[222] | 28 | return self._high
|
---|
| 29 |
|
---|
[243] | 30 | def getStep(self)->Decimal:
|
---|
[222] | 31 | return self._step
|
---|
| 32 |
|
---|
[243] | 33 | def get(self, index:int)-> Decimal:
|
---|
[222] | 34 | return self._low+ self._step * index
|
---|
| 35 |
|
---|
[243] | 36 | def size(self) -> int:
|
---|
[222] | 37 | if self._low > self._high:
|
---|
[243] | 38 | return 0
|
---|
| 39 | return 1 + \
|
---|
| 40 | int( (( self._high - self._low )/self._step) .quantize(Decimal('1'), rounding=ROUND_FLOOR) )
|
---|
[661] | 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 | '''
|
---|
[662] | 47 | return value>=self._low and value<= self._high and (value-self._low) % self._step == 0
|
---|
[661] | 48 |
|
---|
| 49 |
|
---|
[222] | 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):
|
---|
[243] | 60 | return hash((self._low, self._high, self._step))
|
---|
[222] | 61 | |
---|