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